1#
2# (c) Jan Gehring <jan.gehring@gmail.com>
3#
4# vim: set ts=2 sw=2 tw=0:
5# vim: set expandtab:
6
7package Rex::Shared::Var::Common;
8
9use 5.010001;
10use strict;
11use warnings;
12
13require Exporter;
14use base qw/Exporter/;
15our @EXPORT_OK = qw/__lock __store __retrieve/;
16
17our $VERSION = '1.13.4'; # VERSION
18
19use Fcntl qw(:DEFAULT :flock);
20use Storable;
21use File::Spec;
22
23# $PARENT_PID gets set when Rex starts.  This value remains the same after the
24# process forks.  So $PARENT_PID is always the pid of the parent process.  $$
25# however is always the pid of the current process.
26our $PARENT_PID = $$;
27our $FILE = File::Spec->catfile( File::Spec->tmpdir(), "vars.db.$PARENT_PID" );
28our $LOCK_FILE =
29  File::Spec->catfile( File::Spec->tmpdir(), "vars.db.lock.$PARENT_PID" );
30
31sub __lock {
32  sysopen( my $dblock, $LOCK_FILE, O_RDONLY | O_CREAT ) or die($!);
33  flock( $dblock, LOCK_EX )                             or die($!);
34
35  my $ret = $_[0]->();
36
37  close($dblock);
38
39  return $ret;
40}
41
42sub __store {
43  my $ref = shift;
44  store( $ref, $FILE );
45}
46
47sub __retrieve {
48  return {} unless -f $FILE;
49  return retrieve($FILE);
50
51}
52
53sub END {
54
55  # return if we exiting a child process
56  return unless $$ eq $PARENT_PID;
57
58  # we are exiting the master process
59  unlink $FILE      if -f $FILE;
60  unlink $LOCK_FILE if -f $LOCK_FILE;
61}
62
631;
64