blib/lib/App/karr/Foundation/Executor.pm untested

filter: Statementstmt 0.0% 0 / 332 Branchbran 0.0% 0 / 172 Conditioncond 0.0% 0 / 91 MC/DCmcdc 0.0% 0 / 50 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 712 CC 87 SCAR 40.0
CC
87
Cov
0%
_do_step
156.0
facts_for
132.0
_question_verdict
72.0
CRAP 54.5
1 # ABSTRACT: karr-foundation chain executor -- picks a ready step, runs it, writes its state back
2  
3 package App::karr::Foundation::Executor;
4 our $VERSION = '0.602';
5 use Moo;
6 use POSIX qw( strftime );
7 use Sys::Hostname ();
8 use Try::Tiny;
9 use Path::Tiny;
10 use App::karr::Error qw( user_error clean_error );
11 use App::karr::Git;
12 use App::karr::BoardStore;
13 use App::karr::CrossBoard;
14  
15  
16  
17 has foundation => (
18 is => 'ro',
19 weak_ref => 1,
20 required => 1,
21 );
22  
23  
24 has store => (
25 is => 'lazy',
26 builder => '_build_store',
27 );
28  
29 sub _build_store {
30 my ( $self ) = @_;
31 return $self->foundation->_chain_store // user_error(
32 'No usable hub repository: the chain lives in '
33 . 'refs/karr-foundation/chain/* in the fleet hub, so name one with '
34 . "'hub: /path/to/repo' in " . $self->foundation->_config_path );
35 }
36  
37 sub _now { return strftime( '%Y-%m-%dT%H:%M:%SZ', gmtime() ) }
38  
39 sub _say { my ( $self, $msg ) = @_; print "$msg\n"; return }
40  
41 # ---------------------------------------------------------------------------
42 # The tick
43 # ---------------------------------------------------------------------------
44  
45  
46 sub run {
47 my ( $self ) = @_;
48 my $store = $self->store;
49  
50 return $self->_preview if $self->foundation->dry_run;
51  
52 # Before anything reads the chain (#186/#190). A tick that skipped this and
53 # ran from its own clone would be executing a plan another machine has
54 # already worked through.
55 return 1 unless $self->_pull;
56  
57 my $header = $store->header;
58 my $chain = $header->{id};
59 unless ( defined $chain ) {
60 $self->_say( 'No chain in ' . $self->_hub . " -- nothing to execute "
61 . '(a planner writes one into refs/karr-foundation/chain/)' );
62 return 0;
63 }
64  
65 my $run = $store->new_run_id;
66 $store->log_run( $run, event => 'start', chain => $chain,
67 host => Sys::Hostname::hostname(), pid => $$ );
68  
69 my ( %seen, %tally, @planner );
70 while ( 1 ) {
71 my @ready = grep { !$seen{ $self->_key($_) } } $store->ready_steps;
72 last unless @ready;
73 for my $step ( @ready ) {
74 $seen{ $self->_key($step) } = 1;
75 my $verdict = $self->_do_step( $run, $step );
76 $tally{ $verdict->{state} }++;
77 push @planner, [ $step->{id}, $verdict->{planner} ] if $verdict->{planner};
78 }
79 # A fresh view before the next round, for the same reason as the first
80 # pull: the steps this round unblocked are ready for every machine, not
81 # only for this one.
82 last unless $self->_pull;
83 }
84  
85 $store->log_run( $run, event => 'end', chain => $chain,
86 map { ( $_ => $tally{$_} ) } sort keys %tally );
87 $self->_push;
88  
89 # The one place the three chain-side deviations meet (#210). A kind: plan
90 # step, an escalate_to_ai question and a step gone stale each record that the
91 # planner is wanted where they meet it, and each has always ended up here --
92 # so this is where the coordination agent is told, and it is told once for
93 # the whole tick rather than once per entry. F<karr-foundation> makes the
94 # call itself (App::karr::Foundation::_run_chain), after this method has
95 # finished: a planner called from inside the loop would be planning against a
96 # chain this tick was still working through.
97 $self->foundation->_coordinator->want( step => $_->[0], reason => $_->[1] )
98 for @planner;
99  
100 $self->_report( $chain, \%tally, \@planner );
101 return 0;
102 }
103  
104 # One step is identified by the chain it belongs to as well as by its id: a
105 # planner that replaces the chain between two rounds may reuse an id, and a
106 # tick that had already seen the old step would skip the new one for ever.
107 sub _key {
108 my ( $self, $step ) = @_;
109 return ( $step->{chain} // '-' ) . '/' . ( $step->{id} // '-' );
110 }
111  
112 sub _hub {
113 my ( $self ) = @_;
114 my $git = $self->foundation->_hub_git or return '(no hub)';
115 return $git->dir;
116 }
117  
118 sub _report {
119 my ( $self, $chain, $tally, $planner ) = @_;
120 my @parts = map { "$tally->{$_} $_" } sort keys %$tally;
121 $self->_say( "chain $chain: " . ( @parts ? join( ', ', @parts ) : 'nothing ready' ) );
122 return unless @$planner;
123  
124 # Said out loud rather than only written into the run log: whoever reads a
125 # tick has to see that the chain stopped short of something, and where this
126 # fleet has no coordination agent the operator IS the planner.
127 $self->_say( 'the planner is wanted for step(s) '
128 . join( ', ', map { "$_->[0] ($_->[1])" } @$planner )
129 . ( $self->foundation->_coordinator->configured
130 ? " -- the coordination agent is called at the end of this tick"
131 : " -- no planner runs from here yet; re-plan the chain" ) );
132 return;
133 }
134  
135 # What --dry-run answers: the ready set and what each precheck says about it
136 # right now. Nothing is pulled either -- a dry run that fetched would be the
137 # one part of a tick it still performed.
138 sub _preview {
139 my ( $self ) = @_;
140 my $store = $self->store;
141 my $chain = $store->header->{id};
142 unless ( defined $chain ) {
143 $self->_say( 'No chain in ' . $self->_hub . " -- nothing to execute" );
144 return 0;
145 }
146 my @ready = $store->ready_steps;
147 $self->_say( "chain $chain: " . scalar(@ready) . ' step(s) ready (dry run, '
148 . 'nothing pulled, claimed or executed)' );
149 for my $step ( @ready ) {
150 my $facts = $self->facts_for( $step );
151 my $holds = $store->precheck_holds( $step, $facts );
152 $self->_say( ' ' . $self->_describe($step) . ': '
153 . ( $holds ? $self->_would_do( $step, $facts )
154 : $self->_stale_reason( $step, $facts ) ) );
155 }
156 return 0;
157 }
158  
159 # What a dry run says about a step whose precheck holds. "would run" for the
160 # kinds that run something, and something more exact for a question step, read
161 # off the fact that has already been measured for it: "would run" about a step
162 # that is in fact going to sit and wait would be the one line of this command
163 # nobody could trust afterwards.
164 sub _would_do {
165 my ( $self, $step, $facts ) = @_;
166 return 'would run' unless ( $step->{kind} // '' ) eq 'question';
167 my $state = $facts->{question_state};
168 return "no question in the mailbox names it -- would go stale"
169 unless defined $state;
170 return "its question is answered -- would finish the step"
171 if $state eq 'answered';
172 return "its question is overdue -- the policy on it decides"
173 if $state eq 'overdue';
174 return "its question is unanswered -- would wait";
175 }
176  
177 sub _describe {
178 my ( $self, $step ) = @_;
179 my $what = "step $step->{id} ($step->{kind}";
180 $what .= " $step->{ticket}" if defined $step->{ticket};
181 $what .= ')';
182 $what .= " in $step->{repo}" if defined $step->{repo};
183 return $what;
184 }
185  
186 # ---------------------------------------------------------------------------
187 # One step
188 # ---------------------------------------------------------------------------
189  
190 # Returns { state => done|failed|stale|pending|declined|skipped,
191 # planner => $why_or_undef }. The state is what happened to the step,
192 # not what the command exited with.
193 sub _do_step {
194 my ( $self, $run, $step ) = @_;
195 my $store = $self->store;
196 my $id = $step->{id};
197 my $kind = $step->{kind} // '';
198  
199 # A question step is not executed but resolved, against the mailbox that
200 # lives in the same fleet namespace as the chain. It is dispatched before the
201 # repo check below because it names no repository at all: a question is
202 # fleet-wide, so any machine that can read the chain can resolve it (#200).
203 return $self->_do_question_step( $run, $step ) if $kind eq 'question';
204  
205 # A kind this executor does not run: `kind: plan`, and whatever a later
206 # planner invents. Left pending and unclaimed on purpose -- a plan step waits
207 # for the coordination agent, which is called once at the end of the tick and
208 # not from in here (#210), so this is a deliberate stop and not an omission.
209 # Its dependents wait with it, which is the honest state of a chain that has
210 # reached something nothing here can do.
211 unless ( $kind eq 'ticket' || $kind eq 'shell' ) {
212 $self->_say( $self->_describe($step)
213 . ": left pending -- this foundation runs kind: ticket, "
214 . 'kind: shell and kind: question' );
215 $store->log_run( $run, event => 'step', step => "$id", kind => $kind,
216 state => 'pending', detail => 'kind not executed here' );
217 # Recorded as wanting the planner for the same reason a failure is: a chain
218 # that cannot proceed must not do it quietly. It is the only signal that
219 # exists for a plan step -- nothing here can call the agent that would
220 # write the next chain, so saying that it is wanted is the whole answer.
221 $store->log_run( $run, event => 'planner', step => "$id", policy => 'plan',
222 reason => "kind: $kind is not executed here" );
223 $self->_push;
224 return { state => 'skipped', planner => "kind: $kind is not executed here" };
225 }
226  
227 # A repository this machine does not have is the ordinary case in a fleet:
228 # the chain is shared state, the working copies are not. Nothing is claimed,
229 # nothing is logged, and the machine that does have it runs the step.
230 my $repo = defined $step->{repo} ? path( $step->{repo} ) : undef;
231 unless ( $repo && $repo->is_dir ) {
232 $self->foundation->_say_verbose( $self->_describe($step)
233 . ": not on this machine -- left for one that has it" );
234 return { state => 'skipped' };
235 }
236  
237 # The board, before the facts are measured off it. Without this the precheck
238 # would be evaluated against whatever this clone last happened to fetch,
239 # which is the same mistake the fleet-namespace pull above exists to avoid.
240 return $self->_requeue( $run, $step, 'the board could not be pulled' )
241 unless $self->_pull_board( $repo );
242  
243 my $facts = $self->facts_for( $step );
244  
245 unless ( $store->precheck_holds( $step, $facts ) ) {
246 return $self->_stale( $run, $step, $self->_stale_reason( $step, $facts ) );
247 }
248  
249 # A ticket step whose card is not on the board is a plan that has gone out of
250 # date in the one way a precheck cannot express: there is nothing to be
251 # about. Stale, for the same reason and at the same cost as any other stale
252 # step. Whether the card is blocked or already done is deliberately NOT
253 # asked here -- that is what a precheck is for, and karr does not get to be
254 # cleverer than the plan it was given.
255 if ( $kind eq 'ticket' && !exists $facts->{ticket_status} ) {
256 return $self->_stale( $run, $step,
257 "ticket $step->{ticket} is not on the board in $repo" );
258 }
259  
260 # ----- claim, and publish the claim before any work starts -----
261 return { state => 'declined' } unless $self->_claim( $run, $step,
262 repo => "$repo",
263 ( defined $step->{ticket} ? ( ticket => "$step->{ticket}" ) : () ) );
264  
265 # ----- run it -----
266 my $verdict = $kind eq 'ticket'
267 ? $self->_run_ticket_step( $step, $repo )
268 : $self->_run_shell_step( $step, $repo );
269  
270 return $self->_requeue( $run, $step, $verdict->{detail} )
271 if $verdict->{state} eq 'pending';
272 return $self->_finish( $run, $step, $verdict );
273 }
274  
275 # The claim and the publication of it, shared by every kind that writes a step
276 # back. A method rather than the inline block it started as because the
277 # ordering it implements -- compare-and-swap, then publish, then work -- is what
278 # actually keeps one step to one machine (see L</Pull before reading, push
279 # before working>), and a second copy of it would be a second place to get it
280 # wrong. Returns true when this tick owns the step; a decline has already been
281 # said out loud. %entry is whatever the kind wants in the run log beside the
282 # claim: a repo, a ticket, or for a question nothing at all.
283 sub _claim {
284 my ( $self, $run, $step, %entry ) = @_;
285 my $store = $self->store;
286 my $id = $step->{id};
287  
288 my $claimed = $store->update_step( $id, sub {
289 my ( $current ) = @_;
290 return undef unless ( $current->{state} // 'pending' ) eq 'pending';
291 return undef unless ( $current->{chain} // '' ) eq ( $step->{chain} // '' );
292 $current->{state} = 'running';
293 $current->{started} = _now();
294 $current->{attempts} = ( $current->{attempts} // 0 ) + 1;
295 return $current;
296 } );
297 unless ( $claimed ) {
298 $self->foundation->_say_verbose(
299 $self->_describe($step) . ': taken by another tick' );
300 return 0;
301 }
302  
303 $store->log_run( $run, event => 'step', step => "$id",
304 kind => ( $step->{kind} // '' ), state => 'running', %entry );
305  
306 return 1 if $self->_push;
307  
308 # Nobody else ever saw this claim, so taking it back costs nothing and
309 # leaving it would park the step as `running` on a machine that is not
310 # running it.
311 $store->update_step( $id, sub {
312 my ( $current ) = @_;
313 return undef unless ( $current->{state} // '' ) eq 'running';
314 $current->{state} = 'pending';
315 delete $current->{started};
316 return $current;
317 } );
318 $self->_say( $self->_describe($step)
319 . ": claim could not be published -- left for the next tick" );
320 return 0;
321 }
322  
323 # ---------------------------------------------------------------------------
324 # The two kinds that run something
325 # ---------------------------------------------------------------------------
326  
327 # Into the existing ticket-mode path (#185), which is what makes this a layer
328 # above the repo modes rather than a fourth one: the lock, the cooldown, the
329 # agent availability, the claim discipline, the ownership guard on the
330 # auto-block and the run's own report all come from there. What the chain adds
331 # is which card, and how long it may take.
332 sub _run_ticket_step {
333 my ( $self, $step, $repo ) = @_;
334  
335 my $result = try {
336 $self->foundation->_process_repo( $repo,
337 ticket => $step->{ticket},
338 ( defined $step->{timeout} ? ( timeout => $step->{timeout} ) : () ),
339 );
340 } catch {
341 # A local problem -- a mode this machine cannot read, an agent definition
342 # it does not have -- says nothing about the plan, so the step goes back
343 # rather than down.
344 { outcome => 'skipped', reason => clean_error($_) };
345 };
346  
347 my $outcome = $result->{outcome} // 'error';
348 return { state => 'pending', detail => 'board skipped: ' . ( $result->{reason} // '?' ) }
349 if $outcome eq 'skipped';
350 return { state => 'pending', detail => 'the agent command failed: '
351 . ( $result->{error} // 'common error' ) }
352 if $outcome eq 'common-error';
353 return { state => 'done', outcome => $outcome, exit => $result->{exit},
354 detail => 'the ticket moved' }
355 if $outcome eq 'progress';
356 return { state => 'failed', outcome => $outcome, exit => $result->{exit},
357 detail => "the ticket did not move ($outcome)" };
358 }
359  
360 # A command in a repository, under that repository's own lock and with the
361 # runner's process group, timeout and tee -- the same apparatus the on_drained
362 # hook borrows (#193), and for the same reason: a chain step that builds out of
363 # a working tree must not have another tick's agent walk into it. It runs as
364 # KARR_ROLE=chain, so any karr write it makes lands in its own activity log
365 # rather than counting as an agent's engagement with a card.
366 sub _run_shell_step {
367 my ( $self, $step, $repo ) = @_;
368 my $f = $self->foundation;
369 my $cmd = $step->{command};
370  
371 return { state => 'failed', detail => 'a shell step needs a command' }
372 unless defined $cmd && length $cmd;
373  
374 # The board's own opt-out wins here as it does everywhere else: it is
375 # synchronised board state, and "no automated runs in this repository" does
376 # not become smaller because the run was planned in the hub. Pending, not
377 # failed -- the person who disabled the board is the one who can enable it.
378 return { state => 'pending', detail => 'the board is disabled' }
379 if $f->_board_disabled( $repo );
380  
381 return { state => 'pending', detail => 'the board lock is held' }
382 unless $f->_acquire_lock( $repo );
383  
384 my ( $exit ) = try {
385 $f->_run_command( $repo, $f->_load_karr( $repo ), $cmd, undef, undef,
386 role => 'chain',
387 ( defined $step->{timeout} ? ( max_runtime => $step->{timeout} ) : () ),
388 );
389 } catch {
390 ( -1 );
391 };
392 $f->_release_lock( $repo );
393  
394 return { state => 'done', exit => $exit, detail => 'exit=0' } if $exit == 0;
395 return { state => 'failed', exit => $exit, detail => "exit=$exit" };
396 }
397  
398 # ---------------------------------------------------------------------------
399 # A question step (#200)
400 # ---------------------------------------------------------------------------
401  
402 # Resolve, rather than execute: the planner asked the question, this decides
403 # what its current answer means for the step waiting on it. See L</A question
404 # step resolves a question, it does not ask one> for why the step does not ask
405 # it itself, and what each of the mailbox's three states does here.
406 #
407 # Nothing is pulled and no board is read. The mailbox is
408 # refs/karr-foundation/questions/*, which is the namespace the tick already
409 # pulled before it read the chain (#190/#191) -- one fetch for the plan and the
410 # questions together, which is half the reason they share a namespace.
411 sub _do_question_step {
412 my ( $self, $run, $step ) = @_;
413 my $store = $self->store;
414 my $id = $step->{id};
415  
416 my $facts = $self->facts_for( $step );
417 unless ( $store->precheck_holds( $step, $facts ) ) {
418 return $self->_stale( $run, $step, $self->_stale_reason( $step, $facts ) );
419 }
420  
421 # A ready question step with nothing in the mailbox naming it is a planning
422 # error, and the one thing it must not do is wait quietly for ever: the
423 # question is written before the step can become ready, so an empty mailbox
424 # here means that never happened. Stale, for the same reason and at the same
425 # cost as a ticket step whose card is not on the board. (The mailbox is read
426 # twice on this path, once for the fact and once here; it is a handful of
427 # refs, and the alternative is a public facts_for that takes measurements as
428 # arguments.)
429 my $mailbox = $self->_mailbox;
430 my @asked = $self->_questions_for( $step );
431 return $self->_stale( $run, $step,
432 "no question in the mailbox names step $id -- a question step is "
433 . "asked by the planner ('karr-foundation ask ... --step $id'), it does "
434 . 'not ask itself',
435 'no question was ever asked about it' )
436 unless $mailbox && @asked;
437  
438 my @verdicts = map { $self->_question_verdict( $mailbox, $_ ) } @asked;
439 my @waiting = grep { defined $_->{wait} } @verdicts;
440  
441 if ( @waiting ) {
442 my $detail = join '; ', map { $_->{wait} } @waiting;
443  
444 # Pending and UNCLAIMED: nothing ran, so there is no attempt to count and
445 # no started stamp to write, and the next tick finds the step exactly as
446 # the planner left it. Its dependents wait with it because ready_steps
447 # releases a step only when everything it needs is done; every other branch
448 # of the chain runs, because the tick considers each ready step once and
449 # moves on rather than blocking on this one.
450 $store->log_run( $run, event => 'step', step => "$id", kind => 'question',
451 state => 'pending', detail => $detail );
452  
453 # One planner entry, not one per question: the tick's report names steps,
454 # and the reasons are in the step entry above either way.
455 my ( $planner ) = grep { defined $_->{planner} } @waiting;
456 $store->log_run( $run, event => 'planner', step => "$id",
457 policy => ( $planner->{policy} // 'plan' ), reason => $planner->{planner} )
458 if $planner;
459  
460 $self->_push;
461 $self->_say( $self->_describe($step) . ": left pending -- $detail" );
462 return { state => 'pending',
463 ( $planner ? ( planner => $planner->{planner} ) : () ) };
464 }
465  
466 # Every question naming the step has an answer, so the step is done. The
467 # answers go into the run log and into the step's result, and NOT into a
468 # field of their own on the step: the step schema is the planner's vocabulary
469 # (ChainStore's %STEP_KEY, which would warn about an unknown key anyway), and
470 # an answer copied into it would be the mailbox's schema kept in a second
471 # place -- the same duplication that keeps the question out of the step.
472 #
473 # Claimed like any other step even though resolving does no work: the claim
474 # is what makes exactly one tick write the result and log the answer, instead
475 # of every machine in the fleet logging the same answer on the same tick.
476 return { state => 'declined' } unless $self->_claim( $run, $step );
477 return $self->_finish( $run, $step, { state => 'done',
478 detail => join( '; ', map { $_->{detail} } @verdicts ) } );
479 }
480  
481 # The mailbox, which is in the hub the chain is in. Undef only where there is no
482 # hub at all, and L</store> has already refused the tick by then.
483 sub _mailbox { return $_[0]->foundation->_questions }
484  
485 # The questions a step waits on: the ones whose `step` names it. Walked here
486 # rather than asked of the mailbox through a lookup method of its own, because
487 # the link is one field compared as a string and App::karr::Foundation::Questions
488 # is deliberately ignorant of chains -- it records `step` and never reads it, so
489 # a step-shaped query on it would be chain knowledge in the one class that has
490 # none. Compared stringwise because a step id may be `1` or `release`, and YAML
491 # reads the first back as a number on one side and a string on the other.
492 sub _questions_for {
493 my ( $self, $step ) = @_;
494 my $mailbox = $self->_mailbox or return ();
495 my $id = defined $step->{id} ? "$step->{id}" : '';
496 return () unless length $id;
497 return grep { defined $_->{step} && "$_->{step}" eq $id } $mailbox->questions;
498 }
499  
500 # What one question means for the step waiting on it: an answer to take
501 # (`answer` plus the `detail` that records where it came from) or a reason to
502 # keep waiting (`wait`, and `planner` where waiting is somebody's cue). The
503 # mailbox stops at "what does this resolve to" on purpose -- a mailbox does not
504 # execute chains -- so this is the one place where a state plus a policy becomes
505 # a decision.
506 sub _question_verdict {
507 my ( $self, $mailbox, $q ) = @_;
508 my $id = defined $q->{id} ? $q->{id} : '?';
509 my $r = $mailbox->resolve($q)
510 or return { wait => "question #$id could not be read" };
511  
512 return {
513 answer => $r->{answer},
514 detail => "question #$id answered '$r->{answer}'"
515 . ( defined $r->{answered_by} ? " by $r->{answered_by}" : '' ),
516 } if $r->{state} eq 'answered';
517  
518 my $policy = $r->{policy} // 'block';
519 return { wait => "question #$id is unanswered (policy: $policy)" }
520 if $r->{state} eq 'open';
521  
522 # Overdue: the policy is what the asker wrote down for exactly this moment.
523 if ( $policy eq 'use_default' ) {
524 # resolve() carries the default along as the answer, so a question that
525 # reaches here without one cannot be settled by its own policy at all.
526 # `ask` refuses that combination, which means the ref was hand-written --
527 # a planning error rather than a wait, and recorded as one.
528 return {
529 wait => "question #$id has policy use_default and no default to fall "
530 . 'back on, so its deadline settles nothing',
531 planner => "question #$id cannot be settled by its own policy",
532 } unless defined $r->{answer};
533  
534 return {
535 answer => $r->{answer},
536 detail => "question #$id went unanswered past its deadline; its default "
537 . "'$r->{answer}' stands as the answer",
538 };
539 }
540  
541 # escalate_to_ai is recorded, not resolved. The coordination agent it names is
542 # the judgement layer, and it is called once at the end of the tick (#210) --
543 # never from in here, where it would run inside the resolution of one
544 # question and be called again for the next one. So this policy does what a
545 # `kind: plan` step does: planner wanted, step untouched, a line that says
546 # so. Whatever the agent then decides arrives as an answer in the mailbox,
547 # through the same door a person uses.
548 return {
549 wait => "question #$id is past its deadline and its escalate_to_ai "
550 . 'policy wants the coordination agent',
551 planner => "escalate_to_ai on question #$id",
552 policy => 'escalate_to_ai',
553 } if $policy eq 'escalate_to_ai';
554  
555 # block, the default and the only policy that never invents an answer:
556 # waiting is not a failure of the plan, it IS the plan.
557 return { wait => "question #$id is past its deadline and its block policy "
558 . 'keeps waiting for a person' };
559 }
560  
561 # ---------------------------------------------------------------------------
562 # Writing a step back
563 # ---------------------------------------------------------------------------
564  
565 sub _finish {
566 my ( $self, $run, $step, $verdict ) = @_;
567 my $store = $self->store;
568 my $id = $step->{id};
569 my $state = $verdict->{state};
570  
571 $store->update_step( $id, sub {
572 my ( $current ) = @_;
573 return undef unless ( $current->{state} // '' ) eq 'running';
574 $current->{state} = $state;
575 $current->{finished} = _now();
576 $current->{result} = {
577 at => _now(),
578 run => $run,
579 ( defined $verdict->{outcome} ? ( outcome => $verdict->{outcome} ) : () ),
580 ( defined $verdict->{exit} ? ( exit => $verdict->{exit} ) : () ),
581 ( defined $verdict->{detail} ? ( detail => $verdict->{detail} ) : () ),
582 };
583 return $current;
584 } );
585 $store->log_run( $run, event => 'step', step => "$id", state => $state,
586 ( defined $verdict->{detail} ? ( detail => $verdict->{detail} ) : () ) );
587 $self->_push;
588  
589 $self->_say( $self->_describe($step) . ": $state -- "
590 . ( $verdict->{detail} // '' ) );
591  
592 return { state => $state } unless $state eq 'failed';
593  
594 # on_stall, at the seam. The policy the spec writes is `plan`, and this
595 # executor cannot plan -- so it records that the planner is wanted instead
596 # of pretending, and the dependents of this step simply never become ready
597 # (ready_steps releases a step only when every step it needs is done), which
598 # is the branch pruning itself without anybody computing a cascade.
599 my $policy = $step->{on_stall} // 'plan';
600 $store->log_run( $run, event => 'planner', step => "$id",
601 policy => "$policy", reason => ( $verdict->{detail} // 'the step failed' ) );
602 return { state => $state, planner => "on_stall: $policy" };
603 }
604  
605 # Back to pending: nothing about the plan was learned, so nothing about the
606 # plan is written down. The attempt counter the claim bumped stays as it is --
607 # it is the record of how often this step has been tried, which is what makes
608 # a step that can never run visible to whoever reads the chain.
609 sub _requeue {
610 my ( $self, $run, $step, $detail ) = @_;
611 my $store = $self->store;
612 my $id = $step->{id};
613  
614 $store->update_step( $id, sub {
615 my ( $current ) = @_;
616 return undef if ( $current->{state} // 'pending' ) eq 'pending';
617 $current->{state} = 'pending';
618 delete $current->{started};
619 $current->{result} = { at => _now(), run => $run, detail => $detail };
620 return $current;
621 } );
622 $store->log_run( $run, event => 'step', step => "$id", state => 'pending',
623 detail => $detail );
624 $self->_push;
625 $self->_say( $self->_describe($step) . ": requeued -- $detail" );
626 return { state => 'pending' };
627 }
628  
629 # $summary is the half-line the tick's closing report puts in brackets after
630 # the step id; the reason itself, which is a sentence, goes on the step and into
631 # the run log. Defaulted rather than derived because the caller is the only one
632 # that knows which of the two stale cases this is.
633 sub _stale {
634 my ( $self, $run, $step, $reason, $summary ) = @_;
635 my $store = $self->store;
636 $store->mark_stale( $step->{id}, $reason );
637 $store->log_run( $run, event => 'step', step => "$step->{id}",
638 state => 'stale', detail => $reason );
639 $store->log_run( $run, event => 'planner', step => "$step->{id}",
640 policy => 'plan', reason => $reason );
641 $self->_push;
642 $self->_say( $self->_describe($step) . ": stale -- $reason" );
643 return { state => 'stale',
644 planner => ( $summary // 'the precheck no longer holds' ) };
645 }
646  
647 sub _stale_reason {
648 my ( $self, $step, $facts ) = @_;
649 my $p = $self->store->parse_precheck( $step->{precheck} )
650 or return 'the precheck no longer holds';
651 my $have = exists $facts->{ $p->{fact} }
652 ? "'" . $facts->{ $p->{fact} } . "'"
653 : 'not measurable here';
654 return "precheck '$step->{precheck}' no longer holds ($p->{fact} is $have)";
655 }
656  
657 # ---------------------------------------------------------------------------
658 # Facts
659 # ---------------------------------------------------------------------------
660  
661  
662 sub facts_for {
663 my ( $self, $step ) = @_;
664 my %facts;
665  
666 # Before the board facts, and not under them: a question step names no
667 # repository, so everything below returns early for it.
668 if ( ( $step->{kind} // '' ) eq 'question' ) {
669 my $state = $self->_question_state( $step );
670 $facts{question_state} = $state if defined $state;
671 }
672  
673 my $repo = $step->{repo};
674 return \%facts unless defined $repo && length $repo;
675 return \%facts unless App::karr::Git->new( dir => "$repo" )->is_repo;
676  
677 my $f = $self->foundation;
678 my %states = try { $f->_task_states( $repo ) } catch { () };
679  
680 $facts{board_actionable} =
681 ( grep { $f->_is_actionable( $states{$_} ) } keys %states ) ? 'yes' : 'no';
682  
683 if ( defined $step->{ticket} ) {
684 my $card = $states{ $step->{ticket} };
685 if ( $card ) {
686 $facts{ticket_status} = $card->{status} // '';
687 $facts{ticket_blocked} = $card->{blocked} ? 'yes' : 'no';
688 $facts{ticket_claimed} = defined $card->{claimed_by} ? $card->{claimed_by} : '';
689  
690 my $links = $self->_links_state( $repo, $step->{ticket} );
691 $facts{ticket_links} = $links if defined $links;
692 }
693 }
694 return \%facts;
695 }
696  
697 # One state for a step that may have several questions, and undef where it has
698 # none at all -- absent, so a precheck about it does not hold and the step is
699 # reported rather than left waiting on nothing.
700 sub _question_state {
701 my ( $self, $step ) = @_;
702 my $mailbox = $self->_mailbox or return undef;
703 my @asked = $self->_questions_for( $step ) or return undef;
704  
705 for my $q ( @asked ) {
706 my $r = $mailbox->resolve($q) or next;
707 return $r->{state} if $r->{state} ne 'answered';
708 }
709 return 'answered';
710 }
711  
712 # The far boards, out of the configuration this run has already read -- see
713 # L</A cross-board link is a fact about another board> for why that file and no
714 # other. Built once per executor, so a chain whose steps wait on the same board
715 # opens it once (App::karr::CrossBoard caches the stores it opens).
716 has _fleet => ( is => 'lazy' );
717  
718 sub _build__fleet {
719 my ( $self ) = @_;
720 return App::karr::CrossBoard->new(
721 config_data => $self->foundation->_config_data );
722 }
723  
724 # One value for a card that may carry several cross-board links, and undef --
725 # an absent fact -- where the question cannot be answered on this machine at
726 # all. A card carrying no link is `settled`: nothing elsewhere is holding it,
727 # which is the same shape ticket_blocked has for a card nobody blocked, and
728 # the alternative would make the precheck stop holding the moment
729 # `karr needs --resolve` succeeded and dropped the tag.
730 sub _links_state {
731 my ( $self, $repo, $id ) = @_;
732  
733 # The card itself, not the summary %states carries: the link lives in `tags`
734 # (#192, decision 3), and one ref read for the step's own card is the cheaper
735 # half of the trade against widening a structure three other callers share
736 # for one of them.
737 my $refs = try {
738 my $store = App::karr::BoardStore->new(
739 git => App::karr::Git->new( dir => "$repo" ) );
740 my $card = $store->find_task( $id );
741 $card ? [ App::karr::CrossBoard->needs_of( $card ) ] : undef;
742 } catch { undef };
743 return undef unless $refs;
744 return 'settled' unless @$refs;
745  
746 my $unsettled;
747 for my $ref ( @$refs ) {
748 my $state = try { $self->_fleet->link_state( $ref ) } catch { undef };
749 my $what = ref $state eq 'HASH' ? $state->{state} : undef;
750  
751 # A board this machine cannot place, or a directory that holds no board:
752 # the fact is absent for EVERY link on the card, not merely for this one.
753 # "Is anything elsewhere still holding this card" has no answer here once
754 # one of the answers is missing, and reporting the rest would let a
755 # precheck hold on the strength of a board nobody read.
756 return undef unless defined $what;
757 return undef if $what eq 'unknown-board' || $what eq 'no-board';
758  
759 next if $what eq 'settled';
760 $unsettled //= $what; # `open` or `missing`, first in tag order
761 }
762 return $unsettled // 'settled';
763 }
764  
765 # ---------------------------------------------------------------------------
766 # Transport
767 # ---------------------------------------------------------------------------
768  
769 # The fleet namespace, in. A failure is fatal to the tick rather than a
770 # warning: see L</Pull before reading, push before working>.
771 sub _pull {
772 my ( $self ) = @_;
773 my $ok = try {
774 $self->store->git->pull_foundation;
775 } catch {
776 warn 'karr-foundation: pull of refs/karr-foundation/ failed: '
777 . clean_error($_) . "\n";
778 0;
779 };
780 warn "karr-foundation: refusing to execute the chain without a fresh view "
781 . "of refs/karr-foundation/ -- two machines would run the same step\n"
782 unless $ok;
783 return $ok ? 1 : 0;
784 }
785  
786 # The fleet namespace, out.
787 sub _push {
788 my ( $self ) = @_;
789 my $ok = try {
790 $self->store->git->push_foundation;
791 } catch {
792 warn 'karr-foundation: push of refs/karr-foundation/ failed: '
793 . clean_error($_) . "\n";
794 0;
795 };
796 return $ok ? 1 : 0;
797 }
798  
799 # The step's own board, so its precheck is measured against the fleet's view of
800 # it and not against this clone's last fetch. The ticket-mode path pulls again
801 # on its way in, which is one fetch more than strictly needed and the cheaper
802 # half of the trade: the alternative is a precheck decided on stale refs.
803 sub _pull_board {
804 my ( $self, $repo ) = @_;
805 return try {
806 $self->foundation->_sync_pull( $repo );
807 1;
808 } catch {
809 warn "karr-foundation: pull error in $repo: " . clean_error($_) . "\n";
810 0;
811 };
812 }
813  
814 1;
815  
816 __END__