2
0
mirror of https://github.com/xcat2/xcat-core.git synced 2026-11-25 20:02:19 +00:00

Merge pull request #7974 from VersatusHPC/fix/buildrpms-lock-recovery

fix(buildrpms): a lock directory left by a dead build is never broken
This commit is contained in:
Daniel Hilst
2026-11-07 14:05:58 -03:00
committed by GitHub
15 changed files with 1686 additions and 81 deletions
+162 -47
View File
@@ -34,7 +34,8 @@ our @EXPORT_OK = qw(
orig_tarball_name upstream_version resolve_dest
pin_control_version rewrite_changelog_header
reprepro_distributions reprepro_options
lock_id_for take_build_lock
lock_id_for take_build_lock acquire_lock_dir
attach_build_workers detach_build_workers start_build_worker
build_sources_base build_sources_dir prepare_build_sources_dir
remove_build_sources_dir sweep_build_sources_dirs share_build_sources_dir
sh_quote clean_debian_residue git_revision
@@ -126,7 +127,7 @@ sub rewrite_file {
our $CURRENT_CHILD;
# Locks this process holds, weakly. Released by a signal handler or at exit, because
# _BuildLock::DESTROY does not run when a signal ends the process.
# DESTROY does not run when a signal ends the process.
our @LIVE_LOCKS;
END { release_build_locks() }
@@ -141,7 +142,9 @@ sub sh {
POSIX::sigprocmask(POSIX::SIG_BLOCK(), $blocked, $oldmask)
or die "Cannot block build cancellation signals: $!\n";
my $pid = fork();
# The child runs nothing until every held lock records its group, which happens while the
# signal mask is still blocked, so a cancellation cannot land between fork and record.
my ($pid, $registered) = start_build_worker();
unless (defined $pid) {
my $error = "$!";
POSIX::sigprocmask(POSIX::SIG_SETMASK(), $oldmask)
@@ -151,20 +154,20 @@ sub sh {
}
unless ($pid) {
$SIG{INT} = $SIG{TERM} = 'DEFAULT';
POSIX::setpgid(0, 0) or POSIX::_exit(127);
POSIX::sigprocmask(POSIX::SIG_SETMASK(), $oldmask)
or POSIX::_exit(127);
exec('/bin/sh', '-c', $cmd) or POSIX::_exit(127);
}
local $CURRENT_CHILD = $pid; # also the command's process-group ID
# Both sides set the group, so neither depends on which side runs first.
# EACCES means the child already exec'd, after setting its group; ESRCH
# means it has already gone away.
unless (POSIX::setpgid($pid, $pid) || $!{EACCES} || $!{ESRCH}) {
warn "FATAL: cannot create build process group $pid: $!; retaining locks\n";
kill 'KILL', $pid;
POSIX::_exit(127);
unless ($registered) {
warn "FATAL: cannot record build process group $pid on the build lock; not running $cmd\n";
kill 'KILL', -$pid, $pid;
my $got;
do { $got = waitpid($pid, 0) } while ($got == -1 && $!{EINTR});
detach_build_workers($pid);
POSIX::sigprocmask(POSIX::SIG_SETMASK(), $oldmask);
return 127;
}
POSIX::sigprocmask(POSIX::SIG_SETMASK(), $oldmask) or do {
warn "FATAL: cannot restore signal mask: $!\n";
@@ -175,6 +178,7 @@ sub sh {
my $got;
do { $got = waitpid($pid, 0) } while ($got == -1 && $!{EINTR});
my $status = $?;
detach_build_workers($pid);
return 127 if $got == -1;
return ($status & 127) ? 128 + ($status & 127) : $status >> 8;
}
@@ -647,34 +651,60 @@ sub lock_path_for {
return "$dir/xcatbld-" . lock_id_for($path) . ".lock";
}
# take_build_lock: take the checkout's lock, or die.
# Returns the open handle -- the lock is held for as long as the caller keeps it.
sub take_build_lock {
my ($path, $dir) = @_;
require POSIX;
# A directory, not an flock. A build tree can live on an NFS re-export, where the kernel
# refuses locks outright: every attempt answers errno 524. mkdir(2) is arbitrated by the
# server and needs no lock daemon.
my $lockdir = lock_path_for($path, $dir) . '.d';
unless (mkdir $lockdir) {
die "FATAL: cannot take $lockdir: $!\n" unless $! == POSIX::EEXIST();
my $who = ''; if (open(my $h, '<', "$lockdir/owner")) { local $/; $who = <$h> // ''; close $h }
chomp $who;
die "FATAL: another build of $path already holds $lockdir"
. ($who ? " (held by [$who])" : "") . "\n";
# acquire_lock_dir: take one named lock, or die.
#
# XCAT::NFSLock, not an flock and not a bare mkdir. Its protocol recovers a lock whose owner is
# provably dead, which is the whole point here: a build killed by SIGKILL or the OOM-killer runs
# no handler, and a lock with no recovery then fails every later build of the same target until
# an operator removes it by hand.
#
# The lock lives in /var/lock, which is local. What it guards is host-local too --
# /etc/mock/<cfg>.cfg, /var/lib/mock/<cfg>/ and its buildroot.lock -- so the scope is one host
# and one target. A lock on the shared checkout would serialise the per-arch builds of one
# checkout that run on two hosts, which share nothing.
#
# $held is the advice printed when another build still holds the lock. $what names what contends,
# so the two callers keep their own wording -- a checkout for builddebs.pl, a mock target for
# buildrpms.pl -- while the protocol lives in one place.
sub acquire_lock_dir {
my ($lockdir, $what, $held) = @_;
require XCAT::NFSLock;
$what = $lockdir unless defined $what;
$held = '' unless defined $held;
# 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);
};
unless ($lock) {
my $why = $@ // '';
$why =~ s/\s+\z//;
$why =~ s/^/ /mg;
# NFSLock says which failure it was. Only an exhausted retry budget means something else
# holds the lock; a mkdir that failed outright is a different problem, and every failure
# used to be reported as a concurrent build.
my $contended = $why =~ /\bstill held after [0-9]+ retr/;
die "FATAL: cannot take the build lock for $what\n"
. ($contended ? " another build still holds $lockdir\n" : '')
. "$why\n"
. ($contended ? $held : '');
}
if (open(my $ow, '>', "$lockdir/owner")) { print {$ow} "pid=$$\n"; close $ow }
# The caller keeps the returned value; release is by pid so a fork cannot free the parent's.
my $owner = $$;
my $lock = XCAT::BuildUtils::_BuildLock->new($lockdir, $owner);
push @LIVE_LOCKS, $lock;
# Registered weakly, so holding it here does not keep the lock alive past its caller's
# scope. The registry exists only so a signal can release what DESTROY will not.
require Scalar::Util;
push @LIVE_LOCKS, $lock;
Scalar::Util::weaken($LIVE_LOCKS[-1]);
return $lock;
}
# take_build_lock: take the checkout's lock, or die.
# Returns the guard object -- the lock is held for as long as the caller keeps it.
sub take_build_lock {
my ($path, $dir) = @_;
return acquire_lock_dir(lock_path_for($path, $dir) . '.d', $path);
}
#-------------------------------------------------------------------------------
=head3 release_build_locks
@@ -700,6 +730,103 @@ sub release_build_locks {
return;
}
# attach_build_workers: record a process group on every lock this process holds. A build lock
# protects a checkout and a mock target, and sh() runs each command in its own group, so the
# lock has to name the group rather than only the wrapper that started it.
sub attach_build_workers {
my ($pgid) = @_;
my $all = 1;
for my $l (@LIVE_LOCKS) {
next unless defined $l;
$all = 0 unless $l->attach($pgid);
}
return $all;
}
#-------------------------------------------------------------------------------
=head3 start_build_worker
Descriptions:
Fork a process in its own process group, and let it run only after every held build lock
records that group.
A lock whose owner is dead is recoverable unless it records a live group. A worker that
runs before its record exists can therefore outlive a killed parent while a second build
takes the lock. The child waits on a pipe. It continues only when the parent writes to the
pipe, which the parent does after every attach succeeds. When the parent dies first, the
child reads end-of-file and exits.
Arguments:
$fork - optional coderef that forks, with the return value of fork(). Default: fork().
Parallel::ForkManager callers pass sub { $pm->start($ident) }.
Returns:
In the parent, in list context: ($pid, 1) when the worker may run, ($pid, 0) when the record
failed and the worker exits with status 127, and () when the fork failed. In scalar
context: the pid, or undef.
In the child: 0, after the parent released it. The child never returns otherwise.
When $fork returns 0 without forking, as Parallel::ForkManager does with max_procs 0: 0
(list context: (0, 1)) in the calling process, which then runs the work itself.
=cut
#-------------------------------------------------------------------------------
sub start_build_worker {
my ($fork) = @_;
require POSIX;
$fork //= sub { fork() };
pipe(my $gate_r, my $gate_w) or return;
my $self = $$;
my $pid = $fork->();
unless (defined $pid) {
my $error = $!;
close($gate_r);
close($gate_w);
$! = $error;
return;
}
# Parallel::ForkManager->new(0) does not fork, and start() returns 0 in this process. The
# work then runs here, under the locks this process already holds.
if (!$pid && $$ == $self) {
close($gate_r);
close($gate_w);
return wantarray ? (0, 1) : 0;
}
unless ($pid) {
close($gate_w);
POSIX::setpgid(0, 0) or POSIX::_exit(127);
my ($got, $go) = (undef, '');
do { $got = sysread($gate_r, $go, 1) } while (!defined($got) && $!{EINTR});
POSIX::_exit(127) unless $got && $go eq 'g';
close($gate_r);
return 0;
}
close($gate_r);
# Both sides set the group, so the record never names a pid that is not yet a group leader.
# ESRCH means the pid is not a child of this process. A record of that group can keep the
# lock forever, and the gated child has not run, so record nothing.
my $ok = (POSIX::setpgid($pid, $pid) || $!{EACCES}) ? 1 : 0;
$ok = attach_build_workers($pid) if $ok;
if ($ok) {
# A worker that died after the record leaves no reader. SIGPIPE would end the builder
# and skip its cleanup, so let the write fail with EPIPE instead.
local $SIG{PIPE} = 'IGNORE';
$ok = 0 if (syswrite($gate_w, 'g') // 0) != 1;
}
close($gate_w);
# Scalar context gives the pid, so `start_build_worker(...) and next` keeps the meaning of
# `$pm->start and next` whether or not the record succeeded.
return wantarray ? ($pid, $ok) : $pid;
}
# detach_build_workers: drop that record. Called once the group is reaped, and from
# cancel_build once kill(0, -pgid) answers ESRCH.
sub detach_build_workers {
my ($pgid) = @_;
for my $l (@LIVE_LOCKS) { $l->detach($pgid) if defined $l }
return;
}
#-------------------------------------------------------------------------------
=head3 install_build_cancellation
@@ -777,13 +904,16 @@ sub cancel_build {
# The shell exiting is not enough: its workers may still exist.
if (!kill(0, -$pgid) && $!{ESRCH}) {
$CURRENT_CHILD = undef;
detach_build_workers($pgid);
release_build_locks();
return;
}
select undef, undef, undef, 0.1;
}
}
# Never let END/DESTROY unlock a checkout whose workers may still run.
# Never let END/DESTROY unlock a checkout whose workers may still run. The group is
# still recorded on the lock, because it was not detached, so a later build reads that
# record and refuses the lock instead of recovering it from a dead owner.
warn "FATAL: build process group $pgid has not disappeared; retaining locks\n";
POSIX::_exit(1);
}
@@ -791,21 +921,6 @@ sub cancel_build {
return;
}
{ package XCAT::BuildUtils::_BuildLock;
sub new { my ($c,$d,$p)=@_; return bless { dir=>$d, pid=>$p, released=>0 }, $c }
# Idempotent: a signal handler and then DESTROY both reach here, and the second must not
# remove a directory a LATER build has since taken.
sub release {
my $s = shift;
return if $s->{released};
$s->{released} = 1;
return unless $$ == $s->{pid};
unlink "$s->{dir}/owner";
rmdir $s->{dir};
return;
}
sub DESTROY { shift->release }
}
# The packages a target does not build, and why. A rule names either the target
# prefixes that do NOT build the package, or, with `only`, the pattern of the
+982
View File
@@ -0,0 +1,982 @@
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.
#
# Names in this module
# lock.d the lock path given to acquire
# lock.d/metadata the metadata of the owner
# 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.
# 2. machine-id is unique among participating hosts.
# 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, 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
# lock.d/metadata contains:
# machine-id, boot-id, pid, pstart, token, hash
#
# Ownership identity: (machine-id, boot-id, pid, pstart, token)
# token is random per acquisition.
# hash = HASH(canonical(SORT(k, v))) over all fields except hash.
#
# 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. 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
# R > 0, δ >= 0, T >= 3, T > 2δ
#
# Generic retry:
# if retries >= R: fail
# sleep(T + rand(-δ, δ))
# retries++
# goto 1
#
# Protocol
# 1. mkdir lock.d
# - success: write valid metadata, go to 8
# - EEXIST: continue
# - other error: fail
# 2. Read and validate the metadata.
# - invalid or missing: retry
# - different machine-id: retry
# - same host: save the observed ownership identity
# 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, 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. 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
#
# 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
# 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.
#
# 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), 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
sweep_stranded live_workers);
my @IDENTITY = qw(machine-id boot-id pid pstart token);
#--------------------------------------------------------------------------------
=head3 acquire
Descriptions:
Take the lock at $path with steps 1 to 7 of the protocol.
Arguments:
$path: path of lock.d
%opt:
label => word for messages (default "lock")
delay => T, seconds, 3 or more (default 3)
jitter => δ, seconds, 0 or more and less than T/2 (default 0.5)
retries => R, more than 0 (default: timeout / T, at least 1)
timeout => seconds to wait, used when retries is not given (default 0)
quiet => 1 to print no log lines for this lock
Returns:
A lock object. Dies after R retries, naming the lock and its owner.
=cut
#--------------------------------------------------------------------------------
sub acquire {
my ($class, $path, %opt) = @_;
my $label = $opt{label} // 'lock';
my $delay = $opt{delay} // 3;
my $jitter = $opt{jitter} // 0.5;
die "Invalid delay $delay for $label: must be 3s or more\n" unless $delay >= 3;
die "Invalid jitter $jitter for $label: must be 0 or more\n" unless $jitter >= 0;
die "Invalid jitter $jitter for $label: must be less than half the delay\n"
unless $delay > 2 * $jitter;
my $retries = $opt{retries};
unless (defined($retries)) {
my $timeout = $opt{timeout} // 0;
$retries = int($timeout / $delay);
$retries++ if $retries * $delay < $timeout;
$retries = 1 if $retries < 1;
}
die "Invalid retries $retries for $label: must be a whole number more than 0\n"
unless $retries =~ /\A[1-9][0-9]*\z/;
# The last component names the lock itself. basename would turn '' into './' and drop a
# trailing slash, so the raw path is checked.
my ($name) = ($path // '') =~ m{(?:\A|/)([^/]+)\z};
die "Invalid $label path '" . ($path // '') . "'\n"
if !defined($name) || $name eq '.' || $name eq '..';
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)) {
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;
}
my $error = $@;
unlink("$abs/metadata");
rmdir($abs);
die $error;
}
die "Cannot create $label $abs: $!\n" unless $! == EEXIST;
# Step 2.
my $observed = _read_metadata($abs);
$seen = $observed if defined($observed);
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;
}
}
}
last if $count >= $retries;
$self->_log('wait', sprintf('retry %d/%d, owner %s', $count + 1, $retries, _describe($seen)));
_sleep(_wait($delay, $jitter));
}
my $who = _describe($seen);
$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";
}
#--------------------------------------------------------------------------------
=head3 release
Descriptions:
Steps 9 to 12 of the protocol. Waits while another process holds
lock.borrow. A forked child of the owner does nothing, and a lock whose
metadata names another acquisition is left alone.
Arguments:
none
Returns:
1 when the lock was removed, 0 otherwise.
=cut
#--------------------------------------------------------------------------------
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.
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.
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})) {
# 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";
}
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';
}
}
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}));
}
}
sub path { return $_[0]{path} }
#--------------------------------------------------------------------------------
=head3 this_process
Descriptions:
The ownership identity of this process with a fresh token.
Arguments:
none
Returns:
A hash ref with machine-id, boot-id, pid, pstart and token.
=cut
#--------------------------------------------------------------------------------
sub this_process {
my $here = _here();
return {
'machine-id' => $here->{'machine-id'},
'boot-id' => $here->{'boot-id'},
pid => $$,
pstart => process_start($$) // die("Cannot read the start time of pid $$\n"),
token => _token(),
};
}
#--------------------------------------------------------------------------------
=head3 format_metadata
Descriptions:
The content of lock.d/metadata: one "key=value" line per field, sorted
by key, and the hash line.
Arguments:
$fields: hash ref with machine-id, boot-id, pid, pstart and token
Returns:
The metadata string.
=cut
#--------------------------------------------------------------------------------
sub format_metadata {
my ($fields) = @_;
my $canonical = _canonical($fields);
return $canonical . 'hash=' . sha256_hex($canonical) . "\n";
}
#--------------------------------------------------------------------------------
=head3 parse_metadata
Descriptions:
Validate the content of lock.d/metadata. A partial read, an unknown or
repeated field, a malformed value and a hash that does not match all
make the metadata invalid.
Arguments:
$text: the content of lock.d/metadata, or undef
Returns:
A hash ref of the identity fields, or undef when the metadata is invalid.
=cut
#--------------------------------------------------------------------------------
sub parse_metadata {
my ($text) = @_;
return undef unless defined($text) && $text =~ /\n\z/;
my %field;
for my $line (split(/\n/, $text)) {
my ($key, $value) = $line =~ /\A([a-z-]+)=([^=\s]+)\z/ or return undef;
return undef if exists($field{$key});
$field{$key} = $value;
}
my $hash = delete($field{hash});
return undef unless defined($hash) && keys(%field) == @IDENTITY;
for my $key (@IDENTITY) {
return undef unless defined($field{$key});
}
return undef unless $field{pid} =~ /\A[1-9][0-9]*\z/ && $field{pstart} =~ /\A[0-9]+\z/;
return undef unless $hash eq sha256_hex(_canonical(\%field));
return \%field;
}
#--------------------------------------------------------------------------------
=head3 owner_is_dead
Descriptions:
Step 5: decide from facts alone whether a recorded owner is dead. Only
the owner's machine can know. Any other machine answers "not proven".
Arguments:
$owner: a hash ref from parse_metadata, or undef
$here: hash ref with machine-id, boot-id and start_of, a code ref that
returns the start time of a pid on this machine, or undef when
no such process exists
Returns:
1 when the owner is provably dead, 0 otherwise.
=cut
#--------------------------------------------------------------------------------
sub owner_is_dead {
my ($owner, $here) = @_;
return 0 unless defined($owner);
return 0 unless $owner->{'machine-id'} eq $here->{'machine-id'};
return 1 unless $owner->{'boot-id'} eq $here->{'boot-id'};
my $start = $here->{start_of}->($owner->{pid});
return 1 unless defined($start);
return $start eq $owner->{pstart} ? 0 : 1;
}
#--------------------------------------------------------------------------------
=head3 process_start
Descriptions:
The start time of a process, field 22 of /proc/<pid>/stat, in clock ticks
since boot. A reused pid has a later start time.
Arguments:
$pid: the process id
Returns:
The start time, or undef when no such process exists.
=cut
#--------------------------------------------------------------------------------
sub process_start {
my ($pid) = @_;
open(my $fh, '<', "/proc/$pid/stat") or return undef;
my $stat = <$fh>;
close($fh);
return undef unless defined($stat);
# The command name, field 2, may contain spaces and parentheses.
$stat =~ s/\A.*\)\s+//s or return undef;
my @field = split(/\s+/, $stat);
return $field[19];
}
sub _log {
my ($self, $event, $detail) = @_;
return if $self->{quiet};
my $now = Time::HiRes::time();
my $time = strftime('%Y-%m-%dT%H:%M:%S', gmtime($now)) . sprintf('.%03dZ', ($now - int($now)) * 1000);
my $host = (split(/\./, hostname() || 'unknown'))[0];
my $line = join(' ', '[nfslock]', $time, $host, "pid=$$", $event, $self->{label}, $self->{path},
defined($detail) ? $detail : ());
print "$line\n";
}
sub _canonical {
my ($fields) = @_;
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);
}
# A reader can see this file half written. The hash makes that read invalid.
sub _write_metadata {
my ($path, $identity) = @_;
my $file = "$path/metadata";
my $fh;
open($fh, '>', $file) && print({$fh} format_metadata($identity)) && close($fh)
or die "Cannot write $file: $!\n";
}
sub _read_metadata {
my ($path) = @_;
open(my $fh, '<', "$path/metadata") or return undef;
local $/;
my $text = <$fh>;
close($fh);
return parse_metadata($text);
}
sub _wait {
my ($delay, $jitter) = @_;
return $delay + (2 * rand() - 1) * $jitter;
}
sub _sleep {
my ($seconds) = @_;
Time::HiRes::sleep($seconds);
}
sub _token {
if (open(my $fh, '<:raw', '/dev/urandom')) {
my $read = read($fh, my $bytes, 16);
close($fh);
return unpack('H*', $bytes) if defined($read) && $read == 16;
}
return join('', map { sprintf('%08x', int(rand(2**32))) } 1 .. 4);
}
# Assumption 2 needs a real machine-id. A host without one cannot take part.
sub _here {
return {
'machine-id' => _first_line('/etc/machine-id')
// die("Cannot read /etc/machine-id: an NFS lock needs a machine id\n"),
'boot-id' => _first_line('/proc/sys/kernel/random/boot_id')
// die("Cannot read the boot id of this machine\n"),
start_of => \&process_start,
};
}
sub _first_line {
my ($file) = @_;
open(my $fh, '<', $file) or return undef;
my $line = <$fh>;
close($fh);
return undef unless defined($line);
chomp($line);
return length($line) ? $line : undef;
}
sub _describe {
my ($owner) = @_;
return 'an unknown owner' unless defined($owner);
return sprintf('pid %s on machine %s', $owner->{pid}, $owner->{'machine-id'});
}
# An absolute path in the message, without resolving the lock itself.
sub _absolute {
my ($path) = @_;
my $dir = abs_path(dirname($path)) // dirname($path);
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;
+1 -1
View File
@@ -498,7 +498,7 @@ SCRIPT
# ----------------------------------------------------------------- main ------
# A cancelled build must not keep the checkout. The lock releases in DESTROY, which perl does
# not run when a signal ends the process, so a killed build left its directory behind and the
# next build of that checkout died on "another build already holds" naming a pid that had
# next build of that checkout died on "another build still holds" naming a pid that had
# already exited. buildrpms.pl has released its lock on cancellation for some time; this is the
# Debian builder catching up.
#
+31 -28
View File
@@ -61,8 +61,9 @@ use XCAT::BuildUtils qw(git_revision source_date_epoch sh sh_or_die usage buildi
write_script read_line targetarch_from_target
openeuler_build_target openeuler_repo_subdir
package_skip_reason
mock_config_text);
use POSIX (); # EEXIST, for the directory build lock (see main())
mock_config_text acquire_lock_dir
start_build_worker detach_build_workers);
use POSIX (); # WNOHANG, for the non-blocking waitpid in abort_builds()
use Getopt::Long qw(GetOptions);
use POSIX qw(strftime);
use Parallel::ForkManager;
@@ -889,16 +890,12 @@ sub merge_core_repos {
# file and the cached chroot dirs left behind are normal mock state, not leaks.)
my %MOCK_INFLIGHT; # ForkManager child pid => mock chroot (-r) name it is building
my $ABORTING = 0;
my $BUILD_LOCK_DIR; # per-target build lock, an atomic mkdir rather than an flock. The build
# tree can live on an NFS re-export, where the kernel refuses locks
# outright ("Clients are not allowed to get file locks or delegations from
# a reexport server"), so every flock there fails with errno 524. mkdir(2)
# is arbitrated by the server and needs no lock daemon. File-scoped so the
# release runs once, from END, for the whole process.
my $BUILD_LOCK_PID; # the pid that took it. ForkManager children inherit $BUILD_LOCK_DIR, and
# their END would release the PARENT's lock -- the flock this replaces
# could not be released by a child, and neither may this.
END { rmdir $BUILD_LOCK_DIR if defined $BUILD_LOCK_DIR and defined $BUILD_LOCK_PID and $$ == $BUILD_LOCK_PID }
my $BUILD_LOCK; # per-target build lock, an XCAT::NFSLock through
# XCAT::BuildUtils::acquire_lock_dir. Held in a file-scoped variable
# because the guard releases on DESTROY: discarding it would free the
# lock at the end of the statement that took it. release checks the pid,
# so a ForkManager child cannot free the PARENT's lock.
END { $BUILD_LOCK->release if defined $BUILD_LOCK }
my @CHILD_FAILURES; # idents (chroot names) of ForkManager children that exited non-zero
@@ -970,7 +967,7 @@ sub abort_builds {
warn "[buildrpms] abort cleanup done\n";
# The re-raise below kills this process by signal, and END blocks do not run then. Release the
# build lock here or a killed build strands it for every later run.
rmdir $BUILD_LOCK_DIR if defined $BUILD_LOCK_DIR and defined $BUILD_LOCK_PID and $$ == $BUILD_LOCK_PID;
$BUILD_LOCK->release if defined $BUILD_LOCK;
$SIG{$sig} = 'DEFAULT';
kill $sig, $$; # re-raise for the correct exit status
}
@@ -1003,24 +1000,27 @@ sub main {
# and race the shared chroot -- and abort_builds' fallback lazy-unmounts this build's own chroot
# binds, which for the SAME target(+ext) are the very dirs a peer uses. So refuse to run a second
# build of the same target(+ext) concurrently. Distinct targets / --mock-uniqueext are independent
# and never conflict. (Held for the process lifetime via $BUILD_LOCK_FH, a file-scoped handle.)
# and never conflict. (Held for the process lifetime via $BUILD_LOCK, a file-scoped guard.)
{
my $key = join('-', $opts{targets}->@*)
. ($opts{mock_uniqueext} ? "-$opts{mock_uniqueext}" : "");
$key =~ s/[^A-Za-z0-9._-]/-/g;
my $lock = "/var/lock/buildrpms.$key.lock.d";
{
unless (mkdir $lock) {
die "FATAL: cannot take the build lock $lock: $!\n" unless $! == POSIX::EEXIST();
die "FATAL: another buildrpms.pl is already building target '@{$opts{targets}}'"
. ($opts{mock_uniqueext} ? " (uniqueext=$opts{mock_uniqueext})" : "") . ".\n"
. " ($lock is held). Concurrent builds of the same target collide on the shared\n"
. " /etc/mock + /var/lib/mock chroot namespace (wrong NVR + a killed peer's\n"
. " cleanup unmounts this build's chroot). Serialize them, or pass a distinct\n"
. " --mock-uniqueext per build.\n";
}
$BUILD_LOCK_DIR = $lock; $BUILD_LOCK_PID = $$;
}
# /var/lock, not the checkout: what this lock guards is host-local, so a lock on the
# shared tree would serialise the per-arch builds of one checkout that run on two hosts.
#
# acquire_lock_dir, not a bare mkdir: NFSLock recovers a lock whose owner is provably
# dead. The copy that used to live here recorded no owner at all, and `use autodie`
# above turned its EEXIST branch into dead code, so a build killed with SIGKILL left the
# directory and failed every later build of the target with autodie's raw
# "Can't mkdir(...): File exists".
$BUILD_LOCK = acquire_lock_dir($lock,
"target '@{$opts{targets}}'"
. ($opts{mock_uniqueext} ? " (uniqueext=$opts{mock_uniqueext})" : ""),
" Concurrent builds of the same target collide on the shared /etc/mock +\n"
. " /var/lib/mock chroot namespace (wrong NVR + a killed peer's cleanup\n"
. " unmounts this build's chroot). Serialize them, or pass a distinct\n"
. " --mock-uniqueext per build.\n");
}
# A builder killed with SIGKILL together with this parent leaves its directory behind.
@@ -1047,6 +1047,9 @@ sub main {
$pm->run_on_finish(sub {
my ($pid, $exit_code, $ident, $exit_signal, $core_dump) = @_;
delete $MOCK_INFLIGHT{$pid};
# The builder's record stays on the build lock until it is reaped, so a parent killed
# between two sh() calls leaves a lock that a later build refuses.
detach_build_workers($pid);
remove_build_sources_dir($SOURCES_BASE, $pid);
# A child that die()s exits non-zero; one killed by a SIGNAL (SIGKILL / OOM-killer) is reaped
# with $exit_code==0 but $exit_signal!=0 (and maybe $core_dump). Checking $exit_code alone
@@ -1059,7 +1062,7 @@ sub main {
my ($pkg, $target) = $pair->@*;
my $ext = $opts{mock_uniqueext} ? "-$opts{mock_uniqueext}" : "";
my $chroot = "$pkg-$target$ext"; # matches buildspkgs/buildpkgs `-r`
$pm->start($chroot) and next;
start_build_worker(sub { $pm->start($chroot) }) and next;
$SIG{INT} = $SIG{TERM} = 'DEFAULT'; # child: die on signal; the parent cleans up
buildall($pkg, $target);
@@ -1076,7 +1079,7 @@ sub main {
}
for my $target ($opts{targets}->@*) {
$pm->start and next; # no chroot ident: update_repo runs no mock
start_build_worker(sub { $pm->start }) and next; # no chroot ident: update_repo runs no mock
$SIG{INT} = $SIG{TERM} = 'DEFAULT';
update_repo($target);
+1
View File
@@ -94,6 +94,7 @@ sub run_builder {
"$fixture/dep/openeuler24.03sp3/x86_64", "$fixture/dep/openeuler24.03/ppc64le", "$fixture/dep/el9/x86_64");
copy($ENV{XCAT_TEST_BUILDRPMS} || repo_path('buildrpms.pl'), "$fixture/buildrpms.pl") or die $!;
copy(repo_path('build-utils/lib/XCAT/BuildUtils.pm'), "$fixture/build-utils/lib/XCAT/BuildUtils.pm") or die $!;
copy(repo_path('build-utils/lib/XCAT/NFSLock.pm'), "$fixture/build-utils/lib/XCAT/NFSLock.pm") or die $!;
copy($driver, "$fixture/driver.pl") or die $!;
write_file("$fixture/Version", "2.18.0\n");
write_file("$fixture/Gitepoch", "1756000000\n");
@@ -118,6 +118,7 @@ sub run_builder {
make_path(map {"$fixture/$_"} qw(build-utils/lib/XCAT bin mock locks tmp xCAT-release home/rpmbuild/SOURCES));
copy($builder, "$fixture/buildrpms.pl") or die $!;
copy(repo_path('build-utils/lib/XCAT/BuildUtils.pm'), "$fixture/build-utils/lib/XCAT/BuildUtils.pm") or die $!;
copy(repo_path('build-utils/lib/XCAT/NFSLock.pm'), "$fixture/build-utils/lib/XCAT/NFSLock.pm") or die $!;
copy($spec, "$fixture/xCAT-release/xCAT-release.spec") or die $!;
write_file("$fixture/xCAT-release/$_", $original{$_}) for @files;
write_file("$fixture/Version", "2.19.0\n");
@@ -5,7 +5,8 @@ mount --make-rslave /
export PYTHONPATH="$(dirname "$0")${PYTHONPATH:+:$PYTHONPATH}"
etc="$BUILD_FIXTURE/etc"
mkdir -p "$etc/mock" "$etc/yum.repos.d"
for file in passwd group nsswitch.conf ld.so.cache; do
# machine-id as well: the build lock is an XCAT::NFSLock, and its ownership identity needs one.
for file in passwd group nsswitch.conf ld.so.cache machine-id; do
[ ! -f "/etc/$file" ] || /bin/cp "/etc/$file" "$etc/$file"
done
/bin/cp "$BUILD_FIXTURE/os-release" "$etc/os-release"
+1
View File
@@ -44,6 +44,7 @@ for my $repo (qw(xcat-core xcat-dep xcat-dep-common)) {
like($files, qr{^/etc/yum\.repos\.d/\Q$repo\E\.repo\t17$}m, "$repo remains config(noreplace)");
}
for my $relative (qw(buildrpms.pl build-utils/lib/XCAT/BuildUtils.pm
build-utils/lib/XCAT/NFSLock.pm
build-utils/sync-fips-policy build-utils/fips-policy.sh
xCAT-genesis-scripts/usr/lib/xcat/fips.sh xCAT/postscripts/xcatlib.sh)) {
make_path(dirname("$root/work/$relative"));
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/perl
# A build killed with SIGKILL or by the OOM-killer runs no handler, so it leaves its lock
# behind. Every later build of the same target then fails until an operator removes the lock by
# hand -- /var/lock/buildrpms.openeuler-20.03sp4-x86_64.lock.d did that for seven days.
#
# The build lock is an XCAT::NFSLock, whose protocol recovers a lock whose owner is provably
# dead. The protocol itself is tested in xcat-dep's t/nfslock_borrow_recovery.t. These checks
# cover what xcat-core adds: that the build lock recovers from a killed holder, that a live
# holder is still refused, that a dead holder whose BUILD WORKERS still run is refused, and that
# the refusal says what actually happened -- contention and a mkdir that failed outright are
# different problems and used to print the same sentence.
use strict;
use warnings;
use Test::More;
use File::Temp qw(tempdir);
use POSIX ();
use Time::HiRes ();
use FindBin qw($Bin);
use lib "$Bin/../../build-utils/lib";
use XCAT::BuildUtils qw(take_build_lock);
# A bounded read of one byte. sysread can return fewer bytes than asked for, so a handshake
# built on one read of two bytes is a timing test: it passed on a fast machine and killed the
# wrapper before it held the lock.
sub await_byte {
my ($fh, $seconds) = @_;
my $mask = '';
vec($mask, fileno($fh), 1) = 1;
return undef unless select(my $ready = $mask, undef, undef, $seconds);
my $got = sysread($fh, my $byte, 1);
return defined($got) && $got == 1 ? $byte : undef;
}
my $CKOUT = '/opt/builds/devel/xcat-core';
my $TMP = tempdir(CLEANUP => 1);
my $DIR = XCAT::BuildUtils::lock_path_for($CKOUT, $TMP) . '.d';
# ---- a holder killed with SIGKILL strands nothing --------------------------------------
# The defect, stated as the property that fixes it. This cannot pass on a lock with no
# recovery: the directory outlives the process and the next acquirer fails on it.
#
# This holder runs no build command, so it covers a wrapper and nothing below it. The worker
# case is separate, further down, because a dead wrapper says nothing about the group it
# started.
pipe(my $ready, my $tell) or die "pipe: $!";
my $holder = fork();
die "fork: $!" unless defined $holder;
if (!$holder) {
close $ready;
my $got = eval { take_build_lock($CKOUT, $TMP) };
syswrite($tell, defined($got) ? "held\n" : "failed\n");
# Hold until killed. _exit is never reached; it is here so a stray wake cannot run the END
# blocks or flush the parent's inherited buffers.
sleep 300;
POSIX::_exit(0);
}
close $tell;
my $said = <$ready> // '';
close $ready;
is($said, "held\n", 'a child process takes the build lock');
ok(-d $DIR, 'control: the lock directory exists while that child holds it');
my $blocked = eval { take_build_lock($CKOUT, $TMP) };
ok(!defined $blocked, 'while the holder lives, a second build is refused');
my $refusal = $@ // '';
like($refusal, qr/another build still holds/, 'and the refusal reports contention');
like($refusal, qr/still held after [0-9]+ retr\w+ by pid \Q$holder\E\b/,
'and names the pid that holds it, so a live holder is told from any other failure');
like($refusal, qr/\Q$CKOUT\E/, 'which names the checkout that is building');
# ---- a lock that cannot be created is not reported as a concurrent build ----------------
# Every acquire failure used to print "another build already holds", with the contention advice,
# so an ENOENT or an EACCES sent the operator looking for a build that does not exist.
{
my $advice = "serialize them, or pass a distinct --mock-uniqueext\n";
my $got = eval {
XCAT::BuildUtils::acquire_lock_dir("$TMP/absent/xcatbld-x.lock.d", 'target zz', $advice);
};
my $said = $@ // '';
ok(!defined $got, 'a lock under a directory that does not exist is refused');
like($said, qr/No such file or directory/, 'and the refusal carries the error that happened');
unlike($said, qr/another build still holds|\Q$advice\E/,
'and claims no concurrent build, and prints no advice about one');
}
kill 'KILL', $holder;
waitpid($holder, 0);
ok(!kill(0, $holder), 'the holder is gone, killed with a signal it cannot handle');
my $after = eval { take_build_lock($CKOUT, $TMP) };
ok(defined $after, 'the build lock is recovered after its holder is SIGKILLed')
or diag "take_build_lock died: $@";
# ---- a different checkout is never blocked ---------------------------------------------
# The lock is keyed on the checkout, so two checkouts build at once. Asserted here because the
# recovery above must not have widened what one lock excludes.
my $other = eval { take_build_lock('/opt/builds/stable/xcat-core', $TMP) };
ok(defined $other, 'a build of a different checkout runs beside it');
undef $after;
ok(!-d $DIR, 'releasing the lock removes its directory');
# ---- a dead wrapper does not free a lock whose build workers still run -----------------
# sh() runs each build command in its OWN process group, so SIGKILL on the wrapper leaves that
# group running. A lock recovered from the dead wrapper then lets a second build into the same
# checkout. The lock records each attached group, and a group that still exists keeps the lock.
#
# BOTH halves are here. The blocking half alone is satisfied by a lock that recovers nothing, so
# the second half is what tells this rule from that one.
{
my $ckout = '/opt/builds/workers/xcat-core';
my $dir = XCAT::BuildUtils::lock_path_for($ckout, $TMP) . '.d';
pipe(my $stop_r, my $stop_w) or die "pipe: $!";
pipe(my $worker_r, my $worker_w) or die "pipe: $!";
pipe(my $held_r, my $held_w) or die "pipe: $!";
# The build worker: its own process group, and it outlives the wrapper that started it.
my $worker = fork();
die "fork: $!" unless defined $worker;
unless ($worker) {
close($stop_w); close($worker_r); close($held_r); close($held_w);
POSIX::setpgid(0, 0);
syswrite($worker_w, 'w');
sysread($stop_r, my $go, 1);
POSIX::_exit(0);
}
POSIX::setpgid($worker, $worker);
close($worker_w);
is(await_byte($worker_r, 20), 'w', 'control: the build worker runs in its own process group');
# The wrapper: takes the lock, records the worker, and waits to be killed.
my $wrapper = fork();
die "fork: $!" unless defined $wrapper;
unless ($wrapper) {
close($stop_r); close($stop_w); close($worker_r); close($held_r);
my $held = eval { take_build_lock($ckout, $TMP) };
XCAT::BuildUtils::attach_build_workers($worker) if $held;
syswrite($held_w, $held ? 'h' : 'f');
sleep 300;
POSIX::_exit(0);
}
close($stop_r); close($held_w);
# Read before the kill, so the wrapper is certainly holding the lock and has recorded the
# worker. Nothing here waits on a clock.
is(await_byte($held_r, 20), 'h', 'control: the wrapper holds the build lock');
ok(-d $dir, 'control: the build lock exists');
kill('KILL', $wrapper);
waitpid($wrapper, 0);
ok(!kill(0, $wrapper), 'control: the wrapper is gone, killed with a signal it cannot handle');
ok(kill(0, -$worker), 'control: its build worker group is still running');
my $second = eval { take_build_lock($ckout, $TMP) };
ok(!defined $second, 'a second build is refused while the dead wrapper\'s workers run');
like($@ // '', qr/process group $worker\b/, 'and the refusal names the group that holds it');
# THE OTHER HALF. The worker exits, and the same lock must now be recoverable.
syswrite($stop_w, 'g');
waitpid($worker, 0);
my $after = eval { take_build_lock($ckout, $TMP) };
ok(defined $after, 'once the worker group is gone the second build DOES take the lock')
or diag "take_build_lock died: $@";
undef $after;
undef $second;
close($_) for ($worker_r, $held_r, $stop_w);
}
# ---- a signal handler can release what DESTROY will not ---------------------------------
# DESTROY does not run when a signal ends the process, so cancel_build calls
# release_build_locks instead. That reaches a lock only while the lock is in the registry.
{
my $signalled = '/opt/builds/signal/xcat-core';
my $its_dir = XCAT::BuildUtils::lock_path_for($signalled, $TMP) . '.d';
my $lock = take_build_lock($signalled, $TMP);
ok(-d $its_dir, 'control: the lock directory exists while the guard is held');
XCAT::BuildUtils::release_build_locks();
ok(!-d $its_dir, 'release_build_locks frees a lock whose guard is still in scope');
}
# No lock state may survive, on any path above.
undef $other;
my @left = glob("$TMP/*.lock.d*");
is_deeply(\@left, [], 'no lock directory or borrow is left behind');
done_testing();
@@ -0,0 +1,191 @@
#!/usr/bin/perl
# A build lock whose owner is dead is recovered unless it records a live process group. So a
# process the build starts must be recorded BEFORE it runs: a worker that runs first can outlive
# a killed parent, and a second build then takes the lock while the first one still writes.
#
# These checks cover the three ways a worker could run unrecorded: the record fails, the parent
# dies before it records, and a Perl builder forked by Parallel::ForkManager runs between two
# sh() calls with no group of its own on the lock.
use strict;
use warnings;
use Test::More;
use File::Temp qw(tempdir);
use POSIX ();
use FindBin qw($Bin);
use lib "$Bin/../../build-utils/lib";
use Parallel::ForkManager;
use XCAT::BuildUtils qw(take_build_lock);
# A held lock whose attach the test controls.
{
package FakeLock;
sub new { my ($class, $attach) = @_; return bless { attach => $attach }, $class }
sub attach { my ($self, $pgid) = @_; return $self->{attach}->($pgid) }
sub detach { return 1 }
sub release { return 0 }
}
my $TMP = tempdir(CLEANUP => 1);
# A bounded read of one byte.
sub await_byte {
my ($fh, $seconds) = @_;
my $mask = '';
vec($mask, fileno($fh), 1) = 1;
return undef unless select(my $ready = $mask, undef, undef, $seconds);
my $got = sysread($fh, my $byte, 1);
return defined($got) && $got == 1 ? $byte : undef;
}
# True once no process is left in the group or with that pid.
sub gone_within {
my ($pid, $seconds) = @_;
for (1 .. $seconds * 10) {
return 1 if !kill(0, -$pid) && $!{ESRCH} && !kill(0, $pid) && $!{ESRCH};
select undef, undef, undef, 0.1;
}
return 0;
}
# ---- a record that fails stops the command --------------------------------------------
{
my $marker = "$TMP/ran-after-failed-record";
my $rc = do {
local @XCAT::BuildUtils::LIVE_LOCKS = (FakeLock->new(sub { 0 }));
local $SIG{__WARN__} = sub { };
XCAT::BuildUtils::sh(": > $marker");
};
is($rc, 127, 'sh() fails when a held lock cannot record the process group');
ok(!-e $marker, 'and the command never ran');
my $control = "$TMP/ran-after-record";
my $ok = do {
local @XCAT::BuildUtils::LIVE_LOCKS = (FakeLock->new(sub { 1 }));
XCAT::BuildUtils::sh(": > $control");
};
is($ok, 0, 'control: sh() runs the command when the record succeeds');
ok(-e $control, 'control: and the command wrote its file');
}
# ---- a parent that dies before it records starts nothing ------------------------------
# The fake attach ends the parent with _exit, which runs no handler, like SIGKILL would.
{
my $marker = "$TMP/ran-after-parent-died";
my $pgfile = "$TMP/worker-pgid";
my $parent = fork();
die "fork: $!" unless defined $parent;
unless ($parent) {
local @XCAT::BuildUtils::LIVE_LOCKS = (FakeLock->new(sub {
my ($pgid) = @_;
if (open(my $fh, '>', $pgfile)) { print {$fh} $pgid; close $fh }
POSIX::_exit(0);
}));
XCAT::BuildUtils::sh(": > $marker");
POSIX::_exit(1);
}
waitpid($parent, 0);
my $pgid = do { open(my $fh, '<', $pgfile) or die "no $pgfile: $!"; local $/; <$fh> };
like($pgid, qr/\A[1-9][0-9]*\z/, 'control: the parent reached the record and died there');
ok(gone_within($pgid, 20), 'the command process is gone');
ok(!-e $marker, 'and it never ran the command');
}
# ---- a pid that is not a child of this process is never recorded ----------------------
# A recorded group that is always alive, such as group 1, makes the lock unrecoverable. The
# release_repository.t schedule stub returns 1 from Parallel::ForkManager::start.
{
my @attached;
# No child holds the read end of the gate, so a write to it raises SIGPIPE.
local $SIG{PIPE} = "IGNORE";
my ($pid, $ok) = do {
local @XCAT::BuildUtils::LIVE_LOCKS = (FakeLock->new(sub { push @attached, @_; 1 }));
XCAT::BuildUtils::start_build_worker(sub { getppid() });
};
is($pid, getppid(), 'control: start_build_worker returns the pid the fork gave');
is($ok, 0, 'start_build_worker reports no record for a pid that is not its child');
is_deeply(\@attached, [], 'and no held lock records that group');
}
# ---- the record exists before the worker runs -----------------------------------------
{
my $ckout = '/opt/builds/record-first/xcat-core';
my $dir = XCAT::BuildUtils::lock_path_for($ckout, $TMP) . '.d';
my $lock = take_build_lock($ckout, $TMP);
my $seen = "$TMP/record-seen";
my ($pid, $ok) = XCAT::BuildUtils::start_build_worker();
die "fork: $!" unless defined $pid;
unless ($pid) {
my @mine = glob("$dir/workers/$$.*");
if (open(my $fh, '>', $seen)) { print {$fh} scalar(@mine); close $fh }
POSIX::_exit(0);
}
is($ok, 1, 'start_build_worker reports the record');
waitpid($pid, 0);
my $count = do { open(my $fh, '<', $seen) or die "no $seen: $!"; local $/; <$fh> };
is($count, 1, 'the worker finds its own group recorded on the lock when it starts');
XCAT::BuildUtils::detach_build_workers($pid);
undef $lock;
ok(!-d $dir, 'control: the lock is released once the worker is reaped and detached');
}
# ---- a ForkManager builder keeps the lock after its parent is killed ------------------
# buildrpms.pl runs each package build as a Perl ForkManager child, which writes files between
# its sh() calls. The child stands still here, in Perl, with no sh() command running.
{
my $ckout = '/opt/builds/forkmanager/xcat-core';
my $dir = XCAT::BuildUtils::lock_path_for($ckout, $TMP) . '.d';
pipe(my $up_r, my $up_w) or die "pipe: $!";
pipe(my $stop_r, my $stop_w) or die "pipe: $!";
my $wrapper = fork();
die "fork: $!" unless defined $wrapper;
unless ($wrapper) {
close($up_r);
my $lock = eval { take_build_lock($ckout, $TMP) };
POSIX::_exit(1) unless $lock;
my $pm = Parallel::ForkManager->new(1);
my $builder = XCAT::BuildUtils::start_build_worker(sub { $pm->start });
unless ($builder) {
close($stop_w);
syswrite($up_w, 'b');
sysread($stop_r, my $go, 1);
POSIX::_exit(0);
}
close($stop_r);
close($stop_w);
syswrite($up_w, 'w');
sleep 300;
POSIX::_exit(0);
}
close($up_w);
close($stop_r);
my $first = await_byte($up_r, 20) // '';
my $second = await_byte($up_r, 20) // '';
is(join('', sort $first, $second), 'bw', 'control: the wrapper holds the lock and its builder runs');
my @record = glob("$dir/workers/*");
is(scalar(@record), 1, 'the builder is recorded on the lock');
my ($builder) = ($record[0] // '') =~ m{/([0-9]+)\.[0-9]+\z};
kill('KILL', $wrapper);
waitpid($wrapper, 0);
ok(defined($builder) && kill(0, -$builder), 'control: the builder outlives its killed parent');
my $taken = eval { take_build_lock($ckout, $TMP) };
ok(!defined $taken, 'a second build is refused while the builder runs');
like($@ // '', qr/process group $builder\b/, 'and the refusal names the builder');
# The other half: once the builder exits, the lock is recoverable.
close($stop_w);
ok(gone_within($builder, 20), 'control: the builder exits');
my $after = eval { take_build_lock($ckout, $TMP) };
ok(defined $after, 'then a second build takes the lock') or diag("refused: $@");
undef $after;
undef $taken;
close($up_r);
}
my @left = glob("$TMP/*.lock.d*");
is_deeply(\@left, [], 'no lock directory or borrow is left behind');
done_testing();
@@ -0,0 +1,64 @@
#!/usr/bin/perl
# start_build_worker releases a gated worker by writing one byte to a pipe. When the worker
# dies after the record and before that write, the pipe has no reader. A write to it must
# fail with EPIPE and take the failure path. SIGPIPE must not end the build process, because
# a signal skips the cleanup that restores the checkout and releases the lock.
use strict;
use warnings;
use Test::More;
use POSIX ();
use FindBin qw($Bin);
use lib "$Bin/../../build-utils/lib";
use XCAT::BuildUtils ();
# A held lock whose attach the test controls.
{
package FakeLock;
sub new { my ($class, $attach) = @_; return bless { attach => $attach }, $class }
sub attach { my ($self, $pgid) = @_; return $self->{attach}->($pgid) }
sub detach { return 1 }
sub release { return 0 }
}
# Run start_build_worker in a stand-in for the builder, with the default SIGPIPE disposition.
# $attach runs as the record step. Returns the stand-in's wait status.
# Exit 2: the worker was refused. Exit 1: the worker was released.
sub launch_with {
my ($attach) = @_;
my $builder = fork();
die "fork: $!" unless defined $builder;
unless ($builder) {
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
$SIG{PIPE} = 'DEFAULT';
local @XCAT::BuildUtils::LIVE_LOCKS = (FakeLock->new($attach));
my ($pid, $ok) = XCAT::BuildUtils::start_build_worker();
POSIX::_exit(3) unless defined $pid;
POSIX::_exit(0) unless $pid; # the released worker
waitpid($pid, 0);
POSIX::_exit($ok ? 1 : 2);
}
waitpid($builder, 0);
return $?;
}
# ---- the worker dies after the record and before the release ---------------------------
{
my $status = launch_with(sub {
my ($pgid) = @_;
kill('KILL', $pgid);
waitpid($pgid, 0);
return 1;
});
is($status & 127, 0, 'the builder is not ended by a signal when the worker dies before release');
is($status >> 8, 2, 'and start_build_worker reports the worker as not released');
}
# ---- control: a live worker is released ------------------------------------------------
{
my $status = launch_with(sub { 1 });
is($status & 127, 0, 'control: the builder exits normally');
is($status >> 8, 1, 'control: start_build_worker releases a live worker');
}
done_testing();
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/perl
# buildrpms.pl starts each worker with start_build_worker(sub { $pm->start(...) }). With
# --nproc=0, Parallel::ForkManager does not fork: start() returns 0 in the original process,
# and the caller runs the work itself. start_build_worker must let that process continue. It
# must not wait on the gate as a worker would, because the process holds the only writer.
use strict;
use warnings;
use Test::More;
use POSIX ();
use FindBin qw($Bin);
use lib "$Bin/../../build-utils/lib";
use Parallel::ForkManager;
use XCAT::BuildUtils ();
# Start one worker through a ForkManager with $max_procs, in a stand-in for buildrpms.pl.
# The stand-in exits 0 when the work runs in it, 1 when a forked worker ran the work and
# exited 0, 2 when start_build_worker did not return 0 or a pid, and 3 when the work ran in
# the stand-in after its process group changed.
sub run_worker_loop {
my ($max_procs) = @_;
my $builder = fork();
die "fork: $!" unless defined $builder;
unless ($builder) {
open(STDOUT, '>', '/dev/null');
open(STDERR, '>', '/dev/null');
my ($self, $group) = ($$, getpgrp());
my $pm = Parallel::ForkManager->new($max_procs);
my $pid = XCAT::BuildUtils::start_build_worker(sub { $pm->start('pkg') });
POSIX::_exit(2) unless defined $pid;
unless ($pid) {
# The work. In a forked worker, $$ differs from the stand-in.
POSIX::_exit(5) if $$ != $self;
POSIX::_exit(3) if getpgrp() != $group;
$pm->finish;
$pm->wait_all_children;
POSIX::_exit(0);
}
waitpid($pid, 0);
POSIX::_exit($? == 5 << 8 ? 1 : 4);
}
waitpid($builder, 0);
return $?;
}
my $status = run_worker_loop(0);
is($status & 127, 0, 'the builder is not ended by a signal with --nproc=0');
is($status >> 8, 0, 'with --nproc=0 the work runs in the original process and its original group');
$status = run_worker_loop(1);
is($status >> 8, 1, 'control: with --nproc=1 a forked worker runs the work');
done_testing();
+5 -1
View File
@@ -38,7 +38,11 @@ ok( $first, 'the first build of a checkout takes the lock' );
my $second = eval { take_build_lock($devel, $lockdir) };
ok( !$second, 'a second build of the SAME checkout is refused' );
like( $@, qr/already holds/, 'and says which checkout is already building' );
my $refusal = $@ // '';
like( $refusal, qr/another build still holds/, 'and reports contention' );
like( $refusal, qr/still held after [0-9]+ retr\w+ by pid $$\b/,
'and names the pid holding it, so contention is told from any other failure' );
like( $refusal, qr/\Q$devel\E/, 'and names the checkout that is already building' );
# Different checkout: must not be blocked by the first.
my $stable = eval { take_build_lock('/opt/builds/stable/xcat-core', $lockdir) };
+6 -2
View File
@@ -4,7 +4,8 @@
# The build lock is released in DESTROY, and perl does not run DESTROY when a signal ends the
# process. So a cancelled build left its lock directory behind, and the next build of that
# checkout died on
# FATAL: another build of <path> already holds <dir> (held by [pid=NNNN])
# FATAL: cannot take the build lock for <path>
# another build still holds <dir>
# naming a pid that had already exited. One such directory blocked an openSUSE target across
# three consecutive runs before anyone looked at it.
#
@@ -36,7 +37,10 @@ my $ckout = tempdir(CLEANUP => 1);
ok(-d $path, 'the lock directory exists while it is held');
my $second = eval { XCAT::BuildUtils::take_build_lock($ckout, $lockdir) };
ok(!$second, 'a second build of the same checkout is refused');
like($@, qr/already holds/, 'and told which lock is held');
my $refusal = $@ // '';
like($refusal, qr/another build still holds/, 'and reported contention');
like($refusal, qr/still held after [0-9]+ retr\w+ by pid $$\b/,
'naming the pid that holds it, not the same sentence for every failure');
undef $l;
ok(!-d $path, 'releasing it removes the directory');
}
+2 -1
View File
@@ -153,7 +153,8 @@ ok( !grep( { $_ eq 'buildpkgs' } @{ stages_for(1) } ),
# build-utils/lib on @INC relative to its own directory.
my $sandbox = tempdir(CLEANUP => 1);
for my $needed (qw(buildrpms.pl Version
build-utils/lib/XCAT/BuildUtils.pm)) {
build-utils/lib/XCAT/BuildUtils.pm
build-utils/lib/XCAT/NFSLock.pm)) {
my $from = repo_path($needed);
die("$needed is missing from the repository\n") unless -r $from;
my $to = File::Spec->catfile($sandbox, split(m{/}, $needed));