BerkeleyDB/shared.pm untested

filter: Statementstmt 0.0% 0 / 348 Branchbran 0.0% 0 / 144 Conditioncond 0.0% 0 / 77 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 676 CC 63 SCAR 38.9
CC
63
Cov
0%
_filter_fetch_value
182.0
_filter_store_value
90.0
threads::shared::STORE
90.0
CRAP 49.2
1 package forks::BerkeleyDB::shared;
2  
3 $VERSION = 0.060;
4  
5 package
6 CORE::GLOBAL; #hide from PAUSE
7 use subs qw(fork);
8 {
9 no warnings 'redefine';
10 *fork = \&forks::BerkeleyDB::shared::_fork;
11 }
12  
13 package forks::BerkeleyDB::shared;
14  
15 use strict;
16 use warnings;
17 use vars qw(@ISA);
18 @ISA = 'forks::shared';
19  
20 use forks::BerkeleyDB::Config;
21 use BerkeleyDB 0.27;
22 use Storable qw(freeze thaw);
23 use Tie::Restore 0.11;
24 use Scalar::Util qw(blessed reftype weaken);
25  
26 use constant DEBUG => forks::BerkeleyDB::Config::DEBUG();
27 use constant ENV_PATH => forks::BerkeleyDB::Config::ENV_PATH();
28 #use Data::Dumper;
29  
30 our %object_refs; #refs of all shared objects (for CLONE use, and weak refs: allow shared vars to hold other shared vars as values; END{...} cleanup in all threads)
31 our @shared_cache; #tied BDB array that stores shared variable objects for other threads to use to reconstitute if they were created outside their scope
32 our @shared_cache_attr_bless; #tied BDB array that stores shared variable object attribute bless
33  
34 use constant TERMINATOR => "\0";
35 use constant ELEM_NOT_EXISTS => "!"; #indicates element does not exist (used for arrays)
36  
37 ########################################################################
38 sub _filter_fetch_value {
39 #warn "output: '$_', defined=",defined $_,",length=",length $_ if DEBUG;
40 if (!defined $_ || length $_ == 0) { $_ = undef; }
41 elsif (length $_ == 1 && $_ eq ELEM_NOT_EXISTS) {
42 $_ = forks::BerkeleyDB::ElemNotExists->instance();
43 }
44 else {
45 if (substr($_, -1) eq TERMINATOR) { #regular data value
46 chop($_);
47 }
48 else { #is a shared var, retie to same shared ordinal
49 #warn Dumper($_, $object_refs{$_}, defined $shared_cache[$_] ? thaw($shared_cache[$_]) : undef) if DEBUG;
50 my $obj;
51 if (!defined $object_refs{$_} || !defined $object_refs{$_}->{bdb_is_connected} || !$object_refs{$_}->{bdb_is_connected}) { #shared var created outside scope of this thread or needs to be reloaded: load object from shared var cache & reconnect to db
52 $obj = defined $object_refs{$_} && defined $object_refs{$_}->{bdb_module}
53 ? $object_refs{$_}
54 : eval { @{thaw($forks::BerkeleyDB::shared::shared_cache[$_])}[0] };
55 #warn "*********".threads->tid().": _filter_fetch_value -> obj \#$_ recreated: $obj\n"; #if DEBUG;
56 _croak( "Unable to load object state for shared variable \#$_" ) unless defined $obj;
57 my $sub = '_tie'.$obj->{type};
58 {
59 no strict 'refs';
60 &{$sub}($obj);
61 }
62 } else {
63 $obj = $object_refs{$_};
64 }
65 my $class = $shared_cache_attr_bless[$_];
66 if ($obj->{'type'} eq 'scalar')
67 { my $s; tie $s, 'Tie::Restore', $obj; $_ = $class ? CORE::bless(\$s, $class) : \$s; }
68 elsif ($obj->{'type'} eq 'array')
69 { my @a; tie @a, 'Tie::Restore', $obj; $_ = $class ? CORE::bless(\@a, $class) : \@a; }
70 elsif ($obj->{'type'} eq 'hash')
71 { my %h; tie %h, 'Tie::Restore', $obj; $_ = $class ? CORE::bless(\%h, $class) : \%h; }
72 # elsif ($obj->{'type'} eq 'handle')
73 # { my *h; tie *h, 'Tie::Restore', $obj; $_ = $class ? CORE::bless(\*h, $class) : \*h; }
74 else {
75 _croak( "Unable to restore shared variable \#$_: ".ref($obj) );
76 }
77 }
78 }
79 }
80  
81 sub _filter_store_value {
82 #warn "input: '$_', defined=",defined $_,",length=",length $_ if DEBUG;
83 if (defined $_) {
84 if (ref($_)) { #does this support both share(@a) and share(\@_)?
85 if (UNIVERSAL::isa($_, 'forks::BerkeleyDB::ElemNotExists')) { $_ = ELEM_NOT_EXISTS; }
86 else {
87 my $tied = reftype($_) eq 'SCALAR' ? tied ${$_}
88 : reftype($_) eq 'ARRAY' ? tied @{$_}
89 : reftype($_) eq 'HASH' ? tied %{$_}
90 : reftype($_) eq 'GLOB' ? tied *{$_} : undef;
91 #warn "input: ".Dumper(ref $_, reftype $_, blessed $_, $tied, $_) if DEBUG;
92 if (UNIVERSAL::isa($tied, 'threads::shared')) { #store shared ref ordinal
93 $_ = $tied->{'ordinal'};
94 }
95 else { #future: transparently bless any type of object across all threads?
96 _croak( "Invalid value for shared scalar: ".(reftype($_) || $_) );
97 }
98 }
99 }
100 else {
101 $_ .= TERMINATOR();
102 }
103 }
104 #warn "input final: defined=",defined $_,",length=",length $_ if DEBUG;
105 }
106  
107 ########################################################################
108 BEGIN {
109 require forks::shared;
110 die "forks::shared version 0.18 required--this is only version $forks::shared::VERSION"
111 unless defined $forks::shared::VERSION && $forks::shared::VERSION >= 0.18;
112 use forks::BerkeleyDB::shared::array;
113
114 *_croak = *_croak = \&threads::shared::_croak;
115
116 _croak( "Must first 'use forks::BerkeleyDB'\n" ) unless $INC{'forks/BerkeleyDB.pm'};
117  
118 #need to store separate, serialized, db-disconnected copy in a separate database, so other threads can re-create arrayrefs and hashrefs
119 sub _tie_shared_cache () {
120 tie @shared_cache, 'forks::BerkeleyDB::shared::array', (
121 -Filename => ENV_PATH.'/shared.bdb',
122 -Flags => DB_CREATE,
123 -Mode => forks::BerkeleyDB::BDB_ENV_CHMOD_OCTVAL(),
124 -Env => forks::BerkeleyDB::bdb_env,
125 );
126  
127 tie @shared_cache_attr_bless, 'forks::BerkeleyDB::shared::array', (
128 -Filename => ENV_PATH.'/shared_attr_bless.bdb',
129 -Flags => DB_CREATE,
130 -Mode => forks::BerkeleyDB::BDB_ENV_CHMOD_OCTVAL(),
131 -Env => forks::BerkeleyDB::bdb_env,
132 );
133 }
134
135 sub _untie_shared_cache () {
136 untie @shared_cache;
137 untie @shared_cache_attr_bless;
138 }
139
140 sub _fork {
141 ### safely sync/close databases ###
142 {
143 local $@;
144 foreach my $key (keys %object_refs) {
145 if ($object_refs{$key}->{bdb_is_connected}) {
146 # eval { $object_refs{$key}->{bdb}->db_sync(); }; #disabled: db_close expected to sync
147 eval { $object_refs{$key}->{bdb}->db_close(); };
148 $object_refs{$key}->{bdb} = undef;
149 $object_refs{$key}->{bdb_is_connected} = 0;
150 }
151 $object_refs{$key}->{bdb_is_connected} = 0; #hint that this object must be recreated from cache
152 }
153 }
154 _untie_shared_cache();
155
156 ### do the fork ###
157 my $pid = forks::BerkeleyDB::_fork();
158  
159 if (!defined $pid || $pid) { #in parent
160 ### immediately retie to critical databases ###
161 _tie_shared_cache();
162 # foreach my $key (keys %object_refs) {
163 # my $sub = 'forks::BerkeleyDB::shared::_tie'.$object_refs{$key}->{type};
164 # {
165 # no strict 'refs';
166 # $object_refs{$key} = &{$sub}($object_refs{$key});
167 # }
168 # }
169 }
170
171 return $pid;
172 };
173
174 *import = *import = \&forks::shared::import;
175
176 *_ORIG_CLONE = *_ORIG_CLONE = \&forks::BerkeleyDB::CLONE;
177 {
178 no warnings 'redefine';
179 *forks::BerkeleyDB::CLONE = \&_CLONE;
180 }
181  
182 sub _CLONE { #reopen environment and immediately retie to critical databases
183 _ORIG_CLONE(@_);
184 _tie_shared_cache();
185 # local $@;
186 # foreach my $key (keys %object_refs) {
187 # if ($object_refs{$key}->{bdb_is_connected}) {
188 ## eval { $object_refs{$key}->{bdb}->db_sync(); }; #disabled: db_close expected to sync
189 # eval { $object_refs{$key}->{bdb}->db_close(); };
190 # $object_refs{$key}->{bdb_is_connected} = 0;
191 # }
192 #warn "In clone (tid #".threads->tid."): $key -> ".ref($object_refs{$key}) if DEBUG;
193 # my $sub = '_tie'.$object_refs{$key}->{type};
194 # {
195 # no strict 'refs';
196 # &{$sub}($object_refs{$key});
197 # }
198 # }
199 }
200  
201 ### create the base environment ###
202 _tie_shared_cache();
203 }
204  
205 END {
206 local $@;
207 foreach my $key (keys %object_refs) {
208 if ($object_refs{$key}->{bdb_is_connected}) {
209 # eval { $object_refs{$key}->{bdb}->db_sync(); }; #disabled: db_close expected to sync
210 eval { $object_refs{$key}->{bdb}->db_close(); };
211 $object_refs{$key}->{bdb_is_connected} = 0;
212 }
213 }
214 eval { _untie_shared_cache(); };
215 }
216  
217 ########################################################################
218 sub _tiescalar ($) {
219 my $obj = shift;
220 return $obj unless ref($obj);
221 $shared_cache[$obj->{ordinal}] = freeze([$obj]) unless defined $obj->{bdb_module};
222
223 ### create the database and store as additional property in the object ###
224 $obj->{bdb_module} = __PACKAGE__.'::'.$obj->{type};
225 (my $module_inc = $obj->{bdb_module}) =~ s/::/\//go;
226 eval "use $obj->{bdb_module}" unless exists $INC{$module_inc};
227 my $bdb_path = ENV_PATH.'/'.$obj->{ordinal}.".bdb";
228 $obj->{bdb} = $obj->{bdb_module}->new(
229 -Filename => $bdb_path,
230 -Flags => DB_CREATE,
231 -Mode => 0666,
232 -Env => forks::BerkeleyDB::bdb_env,
233 ) or _croak( "Can't create bdb $bdb_path: $!; $BerkeleyDB::Error" );
234 $obj->{bdb}->filter_fetch_value(\&_filter_fetch_value);
235 $obj->{bdb}->filter_store_value(\&_filter_store_value);
236 $obj->{bdb_is_connected} = 1;
237  
238 ### store ref in package variable ###
239 $object_refs{$obj->{ordinal}} = $obj;
240 weaken($object_refs{$obj->{ordinal}});
241
242 return $obj;
243 }
244  
245 sub _tiearray ($) {
246 my $obj = shift;
247 return $obj unless ref($obj);
248 $shared_cache[$obj->{ordinal}] = freeze([$obj]) unless defined $obj->{bdb_module};
249  
250 ### create the database and store as additional property in the object ###
251 $obj->{bdb_module} = __PACKAGE__.'::'.$obj->{type};
252 (my $module_inc = $obj->{bdb_module}) =~ s/::/\//go;
253 eval "use $obj->{bdb_module}" unless exists $INC{$module_inc};
254 my $bdb_path = ENV_PATH.'/'.$obj->{ordinal}.".bdb";
255 $obj->{bdb} = $obj->{bdb_module}->new(
256 -Filename => $bdb_path,
257 -Flags => DB_CREATE,
258 -Property => DB_RENUMBER,
259 -Mode => 0666,
260 -Env => forks::BerkeleyDB::bdb_env,
261 ) or _croak( "Can't create bdb $bdb_path: $!; $BerkeleyDB::Error" );
262 $obj->{bdb}->filter_fetch_value(\&_filter_fetch_value);
263 $obj->{bdb}->filter_store_value(\&_filter_store_value);
264 $obj->{bdb_is_connected} = 1;
265
266 ### store ref in package variable ###
267 $object_refs{$obj->{ordinal}} = $obj;
268 weaken($object_refs{$obj->{ordinal}});
269  
270 return $obj;
271 }
272  
273 sub _tiehash ($) {
274 my $obj = shift;
275 return $obj unless ref($obj);
276 $shared_cache[$obj->{ordinal}] = freeze([$obj]) unless defined $obj->{bdb_module};
277  
278 ### create the database and store as additional property in the object ###
279 $obj->{bdb_module} = __PACKAGE__.'::'.$obj->{type};
280 (my $module_inc = $obj->{bdb_module}) =~ s/::/\//go;
281 eval "use $obj->{bdb_module}" unless exists $INC{$module_inc};
282 my $bdb_path = ENV_PATH.'/'.$obj->{ordinal}.".bdb";
283 $obj->{bdb} = $obj->{bdb_module}->new(
284 -Filename => $bdb_path,
285 -Flags => DB_CREATE,
286 -Mode => 0666,
287 -Env => forks::BerkeleyDB::bdb_env,
288 ) or _croak( "Can't create bdb $bdb_path: $!; $BerkeleyDB::Error" );
289 $obj->{bdb}->filter_fetch_value(\&_filter_fetch_value);
290 $obj->{bdb}->filter_store_value(\&_filter_store_value);
291 $obj->{bdb_is_connected} = 1;
292
293 ### store ref in package variable ###
294 $object_refs{$obj->{ordinal}} = $obj;
295 weaken($object_refs{$obj->{ordinal}});
296  
297 return $obj;
298 }
299  
300 sub _tiehandle ($) {
301 my $obj = shift;
302 return $obj unless ref($obj);
303 $shared_cache[$obj->{ordinal}] = freeze([$obj]) unless defined $obj->{bdb_module};
304  
305 $obj->{bdb_module} = __PACKAGE__.'::'.$obj->{type};
306 $obj->{bdb} = undef;
307 $obj->{bdb_is_connected} = 1;
308
309 ### store ref in package variable ###
310 $object_refs{$obj->{ordinal}} = $obj;
311 weaken($object_refs{$obj->{ordinal}});
312  
313 return $obj;
314 }
315  
316 ########################################################################
317 ### overload some subs and methods in forks and forks::shared ###
318 {
319 no warnings 'redefine'; #allow overloading without warnings
320  
321 sub threads::shared::_bless {
322 my $it = shift;
323 my $ref = reftype $it;
324 my $class = shift;
325 my $object;
326
327 if ($ref eq 'SCALAR') {
328 $object = tied ${$it};
329 } elsif ($ref eq 'ARRAY') {
330 $object = tied @{$it};
331 } elsif ($ref eq 'HASH') {
332 $object = tied %{$it};
333 } elsif ($ref eq 'GLOB') {
334 $object = tied *{$it};
335 }
336  
337 if (defined $object && blessed $object && $object->isa('threads::shared')) {
338 my $ordinal = $object->{'ordinal'};
339 $shared_cache_attr_bless[$object->{ordinal}] = $class;
340 }
341 }
342
343 my $old_tie = \&threads::shared::_tie;
344 *threads::shared::_tie = sub {
345 my $class = shift;
346 my $type = shift;
347 my $self = shift || {};
348  
349 # Call parent tie
350 my $obj;
351 {
352 local $threads::shared::CLONE_TIED = 0; #just register with shared process; don't store
353 $obj = $old_tie->( $class,$type,$self,@_ );
354 }
355
356 # Perform tie to BDB resources
357 if ($type eq 'scalar') {
358 forks::BerkeleyDB::shared::_tiescalar($obj);
359 } elsif ($type eq 'array') {
360 forks::BerkeleyDB::shared::_tiearray($obj);
361 } elsif ($type eq 'hash') {
362 forks::BerkeleyDB::shared::_tiehash($obj);
363 } elsif ($type eq 'handle') {
364 forks::BerkeleyDB::shared::_tiehandle($obj);
365 } else {
366 _croak("Unknown tie type $type");
367 }
368
369 # Clone any existing data
370 my $data = shift;
371 if ($threads::shared::CLONE_TIED) {
372 if ($type eq 'scalar' && ref($data) eq 'SCALAR' && defined ${$data}) {
373 $obj->STORE(ref(${$data}) ? threads::shared::shared_clone(${$data}) : ${$data});
374 #TODO else handle other clone cases here
375 } elsif ($type eq 'array' && ref($data) eq 'ARRAY' && @{$data}) {
376 for (my $i = 0; $i < @{$data}; $i++) {
377 $obj->STORE($i, ref($data->[$i]) ? threads::shared::shared_clone($data->[$i]) : $data->[$i]);
378 }
379 } elsif ($type eq 'hash' && ref($data) eq 'HASH' && %{$data}) {
380 foreach (keys %{$data}) {
381 $obj->STORE($_, ref($data->{$_}) ? threads::shared::shared_clone($data->{$_}) : $data->{$_});
382 }
383 }
384 }
385
386 return $obj;
387 };
388  
389 sub threads::shared::AUTOLOAD {
390 my $self = shift;
391 my $obj;
392 if (!defined $self->{bdb_is_connected} || !$self->{bdb_is_connected}) { #shared var needs to be reloaded: load shared var cache & connect to db
393 #warn "*********".threads->tid().": threads::shared::AUTOLOAD -> obj \#$self->{ordinal}\n"; #if DEBUG;
394 $obj = defined $object_refs{$self->{ordinal}} && defined $object_refs{$self->{ordinal}}->{bdb_module}
395 ? $object_refs{$self->{ordinal}}
396 : eval { @{thaw($forks::BerkeleyDB::shared::shared_cache[$self->{ordinal}])}[0] };
397 _croak( "Unable to load object state for shared variable \#$self->{ordinal}" ) unless defined $obj;
398 my $sub = 'forks::BerkeleyDB::shared::_tie'.$obj->{type};
399 {
400 no strict 'refs';
401 $self = &{$sub}($obj);
402 }
403 } else {
404 $obj = $object_refs{$self->{ordinal}};
405 }
406 (my $sub = $threads::shared::AUTOLOAD) =~ s/^.*::/$self->{'bdb_module'}::/;
407 #warn "$sub, $self->{ordinal}" if DEBUG;
408 #warn Dumper(\@_) if DEBUG;
409 my @result;
410 @result = $self->{'bdb'}->$sub(@_) if defined $self->{'bdb'};
411 wantarray ? @result : $result[0];
412 }
413
414 # Define generic perltie proxy methods for most scalar, array, hash, and handle events
415  
416 no strict 'refs';
417 foreach my $method (qw/BINMODE CLEAR CLOSE EOF EXTEND FETCHSIZE FILENO GETC
418 OPEN POP PRINT PRINTF READ READLINE SCALAR SEEK SHIFT STORESIZE TELL UNSHIFT WRITE
419 PUSH/) {
420 *{"threads::shared::$method"} = sub {
421 $threads::shared::AUTOLOAD = 'threads::shared::'.$method;
422 threads::shared::AUTOLOAD(@_);
423 };
424 }
425  
426 foreach my $method (qw/DELETE EXISTS FIRSTKEY NEXTKEY/) {
427 *{"threads::shared::$method"} = sub {
428 my $self = shift;
429 my $sub = $self->{'module'}.'::'.$method;
430 if ($self->{'type'} eq 'hash' && ref($_[0]) eq 'CODE') {
431 $_[0] = "$_[0]";
432 }
433 $threads::shared::AUTOLOAD = 'threads::shared::'.$method;
434 threads::shared::AUTOLOAD($self, @_);
435 };
436 }
437  
438 sub threads::shared::STORE {
439 my $self = shift;
440  
441 # If this is a scalar and to-be stored value is a reference
442 # Obtain the object
443 # Die if the reference is not a threads::shared tied object
444 my $val = $_[$self->{'type'} eq 'scalar' ? 0 : 1];
445 if (my $ref = reftype($val)) {
446 my $object;
447 if ($ref eq 'SCALAR') {
448 $object = tied ${$val};
449 } elsif ($ref eq 'ARRAY') {
450 $object = tied @{$val};
451 } elsif ($ref eq 'HASH') {
452 $object = tied %{$val};
453 } elsif ($ref eq 'GLOB') {
454 $object = tied *{$val};
455 }
456 Carp::croak "Invalid value for shared scalar"
457 unless defined $object && $object->isa('threads::shared');
458 }
459  
460 # If we're a hash and the key is a code reference
461 # Force key stringification, to insure remote server uses same key value as thread
462 if ($self->{'type'} eq 'hash' && ref($_[0]) eq 'CODE') {
463 $_[0] = "$_[0]";
464 }
465 $threads::shared::AUTOLOAD = 'threads::shared::STORE';
466 threads::shared::AUTOLOAD($self, @_);
467 }
468
469 sub threads::shared::FETCH {
470  
471 # If we're a hash and the key is a code reference
472 # Force key stringification, to insure remote server uses same key value as thread
473  
474 my $self = shift;
475 if ($self->{'type'} eq 'hash' && ref($_[0]) eq 'CODE') {
476 $_[0] = "$_[0]";
477 }
478 $threads::shared::AUTOLOAD = 'threads::shared::FETCH';
479 threads::shared::AUTOLOAD($self, @_);
480 }
481  
482 sub threads::shared::SPLICE {
483 # Die now if running in thread emulation mode
484 Carp::croak('Splice not implemented for shared arrays') if eval {forks::THREADS_NATIVE_EMULATION()};
485 $threads::shared::AUTOLOAD = 'threads::shared::SPLICE';
486 threads::shared::AUTOLOAD(@_);
487 }
488  
489 sub threads::shared::UNTIE {
490 my $self = shift;
491 return if $self->{'CLONE'} != $threads::shared::CLONE;
492 if (defined $self->{'bdb_module'}) {
493 my $sub = "$self->{'bdb_module'}::UNTIE";
494 my @result;
495 {
496 no strict 'refs';
497 @result = &{$sub}(@_);
498 }
499 }
500 delete $object_refs{$self->{ordinal}};
501 threads::shared::_command( '_untie',$self->{'ordinal'} );
502 }
503  
504 sub threads::shared::DESTROY {
505 my $self = shift;
506 return if $self->{'CLONE'} != $threads::shared::CLONE;
507 if (defined $self->{'bdb_module'}) {
508 my $sub = "$self->{'bdb_module'}::DESTROY";
509 my @result;
510 {
511 no strict 'refs';
512 @result = &{$sub}(@_);
513 }
514 $self->{bdb_is_connected} = 0;
515 }
516 delete $object_refs{$self->{ordinal}};
517 threads::shared::_command( '_tied',$self->{'ordinal'},$self->{'module'}.'::DESTROY' );
518 }
519 }
520  
521 1;
522  
523 __END__