File: Common.pm

package info (click to toggle)
rex 1.14.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,012 kB
  • sloc: perl: 35,587; xml: 264; sh: 51; makefile: 13
file content (60 lines) | stat: -rw-r--r-- 1,252 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#

package Rex::Shared::Var::Common;

use v5.12.5;
use warnings;

require Exporter;
use base qw/Exporter/;
our @EXPORT_OK = qw/__lock __store __retrieve/;

our $VERSION = '1.14.1'; # VERSION

use Fcntl qw(:DEFAULT :flock);
use Storable;
use File::Spec;

# $PARENT_PID gets set when Rex starts.  This value remains the same after the
# process forks.  So $PARENT_PID is always the pid of the parent process.  $$
# however is always the pid of the current process.
our $PARENT_PID = $$;
our $FILE = File::Spec->catfile( File::Spec->tmpdir(), "vars.db.$PARENT_PID" );
our $LOCK_FILE =
  File::Spec->catfile( File::Spec->tmpdir(), "vars.db.lock.$PARENT_PID" );

sub __lock {
  sysopen( my $dblock, $LOCK_FILE, O_RDONLY | O_CREAT ) or die($!);
  flock( $dblock, LOCK_EX )                             or die($!);

  my $ret = $_[0]->();

  close($dblock);

  return $ret;
}

sub __store {
  my $ref = shift;
  store( $ref, $FILE );
}

sub __retrieve {
  return {} unless -f $FILE;
  return retrieve($FILE);

}

sub END {

  # return if we exiting a child process
  return unless $$ eq $PARENT_PID;

  # we are exiting the master process
  unlink $FILE      if -f $FILE;
  unlink $LOCK_FILE if -f $LOCK_FILE;
}

1;