2
# Copyright (C) 2006 MySQL AB
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; version 2 of the License.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22
use base qw(Exporter);
23
our @EXPORT= qw(mtr_get_unique_id mtr_release_unique_id);
28
# print "### unique($$) - ", join(" ", @_), "\n";
35
$dir= "/tmp/mysql-unique-ids";
39
# Try to use machine-wide directory location for unique IDs,
40
# $ALLUSERSPROFILE . IF it is not available, fallback to $TEMP
41
# which is typically a per-user temporary directory
42
if (exists $ENV{'ALLUSERSPROFILE'} && -w $ENV{'ALLUSERSPROFILE'})
44
$dir= $ENV{'ALLUSERSPROFILE'}."/mysql-unique-ids";
48
$dir= $ENV{'TEMP'}."/mysql-unique-ids";
52
my $mtr_unique_fh = undef;
56
mtr_release_unique_id();
60
# Get a unique, numerical ID in a specified range.
62
# If no unique ID within the specified parameters can be
63
# obtained, return undef.
65
sub mtr_get_unique_id($$) {
68
msg("get $min-$max, $$");
70
die "Can only get one unique id per process!" if defined $mtr_unique_fh;
73
# Make sure our ID directory exists
76
# If there is a file with the reserved
77
# directory name, just delete the file.
88
die "can't make directory $dir";
94
for(my $id = $min; $id <= $max; $id++)
96
open( $fh, ">$dir/$id");
97
chmod 0666, "$dir/$id";
98
# Try to lock the file exclusively. If lock succeeds, we're done.
99
if (flock($fh, LOCK_EX|LOCK_NB))
101
# Store file handle - we would need it to release the ID (==unlock the file)
102
$mtr_unique_fh = $fh;
115
# Release a unique ID.
117
sub mtr_release_unique_id()
120
if (defined $mtr_unique_fh)
122
close $mtr_unique_fh;
123
$mtr_unique_fh = undef;