RecordStore/Versioned.pm untested

filter: Statementstmt 0.0% 0 / 802 Branchbran 0.0% 0 / 192 Conditioncond 0.0% 0 / 76 MC/DCmcdc 0.0% 0 / 44 Subroutinesub 0.0% 0 / 86 Podpod 0.0% 0 / 62 totaltotal 0.0% 0 / 1262 CC 97 SCAR 34.9
CC
97
Cov
0%
stow
156.0
open_silo
90.0
_ensure_entry_count
72.0
CRAP 32.8
1 package Data::RecordStore::Versioned;
2  
3 # with immutable objects and versioned ones
4  
5 use strict;
6 use warnings;
7  
8 use Fcntl qw( :flock SEEK_SET );
9 use File::Path qw(make_path);
10 use Data::Dumper;
11  
12 use vars qw($VERSION);
13  
14 $VERSION = '0.01';
15  
16 sub open_store {
17 my( $cls, @options ) = @_;
18  
19 # directory structure
20 # root/CLASS <-- Data::RecordStore::Versioned
21 # root/VERSION <-- version file
22 # root/MASTER_LOCK <-- lock file
23 # master lock is used when creating new silos and setting up
24 # the initial store
25 # root/USER_LOCKS/
26 # root/RECORD_INDEX_SILO/ <-- record index silo directory
27 # root/silos/ <-- directory for silo directories
28  
29  
30 #
31 # Interpret the arguments ---------------------------------------
32 #
33 if( 1 == @options ) {
34 unshift @options, 'BASE_PATH';
35 }
36 my( %options ) = @options;
37 my $directory = $options{BASE_PATH};
38  
39 #
40 # Make sure the path exists ---------------------------------------
41 #
42 make_path( $directory, { error => \my $err } );
43 if( @$err ) {
44 die "Error opening store : " . join ',',map { values %$_ } @$err;
45 }
46
47 #
48 # Engage the master lock ---------------------------------------
49 #
50 open( my $master_fh, ">", "$directory/MASTER_LOCK" ) or die "Unable to create $directory/MASTER_LOCK : $!";
51 flock( $master_fh, LOCK_EX );
52 print $master_fh "MASTER LOCK";
53  
54 #
55 # Ensure the directories ---------------------------------------
56 #
57 for my $subdir ( qw( USER_LOCKS silos TRANS/instances ) ) {
58 make_path( "$directory/$subdir", { error => \my $err } );
59 if( @$err ) {
60 die "Error opening store : " . join ',',map { values %$_ } @$err;
61 }
62 }
63  
64 #
65 # Find the version of the database. ---------------------------------------
66 #
67 my $version;
68 my $version_file = "$directory/VERSION";
69 my $FH;
70 if( -e $version_file ) {
71 open $FH, "<", $version_file;
72 $version = <$FH>;
73 chomp $version;
74 if( $version < 5 ) {
75 die "A database was found in $directory with version $version. Please run the record_store_convert program to upgrade to version $VERSION.";
76 }
77 }
78 else {
79 #
80 # a version file needs to be created. if the database
81 # had been created and no version exists, assume it is
82 # version 1.
83 #
84 if( -e "$directory/STORE_INDEX" ) {
85 die "A database was found in $directory with no version information and is assumed to be an old format. Please run the record_store_convert program.";
86 }
87 $version = $VERSION;
88 open $FH, ">", $version_file;
89 print $FH "$version\n";
90 }
91 close $FH;
92  
93 my $store = bless {
94 DIRECTORY => $directory,
95 MASTER_FH => $master_fh,
96 MASTER_LOCK_COUNT => 1,
97 RECORD_INDEX => Data::RecordStore::Silo->open_silo( "ILL", "$directory/RECORD_INDEX_SILO" ),
98 SILOS => Data::RecordStore::SiloPack->new,
99 VERSION => $version,
100 TRANSACTION => [],
101 LOCKS => [],
102 }, $cls;
103  
104 $store->_unlock_master;
105 return $store;
106 } #open_store
107  
108 sub _open_silo {
109 my $self = shift;
110 $self->_lock_master;
111 my $silo = $self->{SILOS}->open_silo( @_ );
112 $self->_unlock_master;
113 return $silo;
114 }
115  
116 sub _close_silo {
117 my( $self, $silo ) = @_;
118 $self->{SILOS}->clear_silo( $silo->{DIRECTORY} );
119 }
120  
121 sub _lock_master {
122 my $self = shift;
123 flock( $self->{MASTER_FH}, LOCK_EX );
124 $self->{MASTER_LOCK_COUNT}++;
125 }
126  
127 sub _unlock_master {
128 my $self = shift;
129 if( 1 > --$self->{MASTER_LOCK_COUNT} ) {
130 flock( $self->{MASTER_FH}, LOCK_UN );
131 }
132 }
133  
134 sub find_broken_ids {
135 my $self = shift;
136 my $index = $self->{RECORD_INDEX};
137 my $size = $index->entry_count;
138 my $silos = [];
139 my $problems = [];
140 for( my $i=1; $i<=$size; $i++ ) {
141 my($silo_id,$in_silo_idx,$update_time) = @{$index->get_record( $i )};
142 next if $silo_id == 0;
143 my $silo = $silos->[$silo_id];
144 unless( $silo ) {
145 $silo = $self->_get_silo( $silo_id );
146 $silos->[$silo_id] = $silo;
147 }
148 my $ec = $silo->entry_count;
149 if( $in_silo_idx > $ec ) {
150 push @$problems, $i;
151 }
152 }
153 return $problems;
154 } #find_broken_ids
155  
156 sub detect_version {
157 my( $cls, $dir ) = @_;
158 my $ver_file = "$dir/VERSION";
159 my $source_version;
160 if ( -e $ver_file ) {
161 open( my $FH, "<", $ver_file );
162 $source_version = <$FH>;
163 chomp $source_version;
164 close $FH;
165 }
166 return $source_version;
167 } #detect_version
168  
169 #
170 # If there is no current transaction, this starts one.
171 #
172 sub use_transaction {
173 my $self = shift;
174 my $trans = $self->{TRANSACTION}[0];
175 return $trans if $trans;
176 return $self->start_transaction;
177 }
178  
179 sub commit_transaction {
180 my $self = shift;
181 my $trans = $self->{TRANSACTION}[0]; # it is removed in the commit call below
182 if( $trans ) {
183 $trans->commit;
184 } else {
185 warn "No transaction in progress";
186 }
187 } #commit_transaction
188  
189 sub rollback_transaction {
190 my $self = shift;
191 my $trans = $self->{TRANSACTION}[0]; # it is removed in the rollback call below
192 if( $trans ) {
193 $trans->rollback;
194 } else {
195 warn "No transaction in progress";
196 }
197 } #rollback_transaction
198  
199 sub start_transaction {
200 my $self = shift;
201 $self->_lock_master;
202 my $trans = Data::RecordStore::Transaction->_create( $self );
203 unshift @{$self->{TRANSACTION}}, $trans;
204 $self->_unlock_master;
205 return $trans;
206 } #start_transaction
207  
208 sub list_transactions {
209 my $self = shift;
210 my $trans_directory = $self->_open_silo( "ILLI", "$self->{DIRECTORY}/TRANS/META" );
211 $trans_directory->lock;
212 my @trans;
213 my $items = $trans_directory->entry_count;
214 for( my $trans_id=$items; $trans_id > 0; $trans_id-- ) {
215 my $data = $trans_directory->get_record( $trans_id );
216 my $trans = Data::RecordStore::Transaction->_create( $self, $data );
217 if( $trans->get_state == TRA_DONE ) {
218 $trans_directory->pop; #its done, remove it
219 } else {
220 push @trans, $trans;
221 }
222 }
223 $trans_directory->unlock;
224 return @trans;
225 }
226  
227 sub stow {
228 my( $self, $data, $id ) = @_;
229 print STDERR "STOW ($id) <$$>\n";
230 my $trans = $self->{TRANSACTION}[0];
231 if( $trans ) {
232 return $trans->stow( $data, $id );
233 }
234  
235 unless( defined $id ) {
236 $id = $self->next_id(1);
237 }
238  
239 if( $id < 1 ) {
240 die "ID must be a positive integer";
241 }
242  
243 $self->_ensure_entry_count( $id );
244  
245  
246 my $save_size = do { use bytes; length( $data ); };
247  
248 # tack on the size of the id (a long or 4 bytes) and the \0 (1 byte) to the byte count
249 $save_size += 5;
250  
251 my( $current_silo_id, $current_id_in_silo, $update_time ) = @{ $self->{RECORD_INDEX}->get_record( $id ) };
252  
253 #
254 # See if this record is already in a silo. If it is, see if it
255 # should stay there or needs to move to a different sized silo.
256 #
257 my $old_silo = $current_silo_id ? $self->_get_silo( $current_silo_id ) : undef;
258  
259 my( $needs_swap, $needs_pop ) = ( 0, 0 );
260 if( $old_silo ) {
261  
262 #
263 # Nomove case.
264 # Keep it in the same silo if the record is not too big for it
265 # and the record takes at least a third of the space
266 #
267 if ( $save_size <= $old_silo->{RECORD_SIZE} &&
268 ( $current_silo_id == 12 || $old_silo->{RECORD_SIZE} < (3 * $save_size) ) )
269 {
270 $old_silo->put_record( $current_id_in_silo, [$id,$data] );
271 return $id;
272 }
273  
274 #
275 # the old silo was not the right size, so move it to a new silo
276 #
277 if( $old_silo->entry_count > $current_id_in_silo ) {
278 #
279 # the record leaves a hole in the old silo, so move the last
280 # entry in the silo to its location to keep things autovacuumed.
281 #
282 $needs_swap = 1;
283 }
284 else {
285 #
286 # this is the last one in the old silo just pop it off, no swapping
287 # needed.
288 #
289 $needs_pop = 1;
290 }
291 } # if this had a former place
292  
293 #
294 # find the new silo for this record
295 #
296 my $silo_id = 12; # the min size
297 if( $save_size > 4096 ) {
298 $silo_id = log( $save_size ) / log( 2 );
299 if( int( $silo_id ) < $silo_id ) {
300 $silo_id = 1 + int( $silo_id );
301 }
302 }
303  
304 #
305 # Save this to the new silo and update the index
306 #
307 my $silo = $self->_get_silo( $silo_id );
308 my $id_in_silo = $silo->next_id(1);
309 print STDERR " STOW INDEX ($id_in_silo/$silo_id)\n";
310 $self->{RECORD_INDEX}->put_record( $id, [ $silo_id, $id_in_silo, _time() ] );
311 $silo->put_record( $id_in_silo, [ $id, $data ] );
312  
313 #
314 # Clean up the old silo if necessary.
315 #
316 if( $needs_swap ) {
317 $self->_swapout( $old_silo, $current_silo_id, $current_id_in_silo );
318 }
319 elsif( $needs_pop ) {
320 $old_silo->pop;
321 }
322  
323 return $id;
324 } #stow
325  
326 sub last_updated {
327 my( $self, $id ) = @_;
328 (undef,undef,my $update_time) = @{$self->{RECORD_INDEX}->get_record( $id )};
329 return $update_time;
330 }
331  
332 sub fetch {
333 my( $self, $id ) = @_;
334 print STDERR "FETCH ($id) <$$>\n";
335 if( $id > $self->{RECORD_INDEX}->entry_count ) {
336 print STDERR " FETCH ($id) --> past index {empty} <$$>\n";
337 return undef;
338 }
339  
340 my( @trans ) = @{$self->{TRANSACTION}};
341 my( $silo_id, $id_in_silo, $found_trans );
342  
343 # if an existing transaction, return any updates to it
344 for my $trans (@trans) {
345 my( $trans_id );
346 next if $id > $trans->{ITEM_SILO}->entry_count; # this ID was not touched by this transaction
347 ( $trans_id ) = @{ $trans->{ITEM_SILO}->get_record( $id ) };
348 next unless $trans_id;
349 my $trans_record = $trans->{ACTION_SILO}->get_record( $trans_id );
350 my( $action, undef, undef, undef, $to_silo_id, $to_record_id ) = @$trans_record;
351 if( $action eq 'S' ) {
352 $found_trans = 1;
353 ( $silo_id, $id_in_silo ) = ( $to_silo_id, $to_record_id );
354 }
355 else {
356 return undef;
357 }
358 last;
359 }
360  
361 unless( $found_trans ) {
362 print STDERR " FETCH FROM INDEX <$$>\n";
363 ( $silo_id, $id_in_silo ) = @{ $self->{RECORD_INDEX}->get_record( $id ) };
364 }
365 unless( $silo_id ) {
366 print STDERR " FETCH ($id) --> undef <$$>\n";
367 return undef;
368 }
369 print STDERR "FETCH ($id) --> ($id_in_silo/$silo_id) <$$>\n";
370 my $silo = $self->_get_silo( $silo_id );
371  
372 # skip the included id, just get the data
373 ( undef, my $data ) = @{ $silo->get_record( $id_in_silo ) };
374  
375 return $data;
376 } #fetch
377  
378  
379 # returns the size in bytes of the record store
380 sub size {
381 my $self = shift;
382 my $size = 0;
383 my $silos = $self->_all_silos;
384 for my $silo (@$silos) {
385 $size += $silo->size;
386 }
387 return $size;
388 } #size
389  
390 # entry count in the index
391 sub entry_count {
392 my $self = shift;
393 return $self->{RECORD_INDEX}->entry_count;
394 } #entry_count
395  
396 # number of records marked reachable by the index
397 sub active_entry_count {
398 my $self = shift;
399 my $count = 0;
400 for( my $id=1; $id<= $self->{RECORD_INDEX}->entry_count; $id++ ) {
401 my( $silo_id, $id_in_silo ) = @{ $self->{RECORD_INDEX}->get_record( $id ) };
402 $count++ if $silo_id;
403 }
404 return $count;
405 } #entry_count
406  
407 # number of entries across all silos
408 sub record_count {
409 my $self = shift;
410 my $count = 0;
411 my $silos = $self->_all_silos;
412 for my $silo (@$silos) {
413 $count += $silo->entry_count;
414 }
415 return $count;
416 } #record_count
417  
418 sub delete_record {
419 my( $self, $del_id, $no_unlock ) = @_;
420  
421 my $trans = $self->{TRANSACTION}[0];
422 if( $trans ) {
423 return $trans->delete_record( $del_id );
424 }
425 if( $del_id > $self->{RECORD_INDEX}->entry_count ) {
426 return undef;
427 }
428  
429 my( $from_silo_id, $current_id_in_silo ) = @{ $self->{RECORD_INDEX}->get_record( $del_id ) };
430  
431 unless( $from_silo_id ) {
432 return;
433 }
434  
435 my $from_silo = $self->_get_silo( $from_silo_id );
436 $self->{RECORD_INDEX}->put_record( $del_id, [ 0, 0, 0 ] );
437 $self->_swapout( $from_silo, $from_silo_id, $current_id_in_silo );
438  
439 return 1;
440 } #delete_record
441  
442  
443 sub has_id {
444 my( $self, $id ) = @_;
445 my $ec = $self->{RECORD_INDEX}->entry_count;
446  
447 return 0 if $ec < $id || $id < 1;
448  
449 my( $silo_id ) = @{ $self->{RECORD_INDEX}->get_record( $id ) };
450 return $silo_id > 0;
451 } #has_id
452  
453 sub next_id {
454 my( $self ) = @_;
455 my $ret = $self->{RECORD_INDEX}->next_id;
456 print STDERR "NEXT ID : $ret <$$>\n";
457 return $ret;
458 }
459  
460 sub empty {
461 my $self = shift;
462 $self->_lock_master;
463 my $silos = $self->_all_silos;
464 $self->{RECORD_INDEX}->empty;
465 for my $silo (@$silos) {
466 $silo->empty;
467 }
468 $self->_unlock_master;
469 } #empty
470  
471 # locks the given lock names
472 sub lock {
473 my( $self, @locknames ) = @_;
474 if( @{$self->{LOCKS}} ) {
475 die "Data::RecordStore->lock cannot be called twice in a row without unlocking between";
476 }
477 $self->_lock_master;
478 my @fhs;
479 my %seen;
480 my $failed;
481 for my $name (sort @locknames) {
482 next if $seen{$name}++;
483 if( open my $fh, '>', "$self->{DIRECTORY}/USER_LOCKS/$name" ) {
484 flock( $fh, LOCK_EX ); #WRITE LOCK
485 $fh->autoflush(1);
486 push @fhs, $fh;
487 } else {
488 $failed = 1;
489 }
490 }
491 if( $failed ) {
492 # it must be able to lock all the locks or it fails
493 # if it failed, unlock any locks it managed to get
494 for my $fh (@fhs) {
495 flock( $fh, LOCK_UN );
496 }
497 die "Data::RecordStore->lock : lock failed";
498 } else {
499 push @{$self->{LOCKS}}, @fhs;
500 }
501 $self->_unlock_master;
502 } #lock
503  
504 # unlocks all locks
505 sub unlock {
506 my $self = shift;
507 $self->_lock_master;
508 my $fhs = $self->{LOCKS};
509 for my $fh (@$fhs) {
510 flock( $fh, LOCK_UN );
511 }
512 @$fhs = ();
513 $self->_unlock_master;
514 } #unlock
515  
516  
517 # -/// PRIVATES ///-
518  
519 sub _time { #overridable for tests
520 return time();
521 }
522  
523  
524 #
525 # Returns a list of all the silos created in this Data::RecordStore
526 #
527 sub _all_silos {
528 my $self = shift;
529 opendir my $DIR, "$self->{DIRECTORY}/silos";
530 return [ map { /(\d+)_RECSTORE/; $self->_get_silo($1) } grep { /_RECSTORE/ } readdir($DIR) ];
531 } #_all_silos
532  
533 #This makes sure there there are at least min_count
534 #entries in this record store. This creates empty
535 #records if needed.
536 sub _ensure_entry_count {
537 shift->{RECORD_INDEX}->_ensure_entry_count( shift );
538 } #_ensure_entry_count
539  
540  
541 sub _get_silo {
542 my( $self, $silo_index ) = @_;
543  
544 my $dir = "$self->{DIRECTORY}/silos/${silo_index}_RECSTORE";
545 my $silo = $self->{SILOS}->fetch_silo($dir);
546 return $silo if $silo;
547  
548 if( $silo_index > 40 ) { # ~ 1 TB
549 die "TOO BIG SILOINDEX";
550 }
551  
552 my $silo_row_size = 2 ** $silo_index;
553  
554 # storing first the size of the record, uuencode flag, then the bytes of the record
555 $silo = $self->_open_silo( "LZ*", $dir, $silo_row_size );
556  
557 return $silo;
558 } #_get_silo
559  
560 #
561 # Removes a record from the store. If there was a record at the end of the store
562 # then move that record to the vacated space, reducing the file size by one record.
563 #
564 sub _swapout {
565 my( $self, $silo, $silo_id, $vacated_silo_id ) = @_;
566  
567 my $last_id = $silo->entry_count;
568  
569 if( $vacated_silo_id < $last_id ) {
570 my $data = $silo->_copy_record( $last_id - 1, $vacated_silo_id - 1 );
571 #
572 # update the record db with the new silo index for the moved record id
573 #
574 my( $moving_id ) = unpack( $silo->{TMPL}, $data );
575 my( $last_updated ) = $self->last_updated( $moving_id );
576  
577 $self->{RECORD_INDEX}->put_record( $moving_id, [ $silo_id, $vacated_silo_id, $last_updated ] );
578 }
579  
580 # remove the record from the end. This is either the record being vacated or the
581 # record that was moved into its place.
582 return $silo->pop;
583  
584 } #_swapout
585  
586  
587 # ----------- end Data::RecordStore
588  
589  
590 package Data::RecordStore::Silo;
591  
592 use strict;
593 use warnings;
594 no warnings 'uninitialized';
595 no warnings 'numeric';
596  
597 use Fcntl qw( :flock SEEK_SET );
598 use File::Path qw(make_path remove_tree);
599  
600 # this really isn't much of a limit anymore, but...
601 # keeping it for now
602 $Data::RecordStore::Silo::MAX_SIZE = 2_000_000_000;
603 sub open_silo {
604 my( $class, $template, $directory, $size ) = @_;
605  
606 my $template_size = $template =~ /\*/ ? 0 : do { use bytes; length( pack( $template ) ) };
607 my $record_size = $size || $template_size;
608  
609 unless( -d $directory ) {
610 die "Data::RecordStore::Silo->open_silo Error opening record store. $directory exists and is not a directory" if -e $directory;
611 make_path( $directory, { error => \my $err } );
612 }
613 open( my $silo_lock_fh, ">", "$directory/SILO_LOCK" ) or die "Unable to create $directory/SILO_LOCK : $!";
614 flock( $silo_lock_fh, LOCK_EX );
615 print $silo_lock_fh "SILO LOCK";
616 die "Data::RecordStore::Silo->open_sile error : given record size $size does not agree with template size $template_size" if $size && $template_size && $template_size != $size;
617 die "Data::RecordStore::Silo->open_silo Cannot open a zero record sized fixed store" unless $record_size;
618 my $file_max_records = int( $Data::RecordStore::Silo::MAX_SIZE / $record_size );
619 if( $file_max_records == 0 ) {
620 warn "Opening store at $directory with template '$template' of size $record_size which is above the set max size of $Data::RecordStore::Silo::MAX_SIZE. Allowing only one record per file for this size. ";
621 $file_max_records = 1;
622 }
623 my $file_max_size = $file_max_records * $record_size;
624 unless( -e "$directory/0" ){
625 open( my $fh, ">", "$directory/0" ) or die "Data::RecordStore::Silo->open_silo : Unable to open '$directory/0' : $!";
626 close $fh;
627 }
628  
629 unless( -w "$directory/0" ) {
630 die "Data::RecordStore::Silo->open_silo : Unable to open '$directory/0'";
631 }
632  
633 my $silo = bless {
634 DIRECTORY => $directory,
635 RECORD_SIZE => $record_size,
636 FILE_SIZE => $file_max_size,
637 FILE_MAX_RECORDS => $file_max_records,
638 TMPL => $template,
639 FILE_HANDLES => [],
640 SILO_LOCK_FH => $silo_lock_fh,
641 SILO_LOCK_COUNT => 1,
642 }, $class;
643  
644 $silo->unlock;
645  
646 return $silo;
647 } #open_silo
648  
649 sub lock {
650 my $self = shift;
651 if( 0 == $self->{SILO_LOCK_COUNT}++ ) {
652 flock( $self->{SILO_LOCK_FH}, LOCK_EX );
653 }
654  
655 }
656  
657 sub unlock {
658 my $self = shift;
659 if( 0 == --$self->{SILO_LOCK_COUNT} ) {
660 flock( $self->{SILO_LOCK_FH}, LOCK_UN );
661 }
662 }
663  
664 sub empty {
665 my $self = shift;
666 $self->lock;
667 my( $first, @files ) = map { "$self->{DIRECTORY}/$_" } $self->_files;
668 truncate( $first, 0 ) // die "Unable to empty silo $self->{DIRECTORY}";
669 for my $file (@files) {
670 unlink( $file );
671 }
672 $self->unlock;
673 return undef;
674 } #empty
675  
676 sub size {
677 my $self = shift;
678 my @files = $self->_files;
679 my $filesize;
680 for my $file (@files) {
681 $filesize += -s "$self->{DIRECTORY}/$file";
682 }
683 return $filesize;
684 }
685  
686 sub entry_count {
687 # return how many entries this silo has
688 my $self = shift;
689 my @files = $self->_files;
690 my $filesize;
691 for my $file (@files) {
692 $filesize += -s "$self->{DIRECTORY}/$file";
693 }
694 return int( $filesize / $self->{RECORD_SIZE} );
695 } #entry_count
696  
697 sub get_record {
698 my( $self, $id ) = @_;
699  
700 print STDERR "Get Record ($id) <$$> $self->{DIRECTORY}\n";
701 $self->lock;
702 if( $id > $self->entry_count || $id < 1 ) {
703 $self->unlock;
704 die "Data::RecordStore::Silo->get_record : index $id out of bounds for silo $self->{DIRECTORY}. Silo has entry count of ".$self->entry_count;
705 }
706  
707 my( $f_idx, $fh, $file, $file_id ) = $self->_fh( $id );
708  
709 my $seek_pos = $self->{RECORD_SIZE} * $f_idx;
710 sysseek( $fh, $seek_pos, SEEK_SET );
711 my $srv = sysread $fh, my $data, $self->{RECORD_SIZE};
712 $self->unlock;
713  
714 return [unpack( $self->{TMPL}, $data )];
715 } #get_record
716  
717 sub next_id {
718 my( $self ) = @_;
719 $self->lock;
720 my $next_id = 1 + $self->entry_count;
721 $self->_ensure_entry_count( $next_id );
722 $self->unlock;
723 return $next_id;
724 } #next_id
725  
726  
727 sub pop {
728 my( $self ) = @_;
729 print STDERR "POP <$$> $self->{DIRECTORY}\n";
730 $self->lock;
731 my $entries = $self->entry_count;
732 unless( $entries ) {
733 $self->unlock;
734 return undef;
735 }
736 my $ret = $self->get_record( $entries );
737 my( $idx_in_f, $fh, $file, $f_idx ) = $self->_fh( $entries );
738 my $new_fs = (($entries-1) - ($f_idx * $self->{FILE_MAX_RECORDS} ))*$self->{RECORD_SIZE};
739  
740 if( $new_fs || $file =~ m!/0$! ) {
741 truncate $fh, $new_fs;
742 } else {
743 unlink $file;
744 $self->_clearfh( $f_idx );
745 }
746
747 $self->unlock;
748 return $ret;
749 } #pop
750  
751 sub last_entry {
752 my( $self ) = @_;
753 print STDERR "LAST ENTRY <$$> $self->{DIRECTORY}\n";
754 $self->lock;
755 my $entries = $self->entry_count;
756 unless( $entries ) {
757 $self->unlock;
758 return undef;
759 }
760 my $r = $self->get_record( $entries );
761 $self->unlock;
762 return $r;
763 } #last_entry
764  
765 sub push {
766 my( $self, $data ) = @_;
767 print STDERR "PUSH <$$> $self->{DIRECTORY}\n";
768 $self->lock;
769 my $next_id = $self->next_id;
770  
771 # the problem is that the second file has stuff in it not sure how
772 $self->put_record( $next_id, $data );
773 $self->unlock;
774  
775 return $next_id;
776 } #push
777  
778  
779 sub put_record {
780 my( $self, $id, $data ) = @_;
781 print STDERR "PUT RECORD ($id) <$$> $self->{DIRECTORY}\n";
782 $self->lock;
783  
784 if( $id > $self->entry_count || $id < 1 ) {
785 $self->unlock;
786 die "Data::RecordStore::Silo->put_record : index $id out of bounds for silo $self->{DIRECTORY}. Store has entry count of ".$self->entry_count;
787 }
788  
789 my $to_write = pack ( $self->{TMPL}, ref $data ? @$data : $data );
790  
791 # allows the put_record to grow the data store by no more than one entry
792 my $write_size = do { use bytes; length( $to_write ) };
793  
794 if( $write_size > $self->{RECORD_SIZE} ) {
795 $self->unlock;
796 die "Data::RecordStore::Silo->put_record : record size $write_size too large. Max is $self->{RECORD_SIZE}";
797 }
798  
799 my( $idx_in_f, $fh, $file, $file_id ) = $self->_fh( $id );
800 my $seek_pos = $self->{RECORD_SIZE} * ($idx_in_f);
801 sysseek( $fh, $seek_pos, SEEK_SET );
802 syswrite( $fh, $to_write );
803  
804 $self->unlock;
805 # close $fh;
806  
807 return 1;
808 } #put_record
809  
810 sub unlink_store {
811 my $self = shift;
812 remove_tree( $self->{DIRECTORY} );# // die "Data::RecordStore::Silo->unlink_store: Error unlinking store : $!";
813 } #unlink_store
814  
815 #
816 # This copies a record from one index in the store to an other.
817 # This returns the data of record so copied. Note : idx designates an index beginning at zero as
818 # opposed to id, which starts with 1.
819 #
820 sub _copy_record {
821 my( $self, $from_idx, $to_idx ) = @_;
822 print STDERR "COPY RECORD ($from_idx->$to_idx) <$$> $self->{DIRECTORY}\n";
823 $self->lock;
824 if( $from_idx >= $self->entry_count || $from_idx < 0 ) {
825 $self->unlock;
826 die "Data::RecordStore::Silo->_copy_record : from_index $from_idx out of bounds. Store has entry count of ".$self->entry_count;
827 }
828  
829 if( $to_idx >= $self->entry_count || $to_idx < 0 ) {
830 $self->unlock;
831 die "Data::RecordStore::Silo->_copy_record : to_index $to_idx out of bounds. Store has entry count of ".$self->entry_count;
832 }
833  
834 my( $from_file_idx, $fh_from ) = $self->_fh($from_idx+1);
835 my( $to_file_idx, $fh_to ) = $self->_fh($to_idx+1);
836 my $seek_pos = $self->{RECORD_SIZE} * ($from_file_idx);
837 sysseek $fh_from, $seek_pos, SEEK_SET;
838 my $srv = sysread $fh_from, my $data, $self->{RECORD_SIZE};
839  
840 $seek_pos = $self->{RECORD_SIZE} * $to_file_idx;
841 sysseek( $fh_to, $seek_pos, SEEK_SET );
842 syswrite( $fh_to, $data );
843  
844 $self->unlock;
845  
846 return $data;
847 } #_copy_record
848  
849  
850 #Makes sure this silo has at least as many entries
851 #as the count given. This creates empty records if needed
852 #to rearch the target record count.
853 sub _ensure_entry_count {
854 my( $self, $count ) = @_;
855 print STDERR "ENSURE ($count) <$$> $self->{DIRECTORY}\n";
856 my $needed = $count - $self->entry_count;
857  
858 if( $needed > 0 ) {
859 $self->lock;
860 my( @files ) = $self->_files;
861 my $write_file = $files[$#files];
862  
863 my $existing_file_records = int( (-s "$self->{DIRECTORY}/$write_file" ) / $self->{RECORD_SIZE} );
864 my $records_needed_to_fill = $self->{FILE_MAX_RECORDS} - $existing_file_records;
865 $records_needed_to_fill = $needed if $records_needed_to_fill > $needed;
866  
867 if( $records_needed_to_fill > 0 ) {
868 # fill the last file up with \0
869 my $fh;
870 unless( open( $fh, "+<", "$self->{DIRECTORY}/$write_file" ) ) {
871 $self->unlock;
872 die "Data::RecordStore::Silo->ensure_entry_count : Unable to open '$self->{DIRECTORY}/$write_file' : $!";
873 }
874 my $nulls = "\0" x ( $records_needed_to_fill * $self->{RECORD_SIZE} );
875 my $seek_pos = $self->{RECORD_SIZE} * $existing_file_records;
876 sysseek( $fh, $seek_pos, SEEK_SET );
877 syswrite( $fh, $nulls );
878 close $fh;
879  
880 $needed -= $records_needed_to_fill;
881 }
882 while( $needed > $self->{FILE_MAX_RECORDS} ) {
883 # still needed, so create a new file
884 $write_file++;
885  
886 if( -e "$self->{DIRECTORY}/$write_file" ) {
887 $self->unlock;
888 die "Data::RecordStore::Silo->ensure_entry_count : file $self->{DIRECTORY}/$write_file already exists";
889 }
890 open( my $fh, ">", "$self->{DIRECTORY}/$write_file" );
891 my $nulls = "\0" x ( $self->{FILE_MAX_RECORDS} * $self->{RECORD_SIZE} );
892 sysseek( $fh, 0, SEEK_SET );
893 syswrite( $fh, $nulls );
894 $needed -= $self->{FILE_MAX_RECORDS};
895 close $fh;
896 }
897 if( $needed > 0 ) {
898 # still needed, so create a new file
899 $write_file++;
900  
901 if( -e "$self->{DIRECTORY}/$write_file" ) {
902 $self->unlock;
903 die "Data::RecordStore::Silo->ensure_entry_count : file $self->{DIRECTORY}/$write_file already exists";
904 }
905 open( my $fh, ">", "$self->{DIRECTORY}/$write_file" );
906 my $nulls = "\0" x ( $needed * $self->{RECORD_SIZE} );
907 sysseek( $fh, 0, SEEK_SET );
908 syswrite( $fh, $nulls );
909 close $fh;
910 }
911 $self->unlock;
912 }
913 return;
914 } #_ensure_entry_count
915  
916 sub _clearfh {
917 my( $self, $f_idx ) = @_;
918 ( undef, my $fh ) = @{$self->{FILE_HANDLES}[$f_idx]||[]};
919 if( $fh ) {
920 close $fh;
921 }
922 $self->{FILE_HANDLES}[$f_idx] = undef;
923 }
924  
925 #
926 # Takes an insertion id and returns
927 # an insertion index for in the file
928 # filehandle.
929 # filepath/filename
930 # which number file this is (0 is the first)
931 #
932 sub _fh {
933 my( $self, $id ) = @_;
934  
935 my $f_idx = int( ($id-1) / $self->{FILE_MAX_RECORDS} );
936 my $idx_in_f = ($id - ($f_idx*$self->{FILE_MAX_RECORDS})) - 1;
937
938 my $fh_info = $self->{FILE_HANDLES}[$f_idx];
939 if( $fh_info ) {
940 $fh_info->[0] = $idx_in_f;
941 return @$fh_info;
942 }
943  
944 $self->lock;
945 my @files = $self->_files;
946 my $file = $files[$f_idx];
947  
948 my $fh;
949 unless( open( $fh, "+<", "$self->{DIRECTORY}/$file" ) ) {
950 $self->unlock;
951 die "Data::RecordStore::Silo->_fh unable to open '$self->{DIRECTORY}/$file' : $! $?";
952 }
953 $fh->autoflush(1);
954 # index in the file, $file handle, $file, $f_idx
955 $fh_info = [$idx_in_f,$fh,"$self->{DIRECTORY}/$file",$f_idx];
956  
957 $self->{FILE_HANDLES}[$f_idx] = $fh_info;
958 $self->unlock;
959 return @$fh_info;
960  
961 } #_fh
962  
963 #
964 # Returns the list of filenames of the 'silos' of this store. They are numbers starting with 0
965 #
966 sub _files {
967 my $self = shift;
968 $self->lock;
969 my $dh = $self->{DIR_HANDLE};
970 if( $dh ) {
971 rewinddir $dh;
972 } else {
973 unless( opendir( $dh, $self->{DIRECTORY} ) ) {
974 $self->unlock;
975 die "Data::RecordStore::Silo->_files : can't open $self->{DIRECTORY}\n";
976 }
977 $self->{DIR_HANDLE} = $dh;
978 }
979 my( @files ) = (sort { $a <=> $b } grep { $_ eq '0' || (-s "$self->{DIRECTORY}/$_") > 0 } grep { $_ > 0 || $_ eq '0' } readdir( $dh ) );
980 $self->unlock;
981 return @files;
982 } #_files
983  
984 # ----------- end Data::RecordStore::Silo
985  
986 package Data::RecordStore::SiloPack;
987  
988 use strict;
989 use warnings;
990 no warnings 'uninitialized';
991 no warnings 'numeric';
992  
993 use Fcntl qw( :flock SEEK_SET );
994 use File::Path qw(make_path remove_tree);
995  
996 sub new {
997 return bless {
998 SILOS => {},
999 }, shift;
1000 }
1001 sub clear_silos {
1002 my $self = shift;
1003 $self->{SILOS} = {};
1004 }
1005 sub clear_silo {
1006 my( $self, $dir ) = @_;
1007 delete $self->{SILOS}{$dir};
1008 }
1009 sub fetch_silo {
1010 my( $self, $dir ) = @_;
1011 return $self->{SILOS}{$dir};
1012 }
1013 sub open_silo {
1014 my $self = shift;
1015 my( $template, $directory, $size ) = @_;
1016  
1017 my $template_size = $template =~ /\*/ ? 0 : do { use bytes; length( pack( $template ) ) };
1018 my $record_size = $size || $template_size;
1019  
1020 my $silo = $self->{SILOS}{$directory};
1021 if( $silo ) {
1022 # check if the size and template are asked for
1023 if( $silo->{RECORD_SIZE} == $record_size && $silo->{TMPL} eq $template ) {
1024 return $silo;
1025 }
1026 warn "Asking for a silo of a different size from one that was already cached. Creating new";
1027 }
1028 $silo = Data::RecordStore::Silo->open_silo( @_ );
1029 $self->{SILOS}{$directory} = $silo;
1030 return $silo;
1031 } #open_silo
1032  
1033  
1034 # ----------- end Data::RecordStore::SiloPack
1035  
1036 package Data::RecordStore::Transaction;
1037  
1038 use constant {
1039  
1040 ID => 0,
1041 PID => 1,
1042 UPDATE_TIME => 2,
1043 STATE => 3,
1044  
1045 TRA_ACTIVE => 1, # transaction has been created
1046 TRA_IN_COMMIT => 2, # commit has been called, not yet completed
1047 TRA_IN_ROLLBACK => 3, # commit has been called, has not yet completed
1048 TRA_CLEANUP_COMMIT => 4, # everything in commit has been written, TRA is in process of being removed
1049 TRA_CLEANUP_ROLLBACK => 5, # everything in commit has been written, TRA is in process of being removed
1050 TRA_DONE => 6, # transaction complete. It may be removed.
1051 };
1052  
1053 our @STATE_LOOKUP = ('Active',
1054 'In Commit',
1055 'In Rollback',
1056 'In Commit Cleanup',
1057 'In Rollback Cleanup',
1058 'Done');
1059  
1060 #
1061 # Creates a new transaction or returns an existing one based on the data provided
1062 #
1063 sub _create {
1064 my( $pkg, $record_store, $trans_data ) = @_;
1065  
1066 # A transaction has the following
1067 # transaction id
1068 # process id
1069 # update time
1070 # state
1071 my $trans_dir = "$record_store->{DIRECTORY}/TRANS";
1072 my $trans_catalog = $record_store->_open_silo( "ILLI", "$trans_dir/META" );
1073 my $trans_id;
1074  
1075 # trans data is passed in when an existing transaction is loaded
1076 if( $trans_data ) {
1077 ($trans_id) = @$trans_data;
1078 }
1079 else {
1080 $trans_id = $trans_catalog->next_id;
1081 $trans_data = [ $trans_id, $$, time, TRA_ACTIVE ];
1082 $trans_catalog->put_record( $trans_id, $trans_data );
1083 }
1084  
1085 # ACTION_SILO (idx is action id)
1086 # action
1087 # record id
1088 # from silo id
1089 # from silo record id
1090 # to silo id
1091 # to silo record id
1092 # ITEM_SILO (idx is record id)
1093 # action id
1094 my $trans_obj = {
1095 ID => $trans_id,
1096 RECORD_STORE => $record_store,
1097 ACTION_SILO => $record_store->_open_silo(
1098 "ALILIL",
1099 "$trans_dir/instances/$trans_id",
1100 ),
1101 ITEM_SILO => $record_store->_open_silo(
1102 "L",
1103 "$trans_dir/instances/D_$trans_id",
1104 ),
1105 DATA => $trans_data,
1106 CATALOG => $trans_catalog, #LLLI
1107 };
1108 return bless $trans_obj, $pkg;
1109  
1110 } #_create
1111  
1112  
1113 sub get_update_time { shift->{DATA}[UPDATE_TIME] }
1114  
1115 sub get_process_id { shift->{DATA}[PID] }
1116  
1117 sub get_state { shift->{DATA}[STATE] }
1118  
1119 sub get_id { shift->{DATA}[ID] }
1120  
1121 sub stow {
1122 my( $self, $data, $id ) = @_;
1123  
1124 die "Data::RecordStore::Transaction::stow Error : is not active" unless $self->get_state == TRA_ACTIVE;
1125  
1126 my $action_silo = $self->{ACTION_SILO};
1127 my $item_silo = $self->{ITEM_SILO};
1128  
1129 my $store = $self->{RECORD_STORE};
1130  
1131 unless( defined $id ) {
1132 $id = $store->next_id( 1 );
1133 }
1134  
1135 if( $id < 1 || int($id) != $id ) {
1136 die "ID must be a positive integer";
1137 }
1138  
1139 $store->_ensure_entry_count( $id );
1140  
1141 my $save_size = do { use bytes; length( $data ); };
1142  
1143 # tack on the size of the id (a long + \0 or 5 bytes) to the byte count
1144 $save_size += 5;
1145 my( $from_silo_id, $from_record_id ) = @{ $store->{RECORD_INDEX}->get_record( $id ) };
1146  
1147 my $to_silo_id = 12; # the min size
1148  
1149 if( $save_size > 4096 ) {
1150 $to_silo_id = log( $save_size ) / log( 2 );
1151 if( int( $to_silo_id ) < $to_silo_id ) {
1152 $to_silo_id = 1 + int( $to_silo_id );
1153 }
1154 }
1155  
1156 my $to_silo = $store->_get_silo( $to_silo_id );
1157  
1158 my $to_record_id = $to_silo->next_id(1);
1159  
1160 $to_silo->put_record( $to_record_id, [ $id, $data ] );
1161  
1162 my $next_action_id = $action_silo->next_id(1);
1163  
1164 # action (stow)
1165 # record id
1166 # from silo id
1167 # from silo idx
1168 # to silo id
1169 # to silo idx
1170 $action_silo->put_record( $next_action_id,
1171 [ 'S', $id, $from_silo_id, $from_record_id, $to_silo_id, $to_record_id ] );
1172  
1173 $item_silo->_ensure_entry_count( $id );
1174 $item_silo->put_record( $id, [ $next_action_id ] );
1175  
1176 return $id;
1177 } #stow
1178  
1179  
1180 sub delete_record {
1181 my( $self, $id_to_delete ) = @_;
1182 die "Data::RecordStore::Transaction::delete_record Error : is not active" unless $self->get_state == TRA_ACTIVE;
1183  
1184 my $store = $self->{RECORD_STORE};
1185 my $action_silo = $self->{ACTION_SILO};
1186 my $item_silo = $self->{ITEM_SILO};
1187  
1188 my( $from_silo_id, $from_record_id ) = @{ $store->{RECORD_INDEX}->get_record( $id_to_delete ) };
1189 my $next_action_id = $action_silo->next_id(1);
1190 $action_silo->put_record( $next_action_id,
1191 [ 'D', $id_to_delete, $from_silo_id, $from_record_id, 0, 0 ] );
1192 $item_silo->_ensure_entry_count( $id_to_delete );
1193 $item_silo->put_record( $id_to_delete, [ $next_action_id ] );
1194  
1195 return 1;
1196 } #delete_record
1197  
1198 sub commit {
1199 my $self = shift;
1200  
1201 my $store = $self->{RECORD_STORE};
1202  
1203 my $trans = shift @{$store->{TRANSACTION}};
1204  
1205 unless( $trans eq $self ) {
1206 unshift @{$store->{TRANSACTION}}, $trans;
1207 die "Cannot commit outer transaction intil inner transactions have been committed";
1208 }
1209  
1210 my $state = $self->get_state;
1211 unless( $state == TRA_ACTIVE || $state == TRA_IN_COMMIT ||
1212 $state == TRA_IN_ROLLBACK || $state == TRA_CLEANUP_COMMIT ) {
1213 unshift @{$store->{TRANSACTION}}, $trans;
1214 die "Cannot commit transaction. Transaction state is ".$STATE_LOOKUP[$state];
1215 }
1216  
1217 my $index = $store->{RECORD_INDEX};
1218 my $cat_silo = $self->{CATALOG};
1219 my $action_silo = $self->{ACTION_SILO};
1220 my $item_silo = $self->{ITEM_SILO};
1221  
1222 my $trans_id = $self->{ID};
1223  
1224 $cat_silo->put_record( $trans_id, [ $trans_id, $$, Data::RecordStore::_time, TRA_IN_COMMIT ] );
1225 $self->{DATA}[STATE] = TRA_IN_COMMIT;
1226  
1227 my $actions = $action_silo->entry_count;
1228  
1229 #
1230 # In this phase, the indexes are updated to point to new locations
1231 # of updated (via stow) items.
1232 # The old locations are marked for purging, which occurs in a later
1233 # stage.
1234 #
1235 # Since a stow can occur MULTIple times for a single id, only the
1236 # last stow is acted upon.
1237 #
1238 my $purges = [];
1239 my( %foundid );
1240 for( my $a_id=$actions; $a_id > 0; $a_id-- ) {
1241 my $tstep = $action_silo->get_record($a_id);
1242 my( $action, $record_id, $from_silo_id, $from_record_id, $to_silo_id, $to_record_id ) = @$tstep;
1243 if( 0 == $foundid{$record_id}++ ) {
1244 # first time this record is acted upon
1245 if( $action eq 'S' ) {
1246 $index->put_record( $record_id, [ $to_silo_id, $to_record_id, Data::RecordStore::_time ] );
1247 }
1248 push @$purges, [ $action, $record_id, $from_silo_id, $from_record_id ];
1249  
1250 }
1251 elsif( $action eq 'S' ) {
1252 push @$purges, [ $action, $record_id, $to_silo_id, $to_record_id ];
1253 }
1254 }
1255  
1256 #
1257 # This clause deletes records, and deletes the old
1258 # locations of stowed entries.
1259 #
1260 $purges = [ sort { $b->[3] <=> $a->[3] } @$purges ];
1261 for my $purge (@$purges) {
1262 my( $action, $record_id, $from_silo_id, $from_record_id ) = @$purge;
1263 if ( $action eq 'S' ) {
1264 my $silo = $store->_get_silo( $from_silo_id );
1265 $store->_swapout( $silo, $from_silo_id, $from_record_id );
1266 } elsif ( $action eq 'D' ) {
1267 $store->delete_record( $record_id, 1 );
1268 }
1269 }
1270  
1271 #
1272 # Update the state of this transaction and remove the record.
1273 #
1274 $cat_silo->put_record( $trans_id, [ $trans_id, $$, Data::RecordStore::_time, TRA_DONE ] );
1275 $self->{DATA}[STATE] = TRA_DONE;
1276  
1277 $action_silo->unlink_store;
1278 $item_silo->unlink_store;
1279 $store->_close_silo( $action_silo );
1280 $store->_close_silo( $item_silo );
1281  
1282 return 1;
1283 } #commit
1284  
1285  
1286 sub rollback {
1287 my $self = shift;
1288 my $store = $self->{RECORD_STORE};
1289 my $trans = shift @{$store->{TRANSACTION}};
1290  
1291 my $state = $self->get_state;
1292 unless( $state == TRA_ACTIVE || $state == TRA_IN_COMMIT ||
1293 $state == TRA_IN_ROLLBACK || $state == TRA_CLEANUP_ROLLBACK ) {
1294 unshift @{$store->{TRANSACTION}}, $trans;
1295 die "Cannot rollback transaction. Transaction state is ".$STATE_LOOKUP[$state];
1296 }
1297  
1298 my $index = $store->{RECORD_INDEX};
1299 my $cat_silo = $self->{CATALOG};
1300 my $action_silo = $self->{ACTION_SILO};
1301 my $item_silo = $self->{ITEM_SILO};
1302 my $trans_id = $self->{ID};
1303  
1304 $cat_silo->put_record( $trans_id, [ $trans_id, $$, time, TRA_IN_ROLLBACK ] );
1305 $self->{DATA}[STATE] = TRA_IN_ROLLBACK;
1306  
1307 my $actions = $action_silo->entry_count;
1308  
1309 #
1310 # Rewire the index to the old silo/location
1311 #
1312 my( %swapout );
1313 for my $a_id (1..$actions) {
1314 my( $action, $record_id, $from_silo_id, $from_record_id, $to_silo_id, $to_record_id ) =
1315 @{ $action_silo->get_record($a_id) };
1316 if( $from_silo_id ) {
1317 $index->put_record( $record_id, [ $from_silo_id, $from_record_id, time ] );
1318 } else {
1319 $index->put_record( $record_id, [ 0, 0, 0 ] );
1320 }
1321 if( $to_silo_id ) {
1322 push @{$swapout{ $to_silo_id }}, $to_record_id;
1323 }
1324 }
1325  
1326 $cat_silo->put_record( $trans_id, [ $trans_id, $$, time, TRA_CLEANUP_ROLLBACK ] );
1327 $self->{DATA}[STATE] = TRA_CLEANUP_ROLLBACK;
1328  
1329 #
1330 # Cleanup new data. The swapouts for a silo are sorted by descending ID.
1331 # this allows the cleanup to go backwards from the end of the silo file
1332 #
1333 for my $to_silo_id (keys %swapout) {
1334 for my $to_record_id (sort { $b <=> $a } @{$swapout{$to_silo_id}}) {
1335 my $to_silo = $store->_get_silo( $to_silo_id );
1336 $store->_swapout( $to_silo, $to_silo_id, $to_record_id );
1337 }
1338 }
1339  
1340 $cat_silo->put_record( $trans_id, [ $trans_id, $$, time, TRA_DONE ] );
1341 $self->{DATA}[STATE] = TRA_DONE;
1342  
1343 $action_silo->unlink_store;
1344 $item_silo->unlink_store;
1345 $store->_close_silo( $action_silo );
1346 $store->_close_silo( $item_silo );
1347  
1348 # if this is the last transaction, remove it from the list
1349 # of transactions
1350 if( $trans_id == $cat_silo->entry_count ) {
1351 $cat_silo->pop;
1352 }
1353 return;
1354 } #rollback
1355  
1356 1;
1357  
1358 __END__