| 1 | # ABSTRACT: karr-foundation per-repo state -- lock file, JSON state, cooldown backoff | ||
| 2 | |||
| 3 | package App::karr::Foundation::State; | ||
| 4 | our $VERSION = '0.602'; | ||
| 5 | use Moo; | ||
| 6 | use Path::Tiny; | ||
| 7 | use Fcntl qw( LOCK_EX LOCK_NB LOCK_UN ); | ||
| 8 | use App::karr::Encoding qw( json_encode json_decode ); | ||
| 9 | use Try::Tiny; | ||
| 10 | |||
| 11 | |||
| 12 | |||
| 13 | has foundation => ( | ||
| 14 | is => 'ro', | ||
| 15 | weak_ref => 1, | ||
| 16 | required => 1, | ||
| 17 | ); | ||
| 18 | |||
| 19 | # --------------------------------------------------------------------------- | ||
| 20 | # Lock file — flock-gated, holds the work, not the watcher | ||
| 21 | # --------------------------------------------------------------------------- | ||
| 22 | # | ||
| 23 | # The lock names the work, not the foundation process: a stale foundation (a | ||
| 24 | # SIGTERM-restart, a segfault, a hung shell waiting for a child that has been | ||
| 25 | # reaped by init) used to leave a .karr.lock naming a pid nobody could ever | ||
| 26 | # own again, while the lock file was the only thing keeping the next tick from | ||
| 27 | # starting a second agent (#162, #163). The gate is now flock(2): the | ||
| 28 | # foundation that holds the exclusive lock on the file holds the board, and | ||
| 29 | # the recorded pid/pgid are evidence (for `karr-foundation --status` and the | ||
| 30 | # SIGTERM handler) rather than authority. | ||
| 31 | # | ||
| 32 | # File contents are JSON: { pid, pgid, agent_pid, started }. flock on an open | ||
| 33 | # fd is the source of truth: the Foundation instance keeps an open fd for the | ||
| 34 | # lifetime of the lock and only closes it on release. A stale .karr.lock — one | ||
| 35 | # nobody flocks — is not held even if the recorded pid is alive in some other | ||
| 36 | # context, and a process whose recorded pid matches $$ but which never flock'd | ||
| 37 | # the file has no claim. | ||
| 38 | # | ||
| 39 | # Two ticks that overlap, the normal case while a max_runtime-sized drain is | ||
| 40 | # still running and cron fires again, now race on flock: exactly one wins, | ||
| 41 | # exactly one is told to skip (#162). The "tight while-loop" the POD used to | ||
| 42 | # recommend no longer relies on the lock file as a polite signal — under the | ||
| 43 | # new semantics two consecutive tight loops cannot both pass _lock_held, | ||
| 44 | # because the second one will lose the flock race. That is intentional and | ||
| 45 | # desired. | ||
| 46 | |||
| 47 | sub _lock_file { path( $_[1]->child('.karr.lock') ) } | ||
| 48 | |||
| 49 | # Read the lock metadata — pid/pgid/agent_pid/started — without taking the | ||
| 50 | # flock. Used by the SIGTERM handler in Foundation.pm and by --status, which | ||
| 51 | # have to look at the file without acquiring it. Unreadable files (missing, | ||
| 52 | # corrupt) yield undef rather than dying — the caller can fall back to "no | ||
| 53 | # live agent" if it wants. | ||
| 54 | # | ||
| 55 | # We do NOT use Path::Tiny's slurp here: slurp opens a second fd and calls | ||
| 56 | # flock() LOCK_EX on it (blocking). When this foundation still holds the | ||
| 57 | # lock through its own fd, the second fd's flock blocks forever — the | ||
| 58 | # documented quirk is that flock per-open-file-description can deadlock | ||
| 59 | # when one process owns the only exclusive lock. Use raw sysread instead; | ||
| 60 | # the flock doesn't block our own reads, only other flocks. | ||
| 61 | sub _read_lock_metadata { | ||
| 62 | my ( $self, $repo ) = @_; | ||
| 63 | my $lock = $self->_lock_file( $repo ); | ||
| 64 | return undef unless $lock->exists; | ||
| 65 | open( my $fh, '<', "$lock" ) or return undef; | ||
| 66 | my $raw = ''; | ||
| 67 | my $buf = ''; | ||
| 68 | while (1) { | ||
| 69 | my $n = sysread( $fh, $buf, 4096 ); | ||
| 70 | last unless defined $n && $n; | ||
| 71 | $raw .= $buf; | ||
| 72 | last if $n < 4096; | ||
| 73 | } | ||
| 74 | close $fh; | ||
| 75 | return undef unless length $raw; | ||
| 76 | my $data = try { json_decode($raw) } catch { return undef }; | ||
| 77 | return ref $data eq 'HASH' ? $data : undef; | ||
| 78 | } | ||
| 79 | |||
| 80 | # Held iff someone holds the flock. We probe with LOCK_EX LOCK_NB: on success | ||
| 81 | # the lock is stale (no holder), we release and report 0; on EWOULDBLOCK | ||
| 82 | # someone else owns it and we report 1. A file we can read but not flock is | ||
| 83 | # held; a file we can read and flock is not. Missing files are not held. | ||
| 84 | sub _lock_held { | ||
| 85 | my ( $self, $repo ) = @_; | ||
| 86 | my $lock = $self->_lock_file( $repo ); | ||
| 87 | return 0 unless $lock->exists; | ||
| 88 | open( my $fh, '<', "$lock" ) or do { | ||
| 89 | # Unlinked by another tick that just released; the next acquire will | ||
| 90 | # recreate it. Treat as not held. | ||
| 91 | return 0; | ||
| 92 | }; | ||
| 93 | if ( flock( $fh, LOCK_EX | LOCK_NB ) ) { | ||
| 94 | flock( $fh, LOCK_UN ); | ||
| 95 | close $fh; | ||
| 96 | return 0; | ||
| 97 | } | ||
| 98 | close $fh; | ||
| 99 | return 1; | ||
| 100 | } | ||
| 101 | |||
| 102 | # Try to take the lock. Returns 1 on success, 0 on EWOULDBLOCK (someone else | ||
| 103 | # holds it). On success the Foundation instance keeps an open fd to the file | ||
| 104 | # in $self->foundation->{_lock_fhs}{$repo}; the fd holds the flock until | ||
| 105 | # _release_lock closes it. Without that open fd the flock would evaporate on | ||
| 106 | # close — flock is per-process-per-fd, not per-path. | ||
| 107 | sub _acquire_lock { | ||
| 108 | my ( $self, $repo, %meta ) = @_; | ||
| 109 | return 1 if $self->foundation->dry_run; | ||
| 110 | my $lock = $self->_lock_file( $repo ); | ||
| 111 | open( my $fh, '>>', "$lock" ) or return 0; | ||
| 112 | unless ( flock( $fh, LOCK_EX | LOCK_NB ) ) { | ||
| 113 | close $fh; | ||
| 114 | return 0; | ||
| 115 | } | ||
| 116 | # We hold the exclusive lock. Truncate so a stale write from a previous | ||
| 117 | # holder doesn't survive the upgrade — flock is process-scoped to us now, | ||
| 118 | # but truncate ensures our write below is the only content. | ||
| 119 | truncate $fh, 0; | ||
| 120 | seek $fh, 0, 0; | ||
| 121 | my $pid = $meta{pid} // $$; | ||
| 122 | my $data = { | ||
| 123 | pid => $pid, | ||
| 124 | pgid => $meta{pgid}, | ||
| 125 | agent_pid => $meta{agent_pid}, | ||
| 126 | started => $meta{started} // time, | ||
| 127 | }; | ||
| 128 | $fh->autoflush(1); | ||
| 129 | $fh->print( json_encode($data) ); | ||
| 130 | # Stash the open fd so the flock outlives this method. Closing the original | ||
| 131 | # would drop the flock immediately and the next probe would find the lock | ||
| 132 | # free. Foundation's instance attribute owns the fds until _release_lock. | ||
| 133 | $self->foundation->_keep_lock_fh( $repo, $fh ); | ||
| 134 | return 1; | ||
| 135 | } | ||
| 136 | |||
| 137 | # Release iff we still own it. The Foundation holds the lock fd in its | ||
| 138 | # instance state; we recover it, close it (drops the flock — flock is per | ||
| 139 | # open file description), then read the recorded pid and unlink. We do NOT | ||
| 140 | # re-flock the same file from a second fd: on Linux flock locks are per open | ||
| 141 | # file description, not per process, so a second fd from the same process | ||
| 142 | # attempting LOCK_EX|LOCK_NB against the first fd's LOCK_EX fails with | ||
| 143 | # EWOULDBLOCK and we would skip the unlink — locking ourselves out forever. | ||
| 144 | # The fd is the proof we held the lock; trust it, and trust the recorded pid | ||
| 145 | # in the file to catch the only case it could be wrong (a recycled pid | ||
| 146 | # matching $$ by accident). | ||
| 147 | # | ||
| 148 | # Order matters: close the fd BEFORE reading the file. With the lock fd | ||
| 149 | # still open and flock'd, Path::Tiny's slurp_utf8 opens its own fd and then | ||
| 150 | # blocks indefinitely on read (a documented quirk of certain filesystems when | ||
| 151 | # a single process holds the only flock). Releasing the flock first makes | ||
| 152 | # the read return immediately. | ||
| 153 | sub _release_lock { | ||
| 154 | my ( $self, $repo ) = @_; | ||
| 155 | return if $self->foundation->dry_run; | ||
| 156 | my $lock = $self->_lock_file( $repo ); | ||
| 157 | my $fh = $self->foundation->_take_lock_fh( $repo ); | ||
| 158 | return unless $fh; | ||
| 159 | close $fh; | ||
| 160 | my $meta = $self->_read_lock_metadata( $repo ); | ||
| 161 | if ( !$meta || !defined $meta->{pid} || $meta->{pid} == $$ ) { | ||
| 162 | $lock->remove if $lock->exists; | ||
| 163 | } | ||
| 164 | # else: the file's recorded pid is not ours — somebody else's foundation | ||
| 165 | # took the file out from under us (would only happen if _lock_held passed | ||
| 166 | # spuriously, which flock LOCK_EX|LOCK_NB at acquire guarantees cannot). | ||
| 167 | # Leave the file alone; the next tick that successfully acquires will see | ||
| 168 | # its own pid and release its own lock. | ||
| 169 | return; | ||
| 170 | } | ||
| 171 | |||
| 172 | # Force-release for the SIGTERM handler: we are on the way out and cannot | ||
| 173 | # trust the normal release path to run. Same rule — the open fd is proof, | ||
| 174 | # the recorded pid is the second check — but without writing to .karr.log | ||
| 175 | # or opening anything else. The handler is a process about to die, so | ||
| 176 | # leaving a stale fd behind doesn't matter. | ||
| 177 | sub _force_release_lock { | ||
| 178 | my ( $self, $repo ) = @_; | ||
| 179 | return if $self->foundation->dry_run; | ||
| 180 | my $lock = $self->_lock_file( $repo ); | ||
| 181 | my $fh = $self->foundation->_take_lock_fh( $repo ); | ||
| 182 | return unless $fh; | ||
| 183 | close $fh; | ||
| 184 | my $meta = $self->_read_lock_metadata( $repo ); | ||
| 185 | if ( $meta && defined $meta->{pid} && $meta->{pid} != $$ ) { | ||
| 186 | # Same protection as _release_lock: a recycled pid is not us. | ||
| 187 | return; | ||
| 188 | } | ||
| 189 | $lock->remove if $lock->exists; | ||
| 190 | return; | ||
| 191 | } | ||
| 192 | |||
| 193 | # --------------------------------------------------------------------------- | ||
| 194 | # State file | ||
| 195 | # --------------------------------------------------------------------------- | ||
| 196 | |||
| 197 | sub _state_file { path( $_[1]->child('.karr.state') ) } | ||
| 198 | |||
| 199 | sub _state_get { | ||
| 200 | my ( $self, $repo, $key ) = @_; | ||
| 201 | my $state_file = $self->_state_file( $repo ); | ||
| 202 | return undef unless $state_file->exists; | ||
| 203 | my $data = try { json_decode( $state_file->slurp_utf8 ) } catch { {} }; | ||
| 204 | return $data->{$key}; | ||
| 205 | } | ||
| 206 | |||
| 207 | sub _state_set { | ||
| 208 | my ( $self, $repo, %kv ) = @_; | ||
| 209 | return if $self->foundation->dry_run; | ||
| 210 | my $state_file = $self->_state_file( $repo ); | ||
| 211 | my $data = {}; | ||
| 212 | if ( $state_file->exists ) { | ||
| 213 | $data = try { json_decode( $state_file->slurp_utf8 ) } catch { {} }; | ||
| 214 | } | ||
| 215 | $data->{$_} = $kv{$_} for keys %kv; | ||
| 216 | $state_file->spew_utf8( json_encode( $data ) ); | ||
| 217 | } | ||
| 218 | |||
| 219 | # Drop keys entirely rather than null them: .karr.state is read by an operator | ||
| 220 | # as much as by karr, and a key that is still there describes the last run. A | ||
| 221 | # last_error left behind by a run three cooldowns ago, sitting next to | ||
| 222 | # last_exit: 0, reads as a contradiction nobody can resolve (#160). | ||
| 223 | sub _state_del { | ||
| 224 | my ( $self, $repo, @keys ) = @_; | ||
| 225 | return if $self->foundation->dry_run; | ||
| 226 | my $state_file = $self->_state_file( $repo ); | ||
| 227 | return unless $state_file->exists; | ||
| 228 | my $data = try { json_decode( $state_file->slurp_utf8 ) } catch { {} }; | ||
| 229 | my $gone = 0; | ||
| 230 | for my $key ( @keys ) { | ||
| 231 | next unless exists $data->{$key}; | ||
| 232 | delete $data->{$key}; | ||
| 233 | $gone++; | ||
| 234 | } | ||
| 235 | return unless $gone; | ||
| 236 | $state_file->spew_utf8( json_encode( $data ) ); | ||
| 237 | } | ||
| 238 | |||
| 239 | # --------------------------------------------------------------------------- | ||
| 240 | # Exponential cooldown (1, 2, 4, 8, ... minutes, capped) on common-error | ||
| 241 | # --------------------------------------------------------------------------- | ||
| 242 | |||
| 243 | sub _cooldown_active { | ||
| 244 | my ( $self, $repo ) = @_; | ||
| 245 | my $until = $self->_state_get( $repo, 'cooldown_until' ) or return 0; | ||
| 246 | return time < $until ? 1 : 0; | ||
| 247 | } | ||
| 248 | |||
| 249 | sub _set_cooldown { | ||
| 250 | my ( $self, $repo, $karr ) = @_; | ||
| 251 | return if $self->foundation->dry_run; | ||
| 252 | my $base = $karr->{cooldown_base} // 1; # minutes at level 0 | ||
| 253 | my $cap = $karr->{cooldown_max} // 64; # minutes ceiling | ||
| 254 | my $level = $self->_state_get( $repo, 'cooldown_level' ) // 0; | ||
| 255 | my $minutes = $base * ( 2 ** $level ); | ||
| 256 | $minutes = $cap if $minutes > $cap; | ||
| 257 | $self->_state_set( $repo, | ||
| 258 | cooldown_level => $level + 1, | ||
| 259 | cooldown_until => time + $minutes * 60, | ||
| 260 | ); | ||
| 261 | $self->foundation->_say_verbose( "cooldown $repo -- ${minutes}m (level " . ( $level + 1 ) . ")" ); | ||
| 262 | return $minutes; | ||
| 263 | } | ||
| 264 | |||
| 265 | sub _clear_cooldown { | ||
| 266 | my ( $self, $repo ) = @_; | ||
| 267 | return if $self->foundation->dry_run; | ||
| 268 | my $level = $self->_state_get( $repo, 'cooldown_level' ) // 0; | ||
| 269 | return unless $level; | ||
| 270 | $self->_state_set( $repo, cooldown_level => 0, cooldown_until => 0 ); | ||
| 271 | } | ||
| 272 | |||
| 273 | # --------------------------------------------------------------------------- | ||
| 274 | # Attempt counter (per task, persisted in .karr.state) | ||
| 275 | # --------------------------------------------------------------------------- | ||
| 276 | |||
| 277 | sub _bump_attempts { | ||
| 278 | my ( $self, $repo, $id ) = @_; | ||
| 279 | my $a = $self->_state_get( $repo, 'attempts' ) // {}; | ||
| 280 | $a->{$id} = ( $a->{$id} // 0 ) + 1; | ||
| 281 | $self->_state_set( $repo, attempts => $a ); | ||
| 282 | return $a->{$id}; | ||
| 283 | } | ||
| 284 | |||
| 285 | sub _reset_attempts { | ||
| 286 | my ( $self, $repo, $id ) = @_; | ||
| 287 | my $a = $self->_state_get( $repo, 'attempts' ) // {}; | ||
| 288 | return unless exists $a->{$id}; | ||
| 289 | delete $a->{$id}; | ||
| 290 | $self->_state_set( $repo, attempts => $a ); | ||
| 291 | } | ||
| 292 | |||
| 293 | 1; | ||
| 294 | |||
| 295 | __END__ |