2
0
mirror of https://github.com/xcat2/xcat-dep.git synced 2026-11-29 13:52:16 +00:00

Merge pull request #93 from VersatusHPC/fix/nfslock-borrow-recovery-rebased

fix(nfslock): a taker that dies holding lock.borrow blocks the lock for ever
This commit is contained in:
Daniel Hilst
2026-10-23 15:04:40 -03:00
committed by GitHub
6 changed files with 1325 additions and 77 deletions
@@ -86,6 +86,7 @@ jobs:
prove -v t/net_dns_rr_types.t
prove -v t/repo-lock-race.t
prove -v t/nfslock.t
prove -v t/nfslock_borrow_recovery.t
prove -v t/genesis_oe_source_dir.t
prove -v -It/lib t/genesis_openembedded_release.t
sudo -E prove -v -It/lib t/genesis_openembedded_consumer.t
+552 -64
View File
@@ -2,6 +2,16 @@ package XCAT::NFSLock;
# NFS lock protocol
#
# Copies
# This module is vendored three times, because no repo installs another's build tooling:
# xcat-dep lib/XCAT/NFSLock.pm (the original)
# xcat-core build-utils/lib/XCAT/NFSLock.pm
# xcat-core-ci-cd ci/lib/XCAT/NFSLock.pm
# The three must stay identical. They have diverged once already: sweep_stranded was added to
# the ci-cd copy alone, so the protocol hole it covers stayed open in the other two. Its only
# caller is still in xcat-core-ci-cd (ci/sweep-stranded-locks.pl); it stays in all three copies
# because a copy that drops it reopens that hole.
#
# A lock on a shared, possibly re-exported, NFS tree. flock and fcntl are not
# available there. The protocol uses mkdir, rmdir, unlink and plain file
# writes. It uses no rename.
@@ -9,9 +19,45 @@ 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.d/workers/ one empty file per attached worker, named <pgid>.<leader pstart>
# 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
#
# Workers
# The owner of a lock is one process, and what a lock protects usually outlives it. A build
# wrapper starts each command in its OWN process group, so SIGKILL on the wrapper leaves that
# group running: an owner proven dead says nothing about the work it started, and a take-over
# then puts two builds in one checkout.
#
# A caller therefore ATTACHES each process group it starts, and DETACHES it once reaped.
# attach records lock.d/workers/<pgid>.<pstart of the group leader>. An owner is recoverable
# only when it is provably dead AND every attached group is gone.
#
# A group is provably gone when kill(0, -pgid) answers ESRCH, which is the test the build
# wrapper's own cancellation path uses to decide it may release. detach applies the same test,
# so the retention is a property of what is on disk and not of who called what. EPERM, or success, means some
# process is in the group, and then the lock is not recoverable. This is deliberately
# conservative: a recycled pgid reads as live and costs a wait, where the other error admits a
# second writer.
#
# Reuse windows. The entry name carries the leader's start time, so removing an entry by name
# cannot remove the record of a LATER group that reused the pgid. The group test itself cannot
# tell a recycled pgid from the original group, and answers live for both. What neither can
# tell is a worker that left its group by calling setpgid itself; the wrapper's cancellation
# path has that same limit, and the two now agree rather than contradict each other.
#
# 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.
@@ -19,11 +65,18 @@ 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 cannot die:
# - after it creates lock.d, until it publishes valid metadata;
# - while it holds lock.borrow, until it removes it.
# 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.
# An attached process group that outlives its owner holds the lock until the group is gone.
# 7. All participants follow the protocol.
#
# Metadata
@@ -36,7 +89,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.
# 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
@@ -57,18 +111,25 @@ package XCAT::NFSLock;
# - invalid or missing: retry
# - different machine-id: retry
# - same host: save the observed ownership identity
# 3. mkdir lock.borrow
# - failure: 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
# 5. Prove that the recorded (boot-id, pid, pstart) is dead.
# - not provably dead: rmdir lock.borrow, retry
# 5. Prove that the recorded (boot-id, pid, pstart) is dead, and that every group in
# lock.d/workers is gone.
# - the owner is not provably dead, or any attached group still exists: give up the borrow,
# retry
# - dead: continue
# 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
# - 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
@@ -76,9 +137,12 @@ package XCAT::NFSLock;
# Core invariants
# lock.d exists => locked
# lock.d absent => acquirable
# an attached group => locked, whatever the owner's state
# invalid metadata => retry only
# different machine-id => never recover here
# lock.borrow exists => ownership transition or release in progress
# 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.
@@ -86,21 +150,25 @@ 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), 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;
use Cwd qw(abs_path);
use File::Find ();
use Digest::SHA qw(sha256_hex);
use Errno qw(EEXIST ENOENT);
use Fcntl qw(O_CREAT O_EXCL O_WRONLY);
use Exporter 'import';
use File::Basename qw(dirname basename);
use POSIX qw(strftime);
use Sys::Hostname qw(hostname);
use Time::HiRes ();
our @EXPORT_OK = qw(this_process format_metadata parse_metadata owner_is_dead process_start);
our @EXPORT_OK = qw(this_process format_metadata parse_metadata owner_is_dead process_start
sweep_stranded live_workers);
my @IDENTITY = qw(machine-id boot-id pid pstart token);
@@ -149,24 +217,28 @@ 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;
my $workers;
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;
}
@@ -180,22 +252,39 @@ sub acquire {
# Step 2.
my $observed = _read_metadata($abs);
$seen = $observed if defined($observed);
if (defined($observed) && $observed->{'machine-id'} eq $here->{'machine-id'} && mkdir($borrow)) {
# Steps 3 to 7.
my $taken = eval {
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});
1;
};
my $error = $@;
rmdir($borrow);
die $error unless defined($taken);
if ($taken) {
$self->_log('took-over', 'from dead pid ' . $observed->{pid});
return $self;
if (defined($observed) && $observed->{'machine-id'} eq $here->{'machine-id'}) {
# 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 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);
# The owner is dead. The work it started may not be.
my @live = live_workers($abs);
if (@live) { $workers = $live[0]{pgid}; return 0 }
my $mine = this_process();
_at('before-commit');
_write_metadata($abs, $mine);
$self->{identity} = $mine;
1;
};
my $error = $@;
_drop_borrow($borrow);
die $error unless defined($taken);
if ($taken) {
_drop_dead_workers($abs);
$self->_log('took-over', 'from dead pid ' . $observed->{pid});
return $self;
}
}
}
@@ -205,8 +294,11 @@ sub acquire {
}
my $who = _describe($seen);
my $s = $retries == 1 ? 'retry' : 'retries';
die "Trying to unlock $abs failed after $retries $s; $label owned by $who.\n"
$who .= ", retained for surviving build workers in process group $workers" if defined($workers);
my $s = $retries == 1 ? 'retry' : 'retries';
# Names what happened, so a caller can tell a lock another process still holds from a mkdir
# that failed outright. The earlier wording said "Trying to unlock", which is the reverse.
die "Cannot lock $abs: still held after $retries $s by $who.\n"
. "If you are sure it is safe, remove the lock: rm -rf $abs\n";
}
@@ -229,32 +321,64 @@ sub acquire {
sub release {
my ($self) = @_;
return 0 if $self->{released} || $$ != $self->{pid};
my $path = $self->{path};
my $borrow = "$path.borrow";
while (1) {
# 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.
return 0 unless defined($self->{identity});
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})) {
$self->{released} = 1;
unlink("$path/metadata");
my $removed = rmdir($path);
my $error = $!;
rmdir($borrow);
warn "Cannot remove $path: $error\n" unless $removed;
$self->_log($removed ? 'released' : 'release-skipped', $removed ? () : ("rmdir: $error"));
return $removed ? 1 : 0;
# Records of groups that are gone come off first. Then the metadata is deleted
# only once the directory can actually be removed: rmdir refuses a non-empty
# directory, and a lock left holding workers and no metadata is one acquire
# refuses for ever, because there is nothing there to validate. A lock still
# HELD is better than that -- it is refused with a reason, and it recovers when
# its owner dies.
_drop_dead_workers($path);
if (_only_metadata($path)) {
$self->{released} = 1;
unlink("$path/metadata");
my $removed = rmdir($path);
my $error = $!;
_drop_borrow($borrow);
warn "Cannot remove $path: $error\n" unless $removed;
$self->_log($removed ? 'released' : 'release-skipped', $removed ? () : ("rmdir: $error"));
return $removed ? 1 : 0;
}
_drop_borrow($borrow);
# Still held, and NOT marked released: DESTROY and the signal handler have to be
# able to try again once the workers are gone.
my @busy = live_workers($path);
$why = @busy ? "build workers of process group $busy[0]{pgid} still exist"
: "$path holds more than its metadata";
}
rmdir($borrow);
# Valid metadata of another acquisition, or no lock.d at all: this lock is gone.
if (defined($current) || !-d $path) {
$self->{released} = 1;
$self->_log('release-skipped', defined($current) ? 'owned by ' . _describe($current) : 'no lock.d');
return 0;
else {
_drop_borrow($borrow);
# Valid metadata of another acquisition, or no lock.d at all: this lock is gone.
if (defined($current) || !-d $path) {
$self->{released} = 1;
$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}) {
# Marked released only when nothing is left to remove. A lock still on disk has to
# stay releasable, or the guard that owns it can never finish the job.
$self->{released} = 1 unless -d $path;
$self->_log('release-skipped', "gave up: $why");
warn "Cannot release $path after $count retries: $why\n";
return 0;
}
_sleep(_wait($self->{delay}, $self->{jitter}));
@@ -415,6 +539,67 @@ sub _canonical {
return join('', map { "$_=$fields->{$_}\n" } sort @IDENTITY);
}
# _drop_borrow: remove a borrow this process created, metadata first.
sub _drop_borrow {
my ($borrow) = @_;
unlink("$borrow/metadata");
return rmdir($borrow);
}
# _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";
}
# _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 {
my ($fields) = @_;
return join("\n", map { $fields->{$_} } @IDENTITY);
@@ -491,4 +676,307 @@ sub _absolute {
return "$dir/" . basename($path);
}
#--------------------------------------------------------------------------------
=head3 attach
Descriptions:
Record a process group this lock holder started, so the lock is not recoverable while
any process is still in that group.
An owner is one process and the work it starts is not. A build wrapper runs each command
in its own process group, so SIGKILL on the wrapper leaves that group running, and an
owner proven dead says nothing about the build it started.
Arguments:
$pgid: the process group id, which is the pid of the group leader
Returns:
1 when the group is recorded, 0 when it names no process or cannot be recorded.
=cut
#--------------------------------------------------------------------------------
sub attach {
my ($self, $pgid) = @_;
return 0 unless defined($pgid) && $pgid =~ /\A[1-9][0-9]*\z/;
# The leader's start time pins the record, so a later group that reuses the pgid gets its own
# entry and cannot be removed by a detach of this one.
my $pstart = process_start($pgid);
return 0 unless defined($pstart);
my $dir = _worker_dir($self->{path});
unless (mkdir($dir) || $! == EEXIST) {
warn "Cannot create $dir: $!\n";
return 0;
}
my $file = "$dir/$pgid.$pstart";
unless (sysopen(my $fh, $file, O_WRONLY | O_CREAT | O_EXCL) || $! == EEXIST) {
warn "Cannot record build worker $pgid: $!\n";
return 0;
}
$self->{workers}{$pgid} = $pstart;
return 1;
}
#--------------------------------------------------------------------------------
=head3 detach
Descriptions:
Remove the record of a process group this holder started. Call it once the group is
reaped.
It removes nothing while any process is still in the group. Reaping the group LEADER does
not end the group: its children inherit it and can outlive it. Refusing here makes the
retention a property of what is on disk rather than of who remembered to call this, so a
caller that detaches too early cannot free a lock whose workers still run.
Arguments:
$pgid: the process group id
Returns:
the number of records removed.
=cut
#--------------------------------------------------------------------------------
sub detach {
my ($self, $pgid) = @_;
return 0 unless defined($pgid) && $pgid =~ /\A[1-9][0-9]*\z/;
return 0 unless !kill(0, -$pgid) && $!{ESRCH};
delete($self->{workers}{$pgid});
my $dir = _worker_dir($self->{path});
opendir(my $dh, $dir) or return 0;
my @mine = grep { /\A\Q$pgid\E\.[0-9]+\z/ } readdir($dh);
closedir($dh);
my $removed = 0;
$removed += unlink("$dir/$_") for @mine;
rmdir($dir);
return $removed;
}
#--------------------------------------------------------------------------------
=head3 live_workers
Descriptions:
The attached process groups of the lock at $path that still have a process in them.
kill(0, -pgid) answering ESRCH is the only answer that proves a group gone, and it is the
test the build wrapper's own cancellation path uses before it releases. Success and EPERM
both mean some process is in the group. A recycled pgid therefore reads as live, which
costs a wait; the opposite error admits a second writer.
Arguments:
$path: the lock path
Returns:
A list of hash refs: pgid, pstart, entry. Empty when every attached group is gone.
=cut
#--------------------------------------------------------------------------------
sub live_workers {
my ($path) = @_;
opendir(my $dh, _worker_dir($path)) or return ();
my @live;
while (defined(my $entry = readdir($dh))) {
next unless $entry =~ /\A([1-9][0-9]*)\.([0-9]+)\z/;
my ($pgid, $pstart) = ($1, $2);
next if !kill(0, -$pgid) && $!{ESRCH};
push @live, { pgid => $pgid, pstart => $pstart, entry => $entry };
}
closedir($dh);
return @live;
}
sub _worker_dir { return "$_[0]/workers" }
# _only_metadata: true when $dir holds nothing besides its metadata file, so rmdir can finish
# once that file is gone. Asked BEFORE the unlink, because the unlink is not reversible: a lock
# directory with no metadata cannot be validated, so acquire refuses it for ever and only a
# sweep under an exclusive claim can clear it.
sub _only_metadata {
my ($dir) = @_;
opendir(my $dh, $dir) or return 0;
while (defined(my $entry = readdir($dh))) {
next if $entry eq '.' || $entry eq '..' || $entry eq 'metadata';
closedir($dh);
return 0;
}
closedir($dh);
return 1;
}
# _drop_dead_workers: remove the records of groups that are gone, and leave the rest.
#
# A group that died without a detach leaves its record behind -- the detach runs in the process
# that reaped the group, and a process killed before it reaps nothing. Without this a holder
# could never release its own lock, because rmdir refuses a non-empty directory. A live record
# is kept for that reason: it is what stops the release, and what a later acquire reads.
#
# Removing an entry by name is safe. The name carries the leader's start time, so only the group
# that was recorded can own that name, and a group that is gone creates nothing.
sub _drop_dead_workers {
my ($path) = @_;
my $dir = _worker_dir($path);
opendir(my $dh, $dir) or return 0;
my @entry = grep { /\A[1-9][0-9]*\.[0-9]+\z/ } readdir($dh);
closedir($dh);
my $removed = 0;
for my $entry (@entry) {
my ($pgid) = $entry =~ /\A([1-9][0-9]*)\./;
next unless !kill(0, -$pgid) && $!{ESRCH};
$removed += unlink("$dir/$entry");
}
rmdir($dir);
return $removed;
}
#--------------------------------------------------------------------------------
=head3 DESTROY
Descriptions:
Release the lock when the caller stops holding the returned object.
Without this a guard that goes out of scope keeps its lock to the end of the process, and
no take-over can recover it either, because its owner is alive. Every caller in this
project keeps its guards in an array for exactly that reason. release checks the pid, so a
forked child cannot free its parent's lock, and it is idempotent.
Arguments:
none
Returns:
nothing
=cut
#--------------------------------------------------------------------------------
sub DESTROY {
local ($@, $!, $?);
my ($self) = @_;
eval { $self->release; 1 };
return;
}
#--------------------------------------------------------------------------------
=head3 sweep_stranded
Descriptions:
Remove lock state that a killed process left behind, under one root.
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.
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 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.
A lock with an attached process group that still exists is kept whatever the caller
claims. The claim is an assertion that no build is running, and a live group is evidence
that one is.
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 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.
=cut
#--------------------------------------------------------------------------------
sub sweep_stranded {
my ($root, $here, %opt) = @_;
$here //= _here();
my @found;
File::Find::find({
no_chdir => 1,
wanted => sub {
my $d = $File::Find::name;
return unless -d $d;
# 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(?:\.[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.
# The lock a path belongs to, so a borrow is judged by its own lock's workers.
my $lock_of = sub { my $p = shift; $p =~ s/\.borrow(?:\.[0-9]+)?\z//; return $p };
for my $d (sort { ($b =~ /\.borrow(?:\.[0-9]+)?\z/ ? 1 : 0) <=> ($a =~ /\.borrow(?:\.[0-9]+)?\z/ ? 1 : 0)
|| $a cmp $b } @found) {
my @busy = live_workers($lock_of->($d));
if (@busy) {
push @report, { path => $d, action => 'kept',
why => "build workers of process group $busy[0]{pgid} still exist" };
next;
}
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' };
next;
}
push @report, _remove($d, 'borrow stranded by a killed take-over');
next;
}
my $owner = _read_metadata($d);
unless (defined($owner)) {
if (-e "$d/metadata") {
push @report, { path => $d, action => 'kept',
why => 'metadata invalid; staleness is never inferred' };
next;
}
unless ($opt{exclusive}) {
push @report, { path => $d, action => 'kept',
why => 'no metadata; no exclusive claim on the root' };
next;
}
push @report, _remove($d, 'no metadata, and the caller claims the root exclusively');
next;
}
if ($owner->{'machine-id'} ne $here->{'machine-id'}) {
push @report, { path => $d, action => 'kept',
why => "owned by machine $owner->{'machine-id'}" };
next;
}
unless (owner_is_dead($owner, $here)) {
push @report, { path => $d, action => 'kept',
why => "pid $owner->{pid} is alive" };
next;
}
push @report, _remove($d, "owner pid $owner->{pid} is provably dead");
}
return @report;
}
sub _remove {
my ($dir, $why) = @_;
# Records of completed workers first, then the same question release asks: can this
# directory be removed at all? Deleting the metadata before knowing that left a lock holding
# workers and no owner, which acquire refuses for ever -- so the sweep left the lock in a
# WORSE state than a take-over would have, and a take-over recovers these locks by itself.
_drop_dead_workers($dir);
unless (_only_metadata($dir)) {
return { path => $dir, action => 'kept', why => "cannot remove: $dir is not empty" };
}
unlink("$dir/metadata");
return { path => $dir, action => 'removed', why => $why } if rmdir($dir);
return { path => $dir, action => 'kept', why => "cannot remove: $!" };
}
1;
+2 -2
View File
@@ -273,7 +273,7 @@ for my $held ('openeuler20.03sp4/x86_64', 'rh20.03sp4/x86_64') {
options => ['--skip-xcat-dep', '--try-unlock-timeout', 0]);
if ($native) {
isnt($result->{rc}, 0, 'the native published cell lock excludes a second publisher');
like($result->{log}, qr/Trying to unlock \Q$result->{lock_path}\E failed/,
like($result->{log}, qr/Cannot lock \Q$result->{lock_path}\E: still held/,
'the refusal names the lock beside the native published cell');
is(read_binary("$result->{repo}/openeuler20.03sp4/x86_64/sentinel"), 'previous repository',
'native lock refusal preserves the published repository');
@@ -322,7 +322,7 @@ for my $name ('native-only', 'mixed', 'legacy-locked') {
my $log = read_binary($logfile);
if ($name eq 'legacy-locked') {
isnt($rc, 0, 'finalization refuses a held legacy destination lock');
like($log, qr{Trying to unlock \Q$root\E/rh9/\.x86_64\.lock failed},
like($log, qr{Cannot lock \Q$root\E/rh9/\.x86_64\.lock: still held},
'finalization refuses the same sibling lock as an EL publisher');
ok(!-e "$x/$prpm", 'lock refusal precedes the legacy cross-copy');
ok(!-d "$x/repodata", 'lock refusal precedes legacy reindexing');
+6 -5
View File
@@ -975,7 +975,7 @@ sub test_rpm_repository_lock {
'--skip-createrepo', '--skip-tarball', '--dry-run',
);
isnt($status, 0, 'a repository cell cannot have two publishers');
like(read_binary($log), qr/^Trying to unlock \Q$cell_lock\E failed after 1 retry;/m,
like(read_binary($log), qr/^Cannot lock \Q$cell_lock\E: still held after 1 retry by/m,
'the lock failure names the locked cell');
ok(-d $cell_lock, 'a lock held on another machine is left in place');
remove_tree($cell_lock);
@@ -1022,7 +1022,7 @@ sub test_finalize_cell_lock {
'--finalize-xcat-dep', '--x86_64-repo', $x86, '--ppc64le-repo', $ppc,
);
isnt($status, 0, 'finalize does not rewrite a cell that a build holds');
like(read_binary($log), qr/^Trying to unlock \Q$cell_lock\E failed after 1 retry;/m,
like(read_binary($log), qr/^Cannot lock \Q$cell_lock\E: still held after 1 retry by/m,
'finalize names the cell lock it waited for');
ok(-d $cell_lock, 'the build keeps its cell lock');
ok(!-e "$ppc/rh10/.ppc64le.lock", 'finalize releases the cell locks it took');
@@ -1038,7 +1038,8 @@ sub test_finalize_cell_lock {
'--x86_64-repo', $x86, '--ppc64le-repo', $ppc,
);
isnt($arch_status, 0, 'finalize of an empty ppc64le cell fails');
unlike(read_binary($arch_log), qr/^Trying to unlock/m, 'finalize of ppc64le cells takes no x86_64 cell lock');
unlike(read_binary($arch_log), qr/^Cannot lock \Q$cell_lock\E/m,
'finalize of ppc64le cells takes no x86_64 cell lock');
like(read_binary($arch_log), qr/no x86_64 xCAT-genesis-base rpm/, 'finalize of ppc64le cells reaches the genesis check');
ok(-d $cell_lock, 'the x86_64 cell lock of the other machine is left in place');
ok(!-e "$ppc/rh10/.ppc64le.lock", 'finalize releases the ppc64le cell lock');
@@ -1108,7 +1109,7 @@ sub test_publish_lock {
my $run_status = run_apt_consumer(log => $run_log, output => $output, apt_dir => $apt_root,
extra => [ '--publish-lock-wait', '2' ]);
isnt($run_status, 0, "a publish does not start while a $build_arch run holds its lock");
like(read_binary($run_log), qr/^Trying to unlock \Q$run_lock\E failed after 1 retry;/m,
like(read_binary($run_log), qr/^Cannot lock \Q$run_lock\E: still held after 1 retry by/m,
"the refusal names the $build_arch run lock");
ok(!-d "$apt_root/dists", "nothing is published while a $build_arch run holds its lock");
$running->release;
@@ -1124,7 +1125,7 @@ sub test_publish_lock {
extra => [ '--publish-lock-wait', '2' ],
);
isnt($locked_status, 0, 'a locked apt tree is not published into');
like(read_binary($locked_log), qr/^Trying to unlock \Q$lockfile\E failed after 1 retry;/m,
like(read_binary($locked_log), qr/^Cannot lock \Q$lockfile\E: still held after 1 retry by/m,
'the refusal names the lock another run owns');
ok(!-d "$apt_root/dists", 'nothing is published while another run holds the lock');
+9 -6
View File
@@ -110,17 +110,17 @@ for my $case (
my $path = stage('retried.lock', metadata(pid => $parent, pstart => $parent_start));
@slept = ();
eval { XCAT::NFSLock->acquire($path, retries => 4, delay => 5, jitter => 2, label => 'cell lock'); 1 };
like($@, qr/\ATrying to unlock \Q$path\E failed after 4 retries; cell lock owned by pid $parent on machine /,
like($@, qr/\ACannot lock \Q$path\E: still held after 4 retries by pid $parent on machine /,
'the error names the lock, the retries and the owner');
is(scalar(@slept), 4, 'acquire waits R times');
is(scalar(grep { $_ >= 3 && $_ <= 7 } @slept), 4, 'each wait is within T ± δ');
@slept = ();
eval { XCAT::NFSLock->acquire($path, timeout => 10); 1 };
like($@, qr/failed after 4 retries;/, 'a timeout of 10s with the default delay of 3s is 4 retries');
like($@, qr/still held after 4 retries by/, 'a timeout of 10s with the default delay of 3s is 4 retries');
@slept = ();
eval { XCAT::NFSLock->acquire($path); 1 };
like($@, qr/failed after 1 retry;/, 'a lock with no timeout still retries once');
like($@, qr/still held after 1 retry by/, 'a lock with no timeout still retries once');
}
# The lock stays with an owner that is not proven dead.
@@ -137,7 +137,7 @@ for my $case (
my $path = stage($file, $text);
@mkdirs = ();
eval { XCAT::NFSLock->acquire($path, retries => 2); 1 };
like($@, qr/\ATrying to unlock \Q$path\E failed after 2 retries;/, "$name: the lock is not taken");
like($@, qr/\ACannot lock \Q$path\E: still held after 2 retries by/, "$name: the lock is not taken");
is(scalar(grep { $_ eq "$path.borrow" } @mkdirs), $name =~ /live owner/ ? 3 : 0,
"$name: lock.borrow is tried only for an owner on this machine with valid metadata");
is(-e "$path/metadata" ? read_text("$path/metadata") : undef, $text, "$name: the metadata is unchanged");
@@ -165,13 +165,16 @@ for my $case (
is($lock->release, 1, "$name: the new owner releases the lock") if $lock;
}
# Another process holds lock.borrow: this one does not take the lock.
# Another process holds lock.borrow: this one does not take the lock. The borrow has to name a
# LIVE taker. A borrow with no metadata is reaped instead, because no participant holds one for
# longer than two file reads, and leaving it made the lock unacquirable for ever.
{
my $dead = metadata(pid => $gone);
my $path = stage('borrowed.lock', $dead);
mkdir("$path.borrow") or die "Cannot stage $path.borrow: $!";
write_text("$path.borrow/metadata", metadata(pid => $parent, pstart => $parent_start));
eval { XCAT::NFSLock->acquire($path, retries => 2); 1 };
like($@, qr/\ATrying to unlock /, 'a lock under another borrower is not taken');
like($@, qr/\ACannot lock /, 'a lock under another borrower is not taken');
is(read_text("$path/metadata"), $dead, 'the metadata under another borrower is unchanged');
ok(-d "$path.borrow", 'the other borrower keeps lock.borrow');
}
+755
View File
@@ -0,0 +1,755 @@
#!/usr/bin/perl
# A process killed during an ownership transition leaves lock.borrow behind. Under the CI that
# happens: Jenkins sends SIGTERM and the OOM-killer sends SIGKILL. Step 3 used to be
# mkdir(lock.borrow), so a stranded borrow made the lock PERMANENTLY unacquirable -- acquire
# skipped steps 4 to 7 for ever and told the operator to remove the lock by hand.
#
# A transition whose taker is provably dead is now ended by SUPERSEDING it: the borrow is
# numbered, and a contender creates the next generation rather than removing the one it
# validated. Removing it by path was unsafe, because rmdir names a path and not the inode that
# was validated -- a reaper could delete a LIVE taker's borrow and two processes then took over
# one lock. The concurrent checks below hold that down at the exact interleaving.
use strict;
use warnings;
use Test::More;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
use File::Temp qw(tempdir);
use File::Slurper qw(read_text write_text);
use POSIX ();
use Time::HiRes ();
use XCAT::NFSLock qw(this_process format_metadata parse_metadata process_start);
# A child killed at its barrier leaves a closed pipe behind. Without this, writing to it ends
# this process by signal, and a signal death names no check.
$SIG{PIPE} = 'IGNORE';
my $dir = tempdir(CLEANUP => 1);
my $me = this_process();
# No process can have a pid above the kernel's pid_max, which is 2**22 at most. Asserted rather
# than assumed: every recovery check below depends on this pid really being dead.
my $gone = 2**22 + 7;
is(process_start($gone), undef, 'control: a pid above pid_max names no process');
my $live = getppid();
my $live_start = process_start($live);
ok(defined($live_start), 'control: the parent pid does name a live process');
sub metadata { return format_metadata({ %$me, token => 'ab' x 16, @_ }) }
# Stage a lock and, optionally, a borrow beside it. $borrow is the metadata text for the borrow,
# or the string 'none' to stage a borrow with no metadata at all, as the old protocol left.
sub stage {
my ($name, %o) = @_;
my $path = "$dir/$name";
mkdir($path) or die "Cannot stage $path: $!";
write_text("$path/metadata", $o{lock}) if defined($o{lock});
if (defined($o{borrow})) {
mkdir("$path.borrow") or die "Cannot stage $path.borrow: $!";
write_text("$path.borrow/metadata", $o{borrow}) if $o{borrow} ne 'none';
}
return $path;
}
# Record the waits instead of sleeping, so a lock that cannot be recovered fails at once. The
# cap matters: a retry loop that lost its bound would otherwise spin here for ever, and a test
# that hangs reads as one still running rather than as a defect caught.
my @slept;
{
no warnings 'redefine';
*XCAT::NFSLock::_sleep = sub {
push(@slept, $_[0]);
die "SLEEP CAP: a retry loop ran " . scalar(@slept) . " times\n" if @slept > 200;
};
}
# Keep the lock's own log out of the TAP stream.
open(my $log_fh, '>', \my $logged) or die "Cannot capture the log: $!";
select($log_fh);
sub take {
my ($path) = @_;
@slept = ();
$logged = '';
my $lock = eval { XCAT::NFSLock->acquire($path, retries => 2, label => 'probe') };
return ($lock, $@, $logged);
}
# A bounded read, so a child that never reaches its barrier fails the test instead of hanging it.
sub read_bounded {
my ($fh, $want, $seconds) = @_;
my $buf = '';
my $deadline = Time::HiRes::time() + $seconds;
while (length($buf) < $want) {
my $left = $deadline - Time::HiRes::time();
return undef if $left <= 0;
my $mask = '';
vec($mask, fileno($fh), 1) = 1;
return undef unless select(my $ready = $mask, undef, undef, $left);
my $got = sysread($fh, my $chunk, $want - length($buf));
return undef unless defined($got) && $got > 0;
$buf .= $chunk;
}
return $buf;
}
# one_shot: an _at override that reports its arrival and blocks, the FIRST time it reaches
# $point. acquire passes that point once per attempt, and a contender that blocks on every
# attempt would never report its result.
sub one_shot {
my ($point, $arrive, $gate) = @_;
my $fired = 0;
return sub {
return if $fired || $_[0] ne $point;
$fired = 1;
syswrite($arrive, 'a');
sysread($gate, my $go, 1);
return;
};
}
# contend: run $n acquires of $path in forked children, each stopped at $point until this
# process releases them all together. The interleaving is a barrier and not a delay, so the
# result does not depend on how fast the machine is. A child holds its lock until it is killed,
# so one winner cannot hide another by releasing first. Returns the number that acquired the
# lock, or undef when a child did not reach the barrier or report in time.
sub contend {
my ($path, $n, $point) = @_;
pipe(my $arrive_r, my $arrive_w) or die "pipe: $!";
pipe(my $gate_r, my $gate_w) or die "pipe: $!";
pipe(my $result_r, my $result_w) or die "pipe: $!";
my @child;
for my $i (1 .. $n) {
my $pid = fork();
die "fork: $!" unless defined $pid;
if ($pid) { push @child, $pid; next }
close($arrive_r); close($gate_w); close($result_r);
# Detached, so a child writes no TAP and flushes none of this process's buffers.
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
no warnings 'redefine';
*XCAT::NFSLock::_at = one_shot($point, $arrive_w, $gate_r);
my $lock = eval { XCAT::NFSLock->acquire($path, retries => 3, label => 'race', quiet => 1) };
syswrite($result_w, $lock ? '1' : '0');
# Block until killed, holding whatever was acquired. _exit runs no END block.
sysread($gate_r, my $hold, 1);
POSIX::_exit(0);
}
close($arrive_w);
close($gate_r);
close($result_w);
my $arrived = read_bounded($arrive_r, $n, 20);
my $results;
if (defined($arrived)) {
syswrite($gate_w, 'g' x $n);
$results = read_bounded($result_r, $n, 20);
}
kill('KILL', $_) for @child;
waitpid($_, 0) for @child;
close($_) for ($arrive_r, $gate_w, $result_r);
return undef unless defined($arrived) && defined($results);
return scalar(() = $results =~ /1/g);
}
# spawn: one acquire in a child, stopped the first time it reaches $point. The caller releases
# each child itself, so a test can order two contenders instead of starting them together. That
# order is what reproduces the defect below: releasing both at once has them race one mkdir,
# which is exclusive either way.
sub spawn {
my ($path, $point, %o) = @_;
pipe(my $arrive_r, my $arrive_w) or die "pipe: $!";
pipe(my $gate_r, my $gate_w) or die "pipe: $!";
pipe(my $result_r, my $result_w) or die "pipe: $!";
my $pid = fork();
die "fork: $!" unless defined $pid;
unless ($pid) {
close($arrive_r); close($gate_w); close($result_r);
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
no warnings 'redefine';
*XCAT::NFSLock::_at = one_shot($point, $arrive_w, $gate_r);
my $lock = eval {
XCAT::NFSLock->acquire($path, retries => $o{retries} // 3, label => 'race', quiet => 1);
};
syswrite($result_w, $lock ? '1' : '0');
sysread($gate_r, my $hold, 1); # hold what was acquired until killed
POSIX::_exit(0);
}
close($arrive_w); close($gate_r); close($result_w);
return { pid => $pid, arrive => $arrive_r, gate => $gate_w, result => $result_r };
}
sub arrived { return read_bounded($_[0]{arrive}, 1, 20) }
sub go { return syswrite($_[0]{gate}, 'g') }
sub won { return read_bounded($_[0]{result}, 1, 20) // 'no result' }
sub reap {
my ($h) = @_;
kill('KILL', $h->{pid});
waitpid($h->{pid}, 0);
close($h->{$_}) for qw(arrive gate result);
return;
}
# ---- 1. a contender that validated a borrow cannot unseat the one that holds it ---------
# THE DEFECT, at the interleaving that reaches it. _reap_borrow validated a borrow and then
# removed it BY PATH, so a contender stopped between those two steps removed whatever was at
# the path when it resumed -- which is a live taker's borrow, not the one it validated.
#
# A is stopped having validated the dead taker. B then takes the borrow and stops before it
# writes the lock. Releasing A makes A act on its stale decision while B is live.
{
my $path = stage('unseat.lock.d',
lock => metadata(pid => $gone, pstart => '1'),
borrow => metadata(pid => $gone, pstart => '2'));
my $a = spawn($path, 'before-supersede');
is(arrived($a), 'a', 'control: A validated the dead taker and holds no borrow yet');
my $b = spawn($path, 'before-commit');
is(arrived($b), 'a', 'control: B holds the borrow and has not written the lock yet');
go($a);
my $first = won($a);
go($b);
my $second = won($b);
is("$first$second", '01', 'A cannot take over as well: only the holder of the borrow does');
reap($a);
reap($b);
}
# ---- 1a. two contenders released together still produce one winner ---------------------
# THE DEFECT. _reap_borrow validated a borrow and then removed it by path, so two contenders
# that both validated the same dead taker both reached mkdir(lock.borrow) and both took over.
# Superseding is a single mkdir of generation N+1, which is exclusive, so one contender wins and
# the other finds a live taker.
{
my $path = stage('supersede.lock.d',
lock => metadata(pid => $gone, pstart => '1'),
borrow => metadata(pid => $gone, pstart => '2'));
my $won = contend($path, 2, 'before-supersede');
is($won, 1, 'exactly one of two contenders takes over a lock whose owner and taker are dead');
}
# ---- 2. a contender that has not written its metadata yet is never superseded ----------
# The reviewer's case, and the one an "unchanged for T seconds" rule cannot cover: a live taker
# can pause for any length of time between its mkdir and its first write. Superseding it would
# put two processes in the transition.
{
my $path = stage('paused.lock.d', lock => metadata(pid => $gone, pstart => '1'));
pipe(my $arrive_r, my $arrive_w) or die "pipe: $!";
pipe(my $gate_r, my $gate_w) or die "pipe: $!";
my $paused = fork();
die "fork: $!" unless defined $paused;
unless ($paused) {
close($arrive_r); close($gate_w);
open(STDOUT, '>', '/dev/null'); open(STDERR, '>', '/dev/null');
no warnings 'redefine';
*XCAT::NFSLock::_at = one_shot('borrow-created', $arrive_w, $gate_r);
eval { XCAT::NFSLock->acquire($path, retries => 3, label => 'paused', quiet => 1) };
POSIX::_exit(0);
}
close($arrive_w); close($gate_r);
my $reached = read_bounded($arrive_r, 1, 20);
is($reached, 'a', 'control: a contender holds generation 0 with no metadata written yet');
ok(-d "$path.borrow", 'control: generation 0 exists');
ok(!-e "$path.borrow/metadata", 'control: and it holds no metadata');
my ($lock, $err) = take($path);
ok(!$lock, 'a generation whose taker has written no metadata is not superseded');
like($err, qr/still held after 2 retries/, 'the second contender waits out its retries');
ok(-d "$path.borrow", 'and the paused contender keeps its generation');
ok(!-d "$path.borrow.1", 'no later generation was created');
syswrite($gate_w, 'g');
waitpid($paused, 0);
close($arrive_r); close($gate_w);
}
# ---- 3. a dead taker's generation is superseded, not removed ---------------------------
# The fix, stated as what is on disk afterwards: generation 0 survives, because nothing removes
# a generation it did not create, and the take-over ran in generation 1.
{
my $path = stage('keep-generation.lock.d',
lock => metadata(pid => $gone, pstart => '1'),
borrow => metadata(pid => $gone, pstart => '2'));
my ($lock, $err, $log) = take($path);
ok($lock, 'a lock whose owner and taker are both dead is taken over') or diag "acquire died: $err";
ok(-d "$path.borrow", 'the dead taker generation is left in place, never removed');
ok(!-d "$path.borrow.1", 'and the generation this process created is gone');
like($log, qr/took-borrow .*superseded generation 0/, 'the log names the generation it superseded');
undef $lock;
}
# ---- 3a. a generation with no valid metadata blocks, and only the sweeper clears it -----
# WITHDRAWN RULE. An earlier revision reclaimed a metadata-less borrow when two attempts found
# it unchanged. Scenario 2 is why that is wrong. The disposition is the one a metadata-less
# lock.d already has: acquire refuses, and sweep_stranded removes it under an exclusive claim.
{
my $root = "$dir/legacy";
mkdir $root or die $!;
my $path = "$root/legacy.lock.d";
mkdir $path or die $!;
write_text("$path/metadata", metadata(pid => $gone, pstart => '1'));
mkdir "$path.borrow" or die $!;
my ($lock, $err) = take($path);
ok(!$lock, 'a borrow with no metadata is not reclaimed by acquire');
like($err, qr/still held after 2 retries/, 'it waits out its retries instead');
ok(-d "$path.borrow", 'and the borrow is left for the sweeper');
my %kept = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef);
is($kept{"$path.borrow"}{action}, 'kept', 'the sweeper keeps it without an exclusive claim');
my %swept = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef, exclusive => 1);
is($swept{"$path.borrow"}{action}, 'removed', 'and removes it under one');
ok(!-d "$path.borrow", 'so the lock can be taken over again');
}
# ---- 3b. a borrow whose metadata does not validate is never assumed stale --------------
# A metadata file that exists but does not hash may be a half-finished write.
{
my $path = stage('junk-borrow.lock.d',
lock => metadata(pid => $gone, pstart => '1'),
borrow => "pid=1\n");
my ($lock, $err) = take($path);
ok(!$lock, 'a borrow with invalid metadata is not superseded');
like($err, qr/still held after 2 retries/, 'it waits out its retries instead');
ok(-d "$path.borrow", 'and the borrow is left alone');
}
# ---- 4. a borrow this module creates carries metadata -----------------------------------
# Scenario 1 can only work if the taker records who it is. Without this the next acquirer has
# nothing to validate and falls into scenario 3.
{
my $path = stage('records-taker.lock', lock => metadata(pid => $gone, pstart => '1'));
my $seen;
{
no warnings 'redefine';
my $real = \&XCAT::NFSLock::owner_is_dead;
# Read the borrow's metadata at the moment the take-over holds it.
local *XCAT::NFSLock::owner_is_dead = sub {
$seen //= eval { read_text("$path.borrow/metadata") };
return $real->(@_);
};
my $lock = eval { XCAT::NFSLock->acquire($path, retries => 2, label => 'probe') };
undef $lock;
}
ok(defined($seen) && length($seen), 'the borrow holds metadata while the take-over runs');
my $id = parse_metadata($seen);
ok($id, 'that metadata is valid and hashes correctly');
is($id && $id->{pid}, $$, 'and it names the process doing the take-over');
}
# ---- 5. the sweeper covers the lock names this project actually uses --------------------
# sweep_stranded removes state a killed process left under one root. Its matcher read '.lock'
# and '.lock.borrow' only, so it swept mockbuild-all.pl's cell locks and silently missed
# cluster-test.pl's <repo>/.build.lock.d and sbuild-all.pl's .sbuild-all.<arch>.nfslock -- which
# is where the permanent strand this file is about would land.
{
my $root = "$dir/sweep";
mkdir $root or die $!;
my %made;
for my $n (qw(.x86_64.lock .build.lock.d .sbuild-all.amd64.nfslock)) {
mkdir "$root/$n" or die $!;
write_text("$root/$n/metadata", metadata(pid => $gone, pstart => '1'));
$made{$n} = "$root/$n";
}
mkdir "$root/.build.lock.d.borrow" or die $!;
$made{'.build.lock.d.borrow'} = "$root/.build.lock.d.borrow";
# A superseded transition leaves numbered generations, which the matcher must also see.
mkdir "$root/.x86_64.lock.borrow.2" or die $!;
$made{'.x86_64.lock.borrow.2'} = "$root/.x86_64.lock.borrow.2";
# A live owner and another machine must survive the sweep, so the matcher widening cannot be
# read as "remove more".
mkdir "$root/.live.lock.d" or die $!;
write_text("$root/.live.lock.d/metadata", metadata(pid => $live, pstart => $live_start));
mkdir "$root/.other.lock.d" or die $!;
write_text("$root/.other.lock.d/metadata",
metadata(pid => $gone, pstart => '1', 'machine-id' => 'f' x 32));
my %act = map { $_->{path} => $_->{action} }
XCAT::NFSLock::sweep_stranded($root, undef, exclusive => 1);
is($act{$made{'.x86_64.lock'}}, 'removed', 'a stale .lock is swept, as before');
is($act{$made{'.build.lock.d'}}, 'removed', 'a stale .lock.d is swept');
is($act{$made{'.build.lock.d.borrow'}}, 'removed', 'a stranded .lock.d.borrow is swept');
is($act{$made{'.x86_64.lock.borrow.2'}}, 'removed', 'a stranded numbered generation is swept');
is($act{$made{'.sbuild-all.amd64.nfslock'}}, 'removed', 'a stale .nfslock is swept');
is($act{"$root/.live.lock.d"}, 'kept', 'a lock whose owner is alive is kept');
is($act{"$root/.other.lock.d"}, 'kept', 'a lock owned by another machine is kept');
}
# ---- 6. a lock.d with no metadata is refused, and only the sweeper removes it ----------
# The build lock in xcat-core wrote no metadata and held lock.d for the whole build, so a
# metadata-less lock.d can be a live build of the earlier code. acquire must refuse it: no fact
# on disk tells that holder from a dead one. Only a caller that claims the root exclusively may
# call it abandoned, which is the one condition under which the sweeper removes it.
{
my $root = "$dir/no-metadata";
mkdir $root or die $!;
my $path = "$root/buildrpms.openeuler-20.03sp4-x86_64.lock.d";
mkdir $path or die $!;
my ($lock, $err) = take($path);
ok(!$lock, 'a lock.d with no metadata is not taken over');
like($err, qr/still held after 2 retries/, 'acquire waits out its retries and names the lock');
ok(-d $path, 'and the directory is left for the sweeper');
my %kept = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef);
is($kept{$path}{action}, 'kept', 'the sweeper keeps it without an exclusive claim');
like($kept{$path}{why}, qr/no exclusive claim/, 'and names the rule that kept it');
my %swept = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef, exclusive => 1);
is($swept{$path}{action}, 'removed', 'with the exclusive claim it is removed');
ok(!-d $path, 'so a later build can take the lock');
}
# ---- 7. a forked child cannot release its parent's lock --------------------------------
# DESTROY calls release, so a child that inherits a guard and exits would otherwise remove a
# lock its parent still holds. The pid test in release is the only thing that stops it.
{
my $path = "$dir/forked.lock.d";
my $lock = XCAT::NFSLock->acquire($path, retries => 1, label => 'forked', quiet => 1);
pipe(my $reader, my $writer) or die "pipe: $!";
my $child = fork();
die "fork: $!" unless defined $child;
unless ($child) {
close $reader;
my $freed = $lock->release;
syswrite($writer, $freed ? "freed\n" : "kept\n");
# _exit, so the child runs no END block and flushes none of the parent's buffers.
POSIX::_exit(0);
}
close $writer;
my $said = <$reader> // '';
close $reader;
waitpid($child, 0);
is($said, "kept\n", 'release in a forked child frees nothing');
ok(-d $path, 'and the parent still holds its lock');
ok($lock->release, 'which the owning process can then release itself');
}
# ---- 7a. a dead owner whose workers still run does not lose its lock -------------------
# An owner is one process; the work it starts is not. The build wrapper runs each command in its
# OWN process group, so SIGKILL on the wrapper leaves that group running, and a lock recovered
# from the dead wrapper puts two builds in one checkout.
#
# BOTH halves are asserted. A test with only the blocking half cannot tell this rule from a lock
# that recovers nothing at all, which would satisfy the same assertion and remove the reason the
# recovery exists.
{
my $path = "$dir/with-workers.lock.d";
pipe(my $stop_r, my $stop_w) or die "pipe: $!";
pipe(my $up_r, my $up_w) or die "pipe: $!";
# The worker: its own process group, as sh() gives each build command, and it outlives the
# owner that started it.
my $worker = fork();
die "fork: $!" unless defined $worker;
unless ($worker) {
close($stop_w); close($up_r);
POSIX::setpgid(0, 0);
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
syswrite($up_w, 'w');
sysread($stop_r, my $go, 1);
POSIX::_exit(0);
}
close($stop_r); close($up_w);
is(read_bounded($up_r, 1, 20), 'w', 'control: the worker is running in its own group');
POSIX::setpgid($worker, $worker);
# The owner takes the lock, attaches the worker, and is then killed with a signal it cannot
# handle, so it runs no handler and detaches nothing.
my $owner = XCAT::NFSLock->acquire($path, retries => 1, label => 'owner', quiet => 1);
is($owner->attach($worker), 1, 'control: the owner records the worker group');
ok(-e "$path/workers/$worker." . process_start($worker), 'control: the record names the group');
write_text("$path/metadata", metadata(pid => $gone, pstart => '1')); # the owner is now dead
my ($blocked, $err) = take($path);
ok(!$blocked, 'a dead owner whose worker group still exists keeps its lock');
like($err, qr/retained for surviving build workers in process group $worker\b/,
'and the refusal names the group that holds it');
ok(-d $path, 'the lock is still there');
my %swept = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($dir, undef, exclusive => 1);
is($swept{$path}{action}, 'kept', 'an exclusive claim does not override a live worker group');
like($swept{$path}{why}, qr/process group $worker still exist/, 'and says which group kept it');
# THE OTHER HALF. Let the worker exit, and the same lock must now be recoverable.
syswrite($stop_w, 'g');
waitpid($worker, 0);
my ($taken, $why) = take($path);
ok($taken, 'once the worker group is gone the lock IS recovered') or diag "acquire died: $why";
ok(!-d "$path/workers", 'and the take-over clears the records of the owner it replaced');
undef $taken;
close($up_r); close($stop_w);
$owner->{released} = 1; # the metadata names another acquisition now
}
# ---- 7b. a group outlives its leader, and the lock reads the GROUP ---------------------
# Reaping the group leader does not end the group: its children inherit it. A liveness test that
# asked about the leader would call this group gone while a build worker still runs in it, which
# is the same substitution the whole finding is about -- asking about one process instead of the
# set that must be dead.
#
# detach is asserted here too. It must refuse while the group exists, so the retention is a
# property of what is on disk and not of which call site remembered to run.
{
my $path = "$dir/orphan.lock.d";
pipe(my $kid_stop_r, my $kid_stop_w) or die "pipe: $!";
pipe(my $leader_stop_r, my $leader_stop_w) or die "pipe: $!";
pipe(my $up_r, my $up_w) or die "pipe: $!";
my $leader = fork();
die "fork: $!" unless defined $leader;
unless ($leader) {
close($kid_stop_w); close($leader_stop_w); close($up_r);
POSIX::setpgid(0, 0);
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
# The grandchild inherits the group and outlives the leader.
my $kid = fork();
if (defined($kid) && !$kid) {
syswrite($up_w, 'k');
sysread($kid_stop_r, my $go, 1);
POSIX::_exit(0);
}
sysread($leader_stop_r, my $go, 1);
POSIX::_exit(0);
}
close($kid_stop_r); close($leader_stop_r); close($up_w);
POSIX::setpgid($leader, $leader);
is(read_bounded($up_r, 1, 20), 'k', 'control: a grandchild runs in the leader\'s group');
my $lock = XCAT::NFSLock->acquire($path, retries => 1, label => 'orphan', quiet => 1);
is($lock->attach($leader), 1, 'control: the group is recorded while its leader is alive');
# The leader exits; the group does not.
syswrite($leader_stop_w, 'g');
waitpid($leader, 0);
is(process_start($leader), undef, 'control: the group LEADER is gone');
ok(kill(0, -$leader), 'control: the group itself is not');
is(scalar(XCAT::NFSLock::live_workers($path)), 1,
'a group that outlived its leader still counts as live');
is($lock->detach($leader), 0, 'and detach refuses to drop its record');
# The grandchild is not this process's child, so waitpid cannot reap it. Poll for the group
# to empty instead, bounded, so a regression fails rather than hangs.
syswrite($kid_stop_w, 'g');
my $deadline = Time::HiRes::time() + 20;
while (kill(0, -$leader) && Time::HiRes::time() < $deadline) {
select(undef, undef, undef, 0.01);
}
ok(!kill(0, -$leader), 'control: the group is empty once the grandchild exits');
is(scalar(XCAT::NFSLock::live_workers($path)), 0, 'and the record then counts as gone');
is($lock->detach($leader), 1, 'so detach drops it');
undef $lock;
close($_) for ($up_r, $kid_stop_w, $leader_stop_w);
}
# ---- 8. a take-over whose commit fails returns that error, and cleans up nothing --------
# acquire set identity before writing the lock metadata, so a write that left partial metadata
# and threw gave DESTROY a lock to release. release then retried for ever, because lock.d
# existed and its metadata could not be validated, and the caller never saw the write error.
#
# The sleep is capped so an unbounded release reports a different error instead of hanging. The
# check is on the error TEXT: anything that merely dies would pass a check for "it died".
{
my $path = stage('commit-fails.lock.d', lock => metadata(pid => $gone, pstart => '1'));
my $capped = 0;
my $lock;
my $err;
{
no warnings 'redefine';
local *XCAT::NFSLock::_sleep = sub { die "SLEEP CAP\n" if ++$capped > 30 };
my $real = \&XCAT::NFSLock::_write_metadata;
# The lock's own metadata write truncates and then fails, as ENOSPC and EIO do.
local *XCAT::NFSLock::_write_metadata = sub {
return $real->(@_) unless $_[0] eq $path;
write_text("$path/metadata", 'pid=');
die "Cannot write $path/metadata: No space left on device\n";
};
$lock = eval { XCAT::NFSLock->acquire($path, retries => 2, label => 'commit', quiet => 1) };
$err = $@;
}
ok(!$lock, 'the take-over fails');
is($err, "Cannot write $path/metadata: No space left on device\n",
'and the write error reaches the caller unchanged');
is($capped, 0, 'and the destructor did not try to clean up at all');
ok(!-d "$path.borrow", 'the borrow generation it took is given back');
}
# ---- 9. release is bounded --------------------------------------------------------------
# release is reached from DESTROY, where an unbounded wait stops the process instead of
# returning. A lock whose metadata cannot be validated is the case that never resolves.
{
my $path = "$dir/bounded.lock.d";
my $lock = XCAT::NFSLock->acquire($path, retries => 4, label => 'bounded', quiet => 1);
write_text("$path/metadata", 'pid='); # no longer validates, and never will
@slept = ();
my $freed = eval { $lock->release };
is($freed, 0, 'release gives up rather than waiting for metadata that cannot validate')
or diag "release died: $@";
cmp_ok(scalar(@slept), '<=', 5, 'and it waits R times at most, not for ever');
is(eval { $lock->release }, 0, 'a second call does not start again');
unlink "$path/metadata"; rmdir $path;
}
# spawn_worker: a process in its OWN group, blocked until this process releases it. Returns the
# pgid and a code ref that ends it and waits for the group to empty.
sub spawn_worker {
pipe(my $stop_r, my $stop_w) or die "pipe: $!";
pipe(my $up_r, my $up_w) or die "pipe: $!";
my $pid = fork();
die "fork: $!" unless defined $pid;
unless ($pid) {
close($stop_w); close($up_r);
POSIX::setpgid(0, 0);
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
syswrite($up_w, 'w');
sysread($stop_r, my $go, 1);
POSIX::_exit(0);
}
close($stop_r); close($up_w);
POSIX::setpgid($pid, $pid);
die "the worker did not start\n" unless read_bounded($up_r, 1, 20) eq 'w';
my $end = sub {
syswrite($stop_w, 'g');
waitpid($pid, 0);
my $deadline = Time::HiRes::time() + 20;
while (kill(0, -$pid) && Time::HiRes::time() < $deadline) {
select(undef, undef, undef, 0.01);
}
close($up_r); close($stop_w);
return !kill(0, -$pid);
};
return ($pid, $end);
}
# ---- 9a. release keeps the lock whole when a worker blocks the removal -----------------
# release deleted the owner metadata and marked the guard released BEFORE it knew the removal
# could finish. With a live worker the rmdir failed, and the lock was left holding workers and no
# owner -- which acquire refuses for ever, because there is nothing there to validate. A lock
# still HELD is refused with a reason and recovers when its owner dies; that one never did.
{
my $path = "$dir/release-busy.lock.d";
my ($worker, $end_worker) = spawn_worker();
my $lock = XCAT::NFSLock->acquire($path, retries => 2, label => 'busy', quiet => 1);
is($lock->attach($worker), 1, 'control: the owner records a live worker group');
is($lock->release, 0, 'release does not free a lock whose worker group still exists');
ok(-d $path, 'the lock directory survives');
ok(-e "$path/metadata", 'and so does the ownership metadata');
is($lock->release, 0, 'a second attempt still refuses, and still keeps it whole');
ok(-e "$path/metadata", 'the metadata is still there after that attempt');
# THE OTHER HALF. The worker exits, and the SAME guard must finish the release.
ok($end_worker->(), 'control: the worker group is gone');
is($lock->release, 1, 'the same guard then releases the lock it kept');
ok(!-d $path, 'and the directory is gone');
my $next = eval { XCAT::NFSLock->acquire($path, retries => 1, label => 'next', quiet => 1) };
ok($next, 'so a later acquire succeeds') or diag "acquire died: $@";
undef $next;
}
# ---- 9b. an owner that exits without releasing leaves a lock that recovers -------------
# The reviewer's path. The owner gives up and exits, so nothing retries. The lock must still be
# recoverable once the owner AND the worker are both gone, which needs its metadata intact.
{
my $path = "$dir/owner-gone.lock.d";
my ($worker, $end_worker) = spawn_worker();
pipe(my $said_r, my $said_w) or die "pipe: $!";
my $owner = fork();
die "fork: $!" unless defined $owner;
unless ($owner) {
close($said_r);
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
my $held = eval { XCAT::NFSLock->acquire($path, retries => 2, label => 'gone', quiet => 1) };
$held->attach($worker) if $held;
my $freed = $held ? $held->release : -1;
syswrite($said_w, $freed == 0 ? 'k' : 'x');
POSIX::_exit(0); # no DESTROY, so nothing retries after this
}
close($said_w);
is(read_bounded($said_r, 1, 20), 'k', 'control: the owner could not release, and exited');
waitpid($owner, 0);
ok(-e "$path/metadata", 'the owner it left behind is still named in the metadata');
my ($blocked, $err) = take($path);
ok(!$blocked, 'a later acquire is refused while the worker group exists');
like($err, qr/process group $worker\b/, 'and the refusal names that group');
# THE OTHER HALF. Both the owner and the worker are gone now.
ok($end_worker->(), 'control: the worker group is gone');
my ($taken, $why) = take($path);
ok($taken, 'and the lock is then recovered from its dead owner') or diag "acquire died: $why";
undef $taken;
close($said_r);
}
# ---- 9c. the sweep does not turn a recoverable lock into a dead one -------------------
# _remove deleted the metadata and then failed on the workers directory, so the sweep reported
# "kept" and left a lock nothing could validate. A take-over recovers the very same lock by
# itself, so the sweep was leaving it in a WORSE state than doing nothing.
{
my $root = "$dir/sweep-workers";
mkdir $root or die $!;
my $path = "$root/completed.lock.d";
mkdir $path or die $!;
write_text("$path/metadata", metadata(pid => $gone, pstart => '1'));
mkdir "$path/workers" or die $!;
# A record of a COMPLETED worker: a pid above pid_max names no group.
write_text("$path/workers/$gone.1", '');
my %act = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef);
is($act{$path}{action}, 'removed', 'the sweep removes a dead owner that has completed worker records');
ok(!-d $path, 'the directory is gone, not left without its metadata');
# THE OTHER HALF, and the reason this matters: the lock has to be usable afterwards.
my $next = eval { XCAT::NFSLock->acquire($path, retries => 1, label => 'after', quiet => 1) };
ok($next, 'so a later acquire succeeds') or diag "acquire died: $@";
undef $next;
}
# ---- 9d. a lock the sweep keeps is left exactly as it was -----------------------------
# The other direction. Whatever the sweep refuses to remove must still carry its metadata, or
# refusing to remove it is the same damage by another route.
{
my $root = "$dir/sweep-live";
mkdir $root or die $!;
my $path = "$root/live.lock.d";
mkdir $path or die $!;
my $text = metadata(pid => $gone, pstart => '1');
write_text("$path/metadata", $text);
my ($worker, $end_worker) = spawn_worker();
mkdir "$path/workers" or die $!;
write_text("$path/workers/$worker." . process_start($worker), '');
my %act = map { $_->{path} => $_ } XCAT::NFSLock::sweep_stranded($root, undef, exclusive => 1);
is($act{$path}{action}, 'kept', 'a lock with a live worker group is kept, exclusive claim or not');
is(read_text("$path/metadata"), $text, 'and its metadata is untouched');
ok($end_worker->(), 'control: the worker group is gone');
my ($taken, $why) = take($path);
ok($taken, 'so the lock is still recoverable afterwards') or diag "acquire died: $why";
undef $taken;
}
# ---- 10. a guard releases when the caller stops holding it -----------------------------
# Without DESTROY the lock is held to the end of the process, and no take-over recovers it
# either, because its owner is alive. Every caller here keeps its guards in an array for that
# reason, so the leak was invisible.
{
my $path = "$dir/scope.lock.d";
{
my $l = XCAT::NFSLock->acquire($path, retries => 1, label => 'scope', quiet => 1);
ok(-d $path, 'control: the lock directory exists while the guard is held');
}
ok(!-d $path, 'the lock is released when the guard goes out of scope');
my $again = eval { XCAT::NFSLock->acquire($path, retries => 1, label => 'scope', quiet => 1) };
ok($again, 'so the same process can take it again') or diag "acquire died: $@";
}
select(STDOUT);
done_testing();