File Coverage

blib/lib/App/Base/Script/OnlyOne.pm
Criterion Covered Total %
statement 12 12 100.0
branch n/a
condition n/a
subroutine 4 4 100.0
pod n/a
total 16 16 100.0


line stmt bran cond sub pod time code
1             package App::Base::Script::OnlyOne;
2 2     2   46288 use Moose::Role;
  2         2  
  2         16  
3              
4 2     2   7908 use Path::Tiny;
  2         4  
  2         126  
5 2     2   916 use File::Flock::Tiny;
  2         1646  
  2         222  
6              
7             =head1 NAME
8              
9             App::Base::Script::OnlyOne - do not allow more than one instance running
10              
11             =head1 VERSION
12              
13             This document describes App::Base version 0.05
14              
15             =head1 SYNOPSIS
16              
17             use Moose;
18             extends 'App::Base::Script';
19             with 'App::Base::Script::OnlyOne';
20              
21             =head1 DESCRIPTION
22              
23             With this role your script will refuse to start if another copy of the script
24             is running already (or if it is deadlocked or entered an infinite loop because
25             of programming error). After start it tries to lock pid file, and if this is
26             not possible, it dies.
27              
28             =cut
29              
30             around script_run => sub {
31             my $orig = shift;
32             my $self = shift;
33              
34             my $class = ref $self;
35             my $piddir = $ENV{APP_BASE_DAEMON_PIDDIR} || '/var/run';
36             my $pidfile = path($piddir)->child("$class.pid");
37             my $lock = File::Flock::Tiny->write_pid("$pidfile");
38             die "Couldn't lock pid file, probably $class is already running" unless $lock;
39              
40             return $self->$orig(@_);
41             };
42              
43 2     2   12 no Moose::Role;
  2         2  
  2         12  
44             1;
45              
46             __END__
47              
48             =head1 LICENSE AND COPYRIGHT
49              
50             Copyright (C) 2010-2014 Binary.com
51              
52             This program is free software; you can redistribute it and/or modify it
53             under the terms of either: the GNU General Public License as published
54             by the Free Software Foundation; or the Artistic License.
55              
56             See http://dev.perl.org/licenses/ for more information.
57              
58             =cut