Refactor Format
[gruntmaster-daemon.git] / lib / Gruntmaster / Daemon / Base.pm
CommitLineData
5c5cd38a
MG
1package Gruntmaster::Daemon::Base;
2
3use 5.014000;
4use strict;
5use warnings;
6use parent qw/Exporter/;
7our @EXPORT_OK = qw/watch/;
8our $VERSION = '0.001';
9
1fc8d024 10use Fcntl qw/:flock/;
5c5cd38a
MG
11use Linux::Inotify2;
12use Log::Log4perl qw/get_logger/;
13
14##################################################
15
16sub process{
17 my ($name, $dir, $cb) = @_;
18 my $logger = get_logger;
19 $logger->debug("Taking job $name...");
1fc8d024 20 open my $file, ">>$dir/$name/meta.yml";
e3a3697a 21 if (flock $file, LOCK_EX|LOCK_NB){
5c5cd38a
MG
22 $logger->debug("Successfully taken job $name, executing callback");
23 $cb->("$dir/$name");
24 } else {
25 $logger->debug("Job $name already taken");
26 }
1fc8d024 27 close $file;
5c5cd38a
MG
28}
29
30sub watch{
31 my ($dir, $cb) = @_;
32 for (<$dir/*>) {
33 s,$dir/,,;
34 process $_, $dir, $cb;
35 }
36
37 my $logger = Log::Log4perl->get_logger(__PACKAGE__);
38 my $inotify = Linux::Inotify2->new or $logger->logdie("Unable to create Linux::Inotify2 object: $!");
39 $inotify->watch($dir, IN_MOVED_TO, sub { process $_[0]->name, $dir, $cb }) or $logger->logdie("Error watching $dir: $!");
40 1 while $inotify->poll;
41 $logger->logdie("Inotify polling stopped: $!");
42}
43
441
This page took 0.026413 seconds and 4 git commands to generate.