Skip to content

Instantly share code, notes, and snippets.

@ferki
Created August 26, 2019 18:18
Show Gist options
  • Select an option

  • Save ferki/334c2ac0b2022e44c217a63c949db916 to your computer and use it in GitHub Desktop.

Select an option

Save ferki/334c2ac0b2022e44c217a63c949db916 to your computer and use it in GitHub Desktop.
Rex+inotify
use strict;
use warnings;
use Rex -feature => [ '1.4', 'exec_autodie' ];
use Linux::Inotify2;
use File::Basename qw(dirname);
use Time::HiRes qw(time tv_interval);
use DDP;
my $inotify = Linux::Inotify2->new();
no_ssh task 'agent', sub {
run_task 'config';
watch('/tmp/file');
$inotify->poll while 1;
};
task 'config', sub {
my $start = [ time() ];
LOCAL {
file '/tmp/file',
ensure => 'present',
content => qq(a),
owner => 'ferki',
group => 'ferki',
mode => '0600';
};
say 'Task run took: ' . tv_interval($start) * 1000 . ' milliseconds';
};
sub watch {
my $file = shift;
watch_file($file);
watch_parent($file);
}
sub watch_file {
my $file = shift;
$inotify->watch(
$file,
IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVE_SELF,
sub {
my $e = shift;
if ( $e->IN_IGNORED ) {
Rex::Logger::info('ignored');
$e->w->cancel;
watch_file($file);
}
Rex::Logger::info(qq(file event: ) . $e->mask);
run_task 'config';
if ( $e->IN_ATTRIB ) {
Rex::Logger::info('attrib escape');
$e->w->cancel;
watch_file($file);
}
}
);
}
sub watch_parent {
my $file = shift;
my $parent = dirname($file);
$inotify->watch(
$parent,
IN_CREATE,
sub {
my $e = shift;
return if $e->fullname ne $file;
Rex::Logger::info(qq(parentdir event: ) . $e->mask);
run_task 'config';
if ( $e->IN_MOVED_TO ) {
Rex::Logger::info('moved to escape');
$e->w->cancel;
watch_parent($file);
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment