1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Base class for per-inbox locking
5 package PublicInbox::Lock;
8 use Fcntl qw(:flock :DEFAULT);
11 # we only acquire the flock if creating or reindexing;
12 # PublicInbox::Import already has the lock on its own.
15 my $lock_path = $self->{lock_path};
16 croak 'already locked '.($lock_path // '(undef)') if $self->{lockfh};
17 return unless defined($lock_path);
18 sysopen(my $lockfh, $lock_path, O_WRONLY|O_CREAT) or
19 croak "failed to open $lock_path: $!\n";
20 flock($lockfh, LOCK_EX) or croak "lock $lock_path failed: $!\n";
21 $self->{lockfh} = $lockfh;
25 my ($self, $wake) = @_;
26 defined(my $lock_path = $self->{lock_path}) or return;
27 my $lockfh = delete $self->{lockfh} or croak "not locked: $lock_path";
29 syswrite($lockfh, '.') if $wake;
31 flock($lockfh, LOCK_UN) or croak "unlock $lock_path failed: $!\n";
32 close $lockfh or croak "close $lock_path failed: $!\n";