2
0
mirror of https://github.com/xcat2/xcat-core.git synced 2026-11-27 12:52:16 +00:00

fix(xcat-core): the vendored lock can put two builds in one build lock

Resyncs build-utils/lib/XCAT/NFSLock.pm with xcat-dep, where the defect was
found and fixed. The module reclaimed a stranded lock.borrow by path after
validating its metadata, and rmdir names a path and not the inode that was
validated, so a contender stopped between the two steps removed whatever
was at the path when it resumed. Two builds of one target could then both
hold the build lock, which is the collision the lock exists to prevent.

The borrow is numbered now, and a transition whose taker is provably dead
is ended by creating the next generation rather than by removing the one
that was validated. A process removes only a generation it created and
still holds.

acquire_lock_dir's comment said the retry budget covers reclaiming a borrow
with no metadata over two attempts. That rule is withdrawn, because a live
taker can pause for any length of time before its first write. A take-over
needs one attempt; the budget leaves two for a contended lock.

Depends on xcat-dep/#93, which carries the same change to the original.

Signed-off-by: Daniel Hilst <392820+dhilst@users.noreply.github.com>
This commit is contained in:
Daniel Hilst
2026-10-22 13:35:49 -03:00
parent c14a30d978
commit db8f387fb5
2 changed files with 152 additions and 118 deletions
+2 -3
View File
@@ -667,9 +667,8 @@ sub acquire_lock_dir {
$what = $lockdir unless defined $what;
$held = '' unless defined $held;
# Three attempts: reaping a stranded borrow takes two, because a borrow with no metadata is
# reclaimed only when two of them find it unchanged, and the take-over takes the third.
# Builds must fail fast rather than queue, so the budget stops there.
# Three attempts. A take-over needs one; the budget leaves two for a contended lock, where
# another build is superseding the same dead owner. Builds must fail fast rather than queue.
my $lock = eval {
XCAT::NFSLock->acquire($lockdir, retries => 2, label => $what, quiet => 1);
};
+150 -115
View File
@@ -19,9 +19,21 @@ package XCAT::NFSLock;
# Names in this module
# lock.d the lock path given to acquire
# lock.d/metadata the metadata of the owner
# lock.borrow <lock path>.borrow, beside lock.d
# lock.borrow <lock path>.borrow, beside lock.d: borrow generation 0
# lock.borrow.N borrow generation N, N >= 1
# R, T, δ the options retries, delay and jitter
#
# Borrow generations
# The borrow is the mutex for an ownership transition. The one safe way to end a transition its
# own taker did not end is to SUPERSEDE it, never to remove it. rmdir names a path and not the
# inode that was validated, so a reaper that validates a borrow and then removes it deletes
# whatever is at that path when it runs, which can be a live taker's borrow.
#
# The taker is the process holding the HIGHEST generation present. A contender supersedes
# generation N by mkdir(lock.borrow.<N+1>), and only after N's metadata proves its taker dead.
# mkdir is exclusive, so exactly one contender wins a generation. A process removes only a
# generation it created and still holds, so no process can delete another process's claim.
#
# Assumptions
# 1. mkdir(path) is atomic and exclusive among contenders, and successful
# namespace changes eventually become visible.
@@ -29,15 +41,15 @@ package XCAT::NFSLock;
# Cloned VMs and images can share it by accident unless it is regenerated.
# 3. Metadata writes eventually become readable completely and consistently.
# 4. A host never declares one of its own live process incarnations dead.
# 5. A process MAY die at any point, lock.borrow included. The borrow carries the same
# metadata as the lock, so a borrow whose taker is provably dead is recovered by the same
# rule. A borrow with NO metadata is left by the earlier protocol, or by a death between
# mkdir and the first write; no version of this protocol holds one for more than
# milliseconds, so one that two attempts find unchanged is held by nobody.
# A lock.d with no metadata is a different case and acquire never recovers it. The build
# lock in xcat-core wrote no metadata and held lock.d for the whole build, so no fact on
# disk tells that holder from a dead one. Only sweep_stranded removes those, and only when
# the caller claims the root exclusively.
# 5. A process MAY die at any point, a borrow generation included. The borrow carries the same
# metadata as the lock, so a generation whose taker is provably dead is superseded by the
# next generation.
# A generation with no valid metadata is a taker that died, or paused, between its mkdir and
# its first write. Nothing can prove that taker dead, so it blocks every later acquire, and
# only sweep_stranded removes it, under an exclusive claim on the root.
# A lock.d with no valid metadata blocks the same way, for the same reason. The build lock in
# xcat-core wrote no metadata and held lock.d for the whole build, so no fact on disk tells
# that holder from a dead one.
# 6. A crashed worker leaves recoverable state. The owning host eventually
# returns and retries. Eventually one worker and its release complete.
# 7. All participants follow the protocol.
@@ -52,11 +64,8 @@ package XCAT::NFSLock;
#
# If the metadata is missing, cannot be parsed or hashed, or the hash does not
# match, assume a partial or inconsistent read and retry. Never infer stale
# ownership from invalid metadata.
#
# One case is not a partial read: a lock.borrow with no metadata FILE, unchanged over two
# attempts. Two attempts of one acquire or release are at least T seconds apart, and no
# participant holds a metadata-less borrow that long, so nobody holds it.
# ownership from invalid metadata. A directory unchanged for some time is not evidence either:
# a live participant can pause for any length of time between two writes.
#
# Retry
# R = max retries, T = base delay, δ = jitter
@@ -77,9 +86,12 @@ package XCAT::NFSLock;
# - invalid or missing: retry
# - different machine-id: retry
# - same host: save the observed ownership identity
# 3. mkdir lock.borrow, then write valid metadata into it
# - EEXIST: recover the borrow if its metadata proves its taker dead, or if it has no
# metadata file and two attempts found it unchanged; then retry
# 3. Take the borrow, then write valid metadata into it. Taking it is mkdir of generation 0
# when no generation exists, and otherwise mkdir of the generation after the highest one
# whose metadata proves its taker dead.
# - the highest generation has no valid metadata, names another machine, or names a live
# process: retry
# - another contender won that generation: retry
# - other failure: retry
# 4. Read and validate the metadata again.
# - invalid, missing, or ownership identity changed: rmdir lock.borrow, retry
@@ -89,9 +101,8 @@ package XCAT::NFSLock;
# 6. Replace the metadata with the identity of this process and a fresh token.
# 7. rmdir lock.borrow
# 8. Call the worker.
# 9. mkdir lock.borrow, then write valid metadata into it
# - EEXIST: recover the borrow by the same rule as step 3
# - failure: sleep(T + rand(-δ, δ)), retry step 9
# 9. Take the borrow as in step 3, then write valid metadata into it
# - not available: sleep(T + rand(-δ, δ)), retry step 9, R times at most, then give up
# 10. unlink lock.d/metadata
# 11. rmdir lock.d (the actual unlock)
# 12. rmdir lock.borrow
@@ -101,9 +112,9 @@ package XCAT::NFSLock;
# lock.d absent => acquirable
# invalid metadata => retry only
# different machine-id => never recover here
# lock.borrow exists => ownership transition or release in progress, unless its metadata
# proves its taker dead, or it has no metadata file and two attempts
# found it unchanged
# a borrow generation => a transition or a release is in progress, unless the highest
# generation's metadata proves its taker dead
# removal => a process removes only a generation it created and still holds
#
# Steps 1 to 7 are acquire, step 8 is the caller, steps 9 to 12 are release.
# release does steps 10 and 11 only when the metadata names this acquisition.
@@ -111,8 +122,9 @@ package XCAT::NFSLock;
# Log
# Unless quiet => 1, each lock event prints one line to the selected output handle:
# [nfslock] <UTC time> <host> pid=<pid> <event> <label> <lock.d> [detail]
# Events: acquired (step 1), took-over (step 6), reaped-borrow (step 3 or 9), wait (a retry),
# released (step 11), release-skipped. The time has milliseconds, so the lines of two hosts sort into one order.
# Events: acquired (step 1), took-over (step 6), took-borrow (a superseded generation),
# wait (a retry), released (step 11), release-skipped. The time has milliseconds, so the lines
# of two hosts sort into one order.
use strict;
use warnings;
@@ -176,27 +188,27 @@ sub acquire {
my ($name) = ($path // '') =~ m{(?:\A|/)([^/]+)\z};
die "Invalid $label path '" . ($path // '') . "'\n"
if !defined($name) || $name eq '.' || $name eq '..';
my $abs = _absolute($path);
my $borrow = "$abs.borrow";
my $self = bless {
path => $abs,
label => $label,
pid => $$,
delay => $delay,
jitter => $jitter,
quiet => $opt{quiet} ? 1 : 0,
my $abs = _absolute($path);
my $self = bless {
path => $abs,
label => $label,
pid => $$,
delay => $delay,
jitter => $jitter,
retries => $retries,
quiet => $opt{quiet} ? 1 : 0,
}, $class;
my $here = _here();
my $seen;
# Directories this acquire has already observed, for _unchanged. The attempts of one acquire
# are one delay apart, which is what makes "unchanged" mean "untouched for T seconds".
my %observed_before;
for (my $count = 0 ; ; $count++) {
# Step 1.
if (mkdir($abs)) {
$self->{identity} = this_process();
if (eval { _write_metadata($abs, $self->{identity}); 1 }) {
my $mine = this_process();
if (eval { _write_metadata($abs, $mine); 1 }) {
# Only now. release acts on identity, and DESTROY calls release, so an acquire
# that failed must leave nothing for the destructor to act on.
$self->{identity} = $mine;
$self->_log('acquired');
return $self;
}
@@ -211,17 +223,25 @@ sub acquire {
my $observed = _read_metadata($abs);
$seen = $observed if defined($observed);
if (defined($observed) && $observed->{'machine-id'} eq $here->{'machine-id'}) {
if (mkdir($borrow)) {
# Steps 3 to 7.
# Step 3.
my ($generation, $why) = _take_borrow($abs, $here);
if (defined($generation)) {
my $borrow = _borrow_path($abs, $generation);
$self->_log('took-borrow', $why) if $generation;
_at('borrow-created');
# Steps 4 to 7.
my $taken = eval {
# The borrow names its taker, so a taker that dies here can be recovered
# below. Written before the death check, which is where a SIGKILL lands.
# The borrow names its taker, so a taker that dies here is superseded by the
# next generation. Written before the death check, where a SIGKILL lands.
_write_metadata($borrow, this_process());
_at('borrow-held');
my $again = _read_metadata($abs);
return 0 unless defined($again) && _key($again) eq _key($observed);
return 0 unless owner_is_dead($again, $here);
$self->{identity} = this_process();
_write_metadata($abs, $self->{identity});
my $mine = this_process();
_at('before-commit');
_write_metadata($abs, $mine);
$self->{identity} = $mine;
1;
};
my $error = $@;
@@ -232,12 +252,6 @@ sub acquire {
return $self;
}
}
elsif ($! == EEXIST) {
# Step 3 fails for as long as the borrow exists, and that skips steps 4 to 7, so
# a taker killed here blocked the lock for every later acquire.
my ($reaped, $why) = _reap_borrow($borrow, $here, \%observed_before);
$self->_log('reaped-borrow', $why) if $reaped;
}
}
last if $count >= $retries;
@@ -273,14 +287,19 @@ sub release {
my ($self) = @_;
return 0 if $self->{released} || $$ != $self->{pid};
# acquire blesses $self before it holds anything, and sets identity only once it does. An
# acquire that dies would otherwise reach the wait loop below and never leave it.
# acquire that dies would otherwise reach the wait loop below.
return 0 unless defined($self->{identity});
my $path = $self->{path};
my $borrow = "$path.borrow";
my %observed_before;
while (1) {
my $path = $self->{path};
my $here = _here();
my $why = 'no attempt was made';
# Bounded. DESTROY reaches this loop, so an unbounded wait turns a lock whose metadata
# cannot be validated into a process that never returns its own error.
for (my $count = 0 ; ; $count++) {
# Step 9.
if (mkdir($borrow)) {
my ($generation, $reason) = _take_borrow($path, $here);
$why = $reason;
if (defined($generation)) {
my $borrow = _borrow_path($path, $generation);
eval { _write_metadata($borrow, $self->{identity}); 1 };
my $current = _read_metadata($path);
if (defined($current) && _key($current) eq _key($self->{identity})) {
@@ -300,15 +319,14 @@ sub release {
$self->_log('release-skipped', defined($current) ? 'owned by ' . _describe($current) : 'no lock.d');
return 0;
}
$why = 'the lock metadata cannot be validated';
}
elsif ($! != EEXIST) {
warn "Cannot create $borrow: $!\n";
if ($count >= $self->{retries}) {
$self->{released} = 1;
$self->_log('release-skipped', "gave up: $why");
warn "Cannot release $path after $count retries: $why\n";
return 0;
}
else {
# A taker killed while holding the borrow would otherwise block this release for ever.
_reap_borrow($borrow, _here(), \%observed_before);
}
_sleep(_wait($self->{delay}, $self->{jitter}));
}
}
@@ -474,43 +492,58 @@ sub _drop_borrow {
return rmdir($borrow);
}
# _reap_borrow: remove a borrow no live taker holds, and say what was found.
#
# Two rules. A borrow with valid metadata is recovered when that metadata names this machine and a
# process this host can prove dead -- the rule the lock itself uses. A borrow with no metadata
# FILE is recovered when two attempts find it unchanged: the earlier protocol wrote none, and no
# version of this one holds a metadata-less borrow for more than milliseconds. A borrow whose
# metadata file exists but does not validate may be a partial read, so it is left alone.
#
# $seen carries the observations across the attempts of one acquire or release.
# Returns ($removed, $why).
sub _reap_borrow {
my ($borrow, $here, $seen) = @_;
$here //= _here();
my $taker = _read_metadata($borrow);
unless (defined($taker)) {
return (0, 'metadata invalid') if -e "$borrow/metadata";
return (0, 'no metadata, first attempt') unless _unchanged($seen, $borrow);
_drop_borrow($borrow);
return (1, 'no metadata, and two attempts found the borrow unchanged');
}
return (0, 'other machine') unless $taker->{'machine-id'} eq $here->{'machine-id'};
return (0, 'taker is alive') unless owner_is_dead($taker, $here);
_drop_borrow($borrow);
return (1, "taker pid $taker->{pid} is dead");
# _at: a point in the protocol a test can stop a process at, to force one interleaving instead of
# depending on timing. It does nothing here.
sub _at { return }
sub _borrow_path {
my ($abs, $generation) = @_;
return $generation ? "$abs.borrow.$generation" : "$abs.borrow";
}
# _unchanged: true when $dir carries the identity and mtime of an earlier observation in $seen.
# Creating or removing a file in a directory moves its mtime, so an unchanged directory had
# nothing written in it between the two observations.
sub _unchanged {
my ($seen, $dir) = @_;
return 0 unless defined($seen);
my @stat = stat($dir) or return 0;
my $mark = join(':', @stat[0, 1, 9]);
my $before = $seen->{$dir};
$seen->{$dir} = $mark;
return defined($before) && $before eq $mark ? 1 : 0;
# _borrow_top: the highest borrow generation present for this lock, or undef when none is.
sub _borrow_top {
my ($abs) = @_;
opendir(my $dh, dirname($abs)) or return undef;
my $name = basename($abs);
my $top;
while (defined(my $entry = readdir($dh))) {
next unless $entry =~ /\A\Q$name\E\.borrow(?:\.([0-9]+))?\z/;
my $generation = defined($1) ? $1 + 0 : 0;
$top = $generation if !defined($top) || $generation > $top;
}
closedir($dh);
return $top;
}
# _take_borrow: become the taker of the ownership transition, or say why not.
#
# It never removes a generation. A transition whose taker is provably dead is ended by creating
# the NEXT generation, because rmdir names a path and not the inode that was validated: a reaper
# that validated a dead taker's borrow and then removed it by path could remove a live taker's
# borrow instead, and two processes then took over one lock.
#
# Returns ($generation, $why), or (undef, $why) when the borrow is not available.
sub _take_borrow {
my ($abs, $here) = @_;
my $top = _borrow_top($abs);
unless (defined($top)) {
_at('before-create');
return (0, 'created the borrow') if mkdir(_borrow_path($abs, 0));
return (undef, 'another process created the borrow') if $! == EEXIST;
return (undef, "cannot create the borrow: $!");
}
my $taker = _read_metadata(_borrow_path($abs, $top));
return (undef, "generation $top holds no valid metadata") unless defined($taker);
return (undef, "generation $top is held by machine $taker->{'machine-id'}")
unless $taker->{'machine-id'} eq $here->{'machine-id'};
return (undef, "generation $top is held by live pid $taker->{pid}")
unless owner_is_dead($taker, $here);
_at('before-supersede');
my $next = $top + 1;
return ($next, "superseded generation $top, held by dead pid $taker->{pid}")
if mkdir(_borrow_path($abs, $next));
return (undef, "another process superseded generation $top");
}
sub _key {
@@ -623,11 +656,12 @@ sub DESTROY {
Descriptions:
Remove lock state that a killed process left behind, under one root.
Assumption 5 says a process cannot die while it holds lock.borrow. Under this CI it does:
the run policy aborts a condemned run and Jenkins sends SIGTERM. A borrow stranded that
way makes its lock PERMANENTLY unacquirable, because step 3 is mkdir(lock.borrow) and a
failure there skips steps 4 to 7 -- so the dead owner is never evicted and every later
acquire waits out its retries. xcat-ci #80 stranded one, and #81 exited 17 on it.
A process killed during a transition leaves a borrow generation behind. Under this CI
that happens: the run policy aborts a condemned run and Jenkins sends SIGTERM. acquire
supersedes a generation whose metadata proves its taker dead, so that one needs no
sweep. A generation with NO valid metadata is a taker killed, or paused, between its
mkdir and its first write, and nothing can prove that taker dead, so it blocks every
later acquire. xcat-ci #80 stranded one, and #81 exited 17 on it.
A dead owner's lock.d is removed as well. acquire would take it over, so this only saves
the wait.
@@ -635,19 +669,19 @@ sub DESTROY {
It never removes a lock owned by a live process or by another machine, and it never
infers staleness from a metadata file it cannot validate.
A lock.d with NO metadata file is removed only with exclusive => 1. acquire refuses one,
because the build lock in xcat-core wrote no metadata and held lock.d for the whole
build, so no fact on disk tells that holder from a dead one. Only a caller that claims
the root exclusively can say it is abandoned.
A lock.d or a borrow generation with NO valid metadata is removed only with
exclusive => 1. acquire refuses both, because nothing on disk tells a dead holder from a
live one that has not written yet. Only a caller that claims the root exclusively can
say either is abandoned.
Arguments:
$root: the directory to walk
$here: hash ref with machine-id, boot-id and start_of, as owner_is_dead takes
%opt: exclusive => 1 when the caller holds the run's exclusive claim on $root, so no
build and no take-over can be in progress. Only then is a borrow removed, and
only then a lock.d with no metadata: a borrow is otherwise a transition that is
milliseconds from finishing, and removing it lets two takers rewrite one
metadata file.
build and no transition can be in progress. Only then is a borrow generation
removed, and only then a lock.d with no metadata: a generation is otherwise a
transition that is milliseconds from finishing, and removing it lets two takers
rewrite one metadata file.
Returns:
A list of hash refs: path, action (removed or kept), why.
@@ -666,14 +700,15 @@ sub sweep_stranded {
# Both spellings. mockbuild-all.pl names a cell lock <dir>/.<arch>.lock, while
# cluster-test.pl names its build lock <repo>/.build.lock.d and sbuild-all.pl uses
# .sbuild-all.<arch>.nfslock. A matcher for '.lock' alone swept only the first.
push @found, $d if $d =~ /\.(?:lock(?:\.d)?|nfslock)(?:\.borrow)?\z/;
push @found, $d if $d =~ /\.(?:lock(?:\.d)?|nfslock)(?:\.borrow(?:\.[0-9]+)?)?\z/;
},
}, $root) if -d $root;
my @report;
# A borrow before its own lock: removing the borrow is what lets the lock be taken over.
for my $d (sort { ($b =~ /\.borrow\z/ ? 1 : 0) <=> ($a =~ /\.borrow\z/ ? 1 : 0) || $a cmp $b } @found) {
if ($d =~ /\.borrow\z/) {
for my $d (sort { ($b =~ /\.borrow(?:\.[0-9]+)?\z/ ? 1 : 0) <=> ($a =~ /\.borrow(?:\.[0-9]+)?\z/ ? 1 : 0)
|| $a cmp $b } @found) {
if ($d =~ /\.borrow(?:\.[0-9]+)?\z/) {
unless ($opt{exclusive}) {
push @report, { path => $d, action => 'kept',
why => 'a borrow may be a live take-over; no exclusive claim' };