File Coverage

blib/lib/App/Base/Script/OnlyOne.pm
Criterion Covered Total %
statement 18 18 100.0
branch n/a
condition n/a
subroutine 6 6 100.0
pod n/a
total 24 24 100.0


line stmt bran cond sub pod time code
1             use strict;
2 2     2   51226 use warnings;
  2         8  
  2         56  
3 2     2   8 use Moose::Role;
  2         4  
  2         58  
4 2     2   10  
  2         4  
  2         12  
5             use Path::Tiny;
6 2     2   9744 use File::Flock::Tiny;
  2         4  
  2         116  
7 2     2   788  
  2         1996  
  2         252  
8             our $VERSION = '0.08'; ## VERSION
9              
10             =head1 NAME
11              
12             App::Base::Script::OnlyOne - do not allow more than one instance running
13              
14             =head1 SYNOPSIS
15              
16             use Moose;
17             extends 'App::Base::Script';
18             with 'App::Base::Script::OnlyOne';
19              
20             =head1 DESCRIPTION
21              
22             With this role your script will refuse to start if another copy of the script
23             is running already (or if it is deadlocked or entered an infinite loop because
24             of programming error). After start it tries to lock pid file, and if this is
25             not possible, it dies.
26              
27             =cut
28              
29             around script_run => sub {
30             my $orig = shift;
31             my $self = shift;
32              
33             my $class = ref $self;
34             my $piddir = $ENV{APP_BASE_DAEMON_PIDDIR} || '/var/run';
35             my $pidfile = path($piddir)->child("$class.pid");
36             my $lock = File::Flock::Tiny->write_pid("$pidfile");
37             die "Couldn't lock pid file, probably $class is already running" unless $lock;
38              
39             return $self->$orig(@_);
40             };
41              
42             no Moose::Role;
43 2     2   12 1;
  2         4  
  2         14  
44