Debian Codegraph @

lib/Test2/Harness/Runner/Resource.pm

raw
1 package Test2::Harness::Runner::Resource;
2 use strict;
3 use warnings;
4
5 use Term::Table;
6 use Time::HiRes qw/time/;
7 use Test2::Util::Times qw/render_duration/;
8
9 our $VERSION = '1.000179';
10
11 sub scope_global { 0 }
12 sub scope_host { 0 }
13 sub scope_run { 1 }
14
15 sub setup {}
16
17 sub new {
18 my $class = shift;
19 return bless({@_}, $class);
20 }
21
22 sub tick { }
23
24 sub refresh { }
25
26 sub discharge { }
27
28 sub sort_weight {
29 my $class = shift;
30 return 100 if $class->job_limiter;
31 return 50;
32 }
33
34 sub job_limiter { 0 }
35
36 sub job_limiter_max { }
37
38 sub job_limiter_at_max { 0 }
39
40 sub available { -1 }
41
42 sub record { }
43
44 sub assign { }
45
46 sub release { }
47
48 sub cleanup { }
49
50 sub status_data {()}
51
52 sub status_lines {
53 my $self = shift;
54
55 my $data = $self->status_data || return;
56 return unless @$data;
57
58 my $out = "";
59
60 for my $group (@$data) {
61 my $gout = "\n";
62 $gout .= "**** $group->{title} ****\n\n" if defined $group->{title};
63
64 for my $table (@{$group->{tables} || []}) {
65 my $rows = $table->{rows};
66
67 if (my $format = $table->{format}) {
68 my $rows2 = [];
69
70 for my $row (@$rows) {
71 my $row2 = [];
72 for (my $i = 0; $i < @$row; $i++) {
73 my $val = $row->[$i];
74 my $fmt = $format->[$i];
75
76 $val = defined($val) ? render_duration($val) : '--'
77 if $fmt && $fmt eq 'duration';
78
79 push @$row2 => $val;
80 }
81 push @$rows2 => $row2;
82 }
83
84 $rows = $rows2;
85 }
86
87 next unless $rows && @$rows;
88
89 my $tt = Term::Table->new(
90 header => $table->{header},
91 rows => $rows,
92
93 sanitize => 1,
94 collapse => 1,
95 auto_columns => 1,
96
97 %{$table->{term_table_opts} || {}},
98 );
99
100 $gout .= "** $table->{title} **\n" if defined $table->{title};
101 $gout .= "$_\n" for $tt->render;
102 $gout .= "\n";
103 }
104
105 if ($group->{lines} && @{$group->{lines}}) {
106 $gout .= "$_\n" for @{$group->{lines}};
107 $gout .= "\n";
108 }
109
110 $out .= $gout;
111 }
112
113 return $out;
114 }
115
116 1;
117
118 __END__
119
120 =pod
121
122 =encoding UTF-8
123
124 =head1 NAME
125
126 Test2::Harness::Runner::Resource - Base class for resource management classes
127
128 =head1 DESCRIPTION
129
130 Sometimes you have limited resources that must be shared/divided between tests
131 that run concurrently. Resource classes give you a way to leverage the IPC
132 system used by L<Test2::Harness> to manage resource assignment and recovery.
133
134 =head1 SYNOPSIS
135
136 Here is a resource class that simply assigns an integer to each test. It would
137 be possible to re-use integers, but since there are infinite integers this
138 example is kept simple and just always grabs the next one.
139
140 package Test2::Harness::Runner::Resource::Foo;
141 use strict;
142 use warnings;
143
144 use parent 'Test2::Harness::Runner::Resource';
145
146 sub setup {
147 my $class = shift; # NOT AN INSTANCE
148 ...
149 }
150
151 sub available {
152 my $self = shift;
153 my ($task) = @_;
154
155 # There are an infinite amount of integers, so we always return true
156 return 1;
157 }
158
159 sub assign {
160 my $self = shift;
161 my ($task, $state) = @_;
162
163 # Next ID, do not record the state change yet!
164 my $id = 1 + ($self->{ID} //= 0);
165
166 print "ASSIGN: $id = $task->{job_id}\n";
167
168 # 'record' should get whatever we need to record the resource, whatever you
169 # pass in will become the argument to the record() sub below. This may be a
170 # scalar, a hash, an array, etc. It will be serialized to JSON before
171 # record() sees it.
172 $state->{record} = $id;
173
174 # Pass the resource into the test, this can be done as envronment variables
175 # and/or arguments to the test (@ARGV).
176 $state->{env_vars}->{FOO_ID} = $id;
177 push @{$state->{args}} => $id;
178
179 # The return is ignored.
180 return;
181 }
182
183 sub record {
184 my $self = shift;
185 my ($job_id, $record_arg_from_assign) = @_;
186
187 # The ID from $state->{record}->{$pkg} in assign.
188 my $id = $record_arg_from_assign;
189
190 # Update our internal state to reflect the new ID.
191 $self->{ID} = $id;
192
193 # Add a mapping of what job ID gets what integer ID.
194 $self->{ID_TO_JOB_ID}->{$id} = $job_id;
195 $self->{JOB_ID_TO_ID}->{$job_id} = $id;
196
197 print "RECORD: $id = $job_id\n";
198
199 # The return is ignored
200 }
201
202 sub tick {
203 my $self = shift;
204
205 # This is called by only 1 process at a time and gives you a way to do
206 # extra stuff at a regular interval without other processes trying to
207 # do the same work at the same time.
208 # For example, if a database is left in a dirty state after it is
209 # released, you can fire off a cleanup action here knowing no other
210 # process will run it at the same time. You can also be sure no record
211 # messages will be sent while this sub is running as the process it
212 # runs in has a lock.
213
214 ...
215 }
216
217
218 sub release {
219 my $self = shift;
220 my ($job_id) = @_;
221
222 # Clear the internal mapping, the integer ID is now free. Theoretically it
223 # can be reused, but this example is not that complex.
224 my $id = delete $self->{JOB_ID_TO_ID}->{$job_id};
225
226 # This is called for all tests that complete, even if they did not use
227 # this resource, so we return if the job_id is not applicable.
228 return unless defined $id;
229
230 delete $self->{ID_TO_JOB_ID}->{$id};
231
232 print " FREE: $id = $job_id\n";
233
234 # The return is ignored
235 }
236
237 sub cleanup {
238 my $self = shift;
239
240 print "CLEANUP!\n";
241 }
242
243 1;
244
245 The print statements generated will look like this when running 2 tests concurrently:
246
247 yath test -R Foo -j2 t/testA.t t/testB.t
248 [...]
249 (INTERNAL) ASSIGN: 1 = 4F7CF5F6-E43F-11EA-9199-24FCBF610F44
250 (INTERNAL) RECORD: 1 = 4F7CF5F6-E43F-11EA-9199-24FCBF610F44
251 (INTERNAL) ASSIGN: 2 = E19CD98C-E436-11EA-8469-8DF0BF610F44
252 (INTERNAL) RECORD: 2 = E19CD98C-E436-11EA-8469-8DF0BF610F44
253 (INTERNAL) FREE: 1 = 4F7CF5F6-E43F-11EA-9199-24FCBF610F44
254 (INTERNAL) FREE: 2 = E19CD98C-E436-11EA-8469-8DF0BF610F44
255 (INTERNAL) CLEANUP!
256 [...]
257
258 Depending on the tests run the 'FREE' prints may be out of order.
259
260 =head1 WORKFLOW
261
262 =head2 HOW STATE IS MANAGED
263
264 Depending on your preload configuration, yath may have several runners
265 launching tests. If a runner has nothing to do it will lock the queue and try
266 to find the next test that should be run. Only 1 of the runners will be in
267 control of the queue at any given time, but the control of the queue may pass
268 between runners. To manage this there is a mechanism to record messages that
269 allow each runner to maintain a copy of the current state.
270
271 =head2 CHECK IF RESOURCES ARE AVAILABLE
272
273 Each runner will have an instance of your resource class. When the runner is in
274 control of the queue, and wants to designate the next test to run, it will
275 check with the resource classes to make sure the correct resources are
276 available. To do that it will call C<available($task)> on each resource
277 instance.
278
279 The C<$task> will contain the specification for the test, it is a hashref, and
280 you B<SHOULD NOT> modify it. The only key most people care about is the 'file'
281 key, which has the test file that will be run if resources are available.
282
283 If resources are available, or if the specific file does not need the resource,
284 the C<available()> method should return true. If the file does need your
285 resource(s), and none are available, this should return false. If any resource
286 class returns false it means the test cannot be run yet and the runner will
287 look for another test to run.
288
289 If C<available()> returns a negative value (e.g. C<-1>), the resource is
290 considered permanently unavailable. By default the test will be skipped. If
291 the C<--fail-on-resource-skip> runner option is enabled, the test will be
292 marked as a failure instead.
293
294 =head2 ASSIGN A RESOURCE
295
296 If the runner has determined the test can be run, and all necessary resources
297 are available, it will then call C<assign($task, $state)> on all resource class
298 instances. At this time the resource class should decide what resource(s) to
299 assign to the class.
300
301 B<CRITICAL NOTE:> the C<assing()> method B<MUST NOT> alter any internal state
302 on the resource class instance. State modification must wait for the
303 C<record()> method to be called. This is because the C<assign()> method is only
304 called in one runner process, the C<record()> method call will happen in every
305 runner process to insure they all have the same internal state.
306
307 The assign() sub should modify the C<$state> hash, which has 3 keys:
308
309 =over 4
310
311 =item env_vars => {}
312
313 Env vars to set for the test
314
315 =item args => []
316
317 Arguments to pass to the test
318
319 =item record => ...
320
321 Data needed to record the state change for resource classes. Can be a scalar,
322 hashref, arrayref, etc. It will be serialized to JSON to be passed between
323 processes.
324
325 =back
326
327 =head2 RECORD A RESOURCE
328
329 Once a resource is assigned, a message will be sent to all runner processes
330 B<INCLUDING THE ONE THAT DID THE ASSIGN> that says it should call
331 C<record($job_id, $record_val)> on your resource class instance. Your resource
332 class instance must use this to update the state so that once done ALL
333 processes will have the proper internal state.
334
335 The C<$record_val> is whatever you put into C<< $state->{record} >> in the
336 C<assign()> method above.
337
338 =head2 QUEUE MANAGEMENT IS UNLOCKED
339
340 Once the above has been done, queue management will be unlocked. You can be
341 guaranteed that only one process will be run the C<available()>, and
342 C<assign()> sequence at a time, and that they will be called in order, though
343 C<assign()> may not be called if another resource was not available. If
344 C<assign()> is called, you can be guaranteed that all processes, including the
345 one that called C<assign()> will have their C<record()> called with the proper
346 argument B<BEFORE> they try to manage the queue (which is the only place
347 resources are checked or assigned).
348
349 =head2 RELEASE A RESOURCE
350
351 Whenever a process that is using a resource exits, the runner that waits on
352 that process will I<eventually> send an IPC message announcing that the job_id
353 has completed. Every time a job_id completes the C<release($job_id)> method
354 will be called on your resource class in all runner processes. This allows the
355 state to be updated to reflect the freed resource.
356
357 You can be guaranteed that any process that locks the queue to run a new
358 test will eventually see the message. The message may come in during a loop
359 that is checking for resources, in which case the state will not reflect the
360 resource being available, however in such cases the loop will end and be
361 called again later with the message having been received. There will be no
362 deadlock due to a queue manager waiting for the message.
363
364 There are no guarantees about what order resources will be released in.
365
366 =head1 METHODS
367
368 =over 4
369
370 =item $class->setup($settings)
371
372 This will be called once before the runner forks or initialized per-process
373 instances. If you have any "setup once" tasks to initialize resources before
374 tests run this is a good place to do it.
375
376 This runs immediately after plugin setup() methods are called.
377
378 B<NOTE:> Do not rely on recording any global state here, the runner and
379 per-process instances may not be forked from the process that calls setup().
380
381 =item $res = $class->new(settings => $settings);
382
383 A default new method, returns a blessed hashref with the settings key set to
384 the L<Test2::Harness::Settings> instance.
385
386 =item $val = $res->available(\%task)
387
388 B<DO NOT MODIFY ANY INTERNAL STATE IN THIS METHOD>
389
390 B<DO NOT MODIFY THE TASK HASHREF>
391
392 Returns a positive true value if the resource is available.
393
394 Returns false if the resource is not available, but will be in the future (IE
395 in use by another test, but will be free when that test is done).
396
397 Returns a negative value if the resource is not available and never will be.
398 This will cause any tests dependent on the resource to be skipped. If the
399 C<--fail-on-resource-skip> flag is set, these tests will be marked as failures
400 instead of skips.
401
402 The only key in C<\%task> hashref that most resources will care about is the
403 C<'file'> key, which contains the test file to be run.
404
405 =item $res->assign(\%task, \%state)
406
407 B<DO NOT MODIFY THE TASK HASHREF>
408
409 B<DO NOT MODIFY ANY INTERNAL STATE IN THIS METHOD>
410
411 If the task does not need any resources you may simply return.
412
413 If resources are needed you should deduce what resources to assign.
414
415 You should put any data needed to update the internal state of your resource
416 instance in the C<< $state->{record} >> hash key. It B<WILL> be serialized to
417 JSON before being used as an argument to C<record()>.
418
419 $state->{record} = $id;
420
421 If you do not set the 'record' key, or set it to undef, then the C<record()>
422 method will not be called.
423
424 If your tests need to know what resources to use, you may set environment
425 variables and/or command line arguments to pass into the test (C<@ARGV>).
426
427 $state->{env_vars}->{FOO_ID} = $id;
428 push @{$state->{args}} => $id;
429
430 The C<\%state> hashref is used only by your instance, you are free to fully
431 replace the 'env_vars' and 'args' keys. They will eventually be merged into a
432 master state along with those of other resources, but this ref is exclusive to
433 you in this method.
434
435 =item $inst->record($job_id, $record_arg_from_assign)
436
437 B<NOTE: THIS MAY BE CALLED IN MULTIPLE PROCESSES CONCURRENTLY>.
438
439 This will be called in all processes so that your instance can update any
440 internal state.
441
442 The C<$job_id> variable contains the id for the job to which the resource was
443 assigned. You should use this to record any internal state. The $job_id will be
444 passed to C<release()> when the job completes and no longer needs the resource.
445
446 This is intended only for modifying internal state, you should not do anything
447 in this sub that will explode if it is also done in another process at the same
448 time with the same arguments. For example creating a database should not be
449 done here, multiple processes will fight to do the create. The creation, if
450 necessary should be done in C<assign()> which will be called in only one
451 process.
452
453 =item $inst->release($job_id)
454
455 B<NOTE: THIS MAY BE CALLED IN MULTIPLE PROCESSES CONCURRENTLY>.
456
457 This will be called for every test job that completes, even if it did not use
458 this resource. If the job_id did not use the resource you may simply return,
459 otherwise update the internal state to reflect that the resource is no longer
460 in use.
461
462 This is intended only for modifying internal state, you should not do anything
463 in this sub that will explode if it is also done in another process at the same
464 time with the same arguments. For example deleting a database should not be
465 done here, multiple processes will fight to do the delete. C<assign()> is the
466 only method that will be run in a single process, so if a database needs to be
467 cleaned before it can be used you should clean it there. Any final cleanup
468 should be done in C<cleanup()> which will only be called by one process at the
469 very end.
470
471 =item $inst->cleanup()
472
473 This will be called once by the parent runner process just before it exits.
474 This is your chance to do any final cleanup tasks such as deleting databases
475 that are no longer going to be used by tests as no more will be run.
476
477 =item $inst->tick()
478
479 This is called by only 1 process at a time and gives you a way to do extra
480 stuff at a regular interval without other processes trying to do the same work
481 at the same time.
482
483 For example, if a database is left in a dirty state after it is released, you
484 can fire off a cleanup action here knowing no other process will run it at the
485 same time. You can also be sure no record messages will be sent while this sub
486 is running as the process it runs in has a lock.
487
488 =item $inst->refresh()
489
490 Called once before each resource-request loop. This is your chance to do things
491 between each set of requests for resources.
492
493 =item $bool = $inst->job_limiter()
494
495 True if your resource is intended as a job limiter (IE alternative to
496 specifying C<-jN> at the command line).
497
498 =item $int = $inst->job_limiter_max()
499
500 Max number of jobs this will allow at the moment, if this resource is a job
501 limiter.
502
503 =item $bool = $inst->job_limiter_at_max()
504
505 True if the limiter has reached its maximum number of running jobs. This is
506 used to avoid a resource-allocation loop as an optimization.
507
508 =item $number = $inst->sort_weight()
509
510 Used to sort resources if you want them to be checked in a specific order. For
511 most resources this defaults to 50. For job_limiter resources this defaults to
512 100. Lower numbers are sorted to the front of the list, IE they are acquired
513 first, before other resources.
514
515 Job slots are sorted later (100) so that we do not try to grab a job slot if
516 other resources are not available.
517
518 Most of the time order will not matter, however with Shared job slots we have a
519 race with other test runs to get slots, and checking availability is enough to
520 consume a slot, even if other resources are not available.
521
522 =item $string = $inst->status_lines()
523
524 Get a (multi-line) string with status info for this resource. This is used to
525 populate the output for the C<yath resources> command.
526
527 The default implementation will build a string from the data provided by the
528 C<status_data()> method.
529
530 =item $arrayref = $inst->status_data()
531
532 The default implementation returns an empty list.
533
534 This should return status data that looks like this:
535
536 return [
537 {
538 title => "Resource Group Title",
539 tables => [
540 {
541 header => \@columns,
542 rows => [
543 \@row1,
544 \@row2,
545 ],
546
547 # Optional fields
548 ##################
549
550 # formatting for fields in rows
551 format => [undef, undef, 'duration', ...],
552
553 # Title for the table
554 title => "Table Title",
555
556 # Options to pass to Term::Table if/when it the data is used in Term::Table
557 term_table_opts => {...},
558 },
559
560 # Any number of tables is ok
561 {...},
562 ],
563 },
564
565 # Any number of groups is ok
566 {...},
567 ];
568
569 Currently the only supported formats are 'default' (undef), and 'duration'.
570 Duration takes a stamp and tells you how much time has passed since the stamp.
571
572 =back
573
574 =head1 SOURCE
575
576 The source code repository for Test2-Harness can be found at
577 F<http://github.com/Test-More/Test2-Harness/>.
578
579 =head1 MAINTAINERS
580
581 =over 4
582
583 =item Chad Granum E<lt>[email protected]<gt>
584
585 =back
586
587 =head1 AUTHORS
588
589 =over 4
590
591 =item Chad Granum E<lt>[email protected]<gt>
592
593 =back
594
595 =head1 COPYRIGHT
596
597 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
598
599 This program is free software; you can redistribute it and/or
600 modify it under the same terms as Perl itself.
601
602 See F<http://dev.perl.org/licenses/>
603
604 =cut