-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRotateDir.pl
executable file
·2508 lines (1925 loc) · 82.5 KB
/
RotateDir.pl
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# The following POD section contains placeholders, so it has to be preprocessed by this script first.
#
# HelpBeginMarker
=head1 OVERVIEW
PROGRAM_NAME version SCRIPT_VERSION
This tool makes room for a new slot, deleting older slots if necessary. Each slot is just a directory on disk.
An example where such a directory rotation is useful would be a daily build server, where build results
from the last 10 days should be available at any point in time.
If RotateDir is used from a script, the caller must parse this tool's output in order to recover
the new directory name. Option "--output-only-new-dir-name" helps simplify the parsing, see below.
The top-level containing directory must already exist.
It's best not to place unrelated content in the top-level directory containing the slots,
as any foreign contents are always at risk of being elected
for automatic deletion during rotation. Even if that could never happen in a given configuration,
a future human error modifiying that configuration might lead to unpleasant surprises.
If you are using this script to do rotating backups, and you have a monitoring system,
see script CheckIfAnyFilesModifiedRecently/SanityCheckRotatingBackup.sh for an example
on how to check that backups are still being performed regularly
and the number of slots falls within expectation.
=head1 HOW SLOTS ARE ROTATED
This is what a rotating directory set looks like, in slot age order:
basedir/rotated-dir-9
basedir/rotated-dir-10-optional-comment
basedir/rotated-dir-11 some manual comment
basedir/rotated-dir-200
If the maximum slot count is 4, then the next time around directory 'rotated-dir-9' will
be deleted and directory "rotated-dir-201" will be created.
Alternatively, directory names can be made of timestamps like this:
basedir/rotated-dir-2010-12-31
basedir/rotated-dir-2011-01-01
basedir/rotated-dir-2011-01-01~2
basedir/rotated-dir-2011-01-01~3-optional-comment
basedir/rotated-dir-2011-01-01~4 some manual comment
basedir/rotated-dir-2011-05-10
Note that, because date "2011-01-01" is duplicated, a sequence number has been automatically appended.
The naming scheme must be based on either plain sequence numbers or timestamps; mixing both
schemes in a single containing directory is not allowed.
The directory's creation date, as recorded in the filesystem, is not considered when determining a slot's age.
Only the slot squence number or timestamp, as recovered from the directory's filename, is taken into account.
This tool does not look at the amount of disk space each slot occupies, it only looks at the number of slots.
The slot size could be taken into account in a future version, but note that the only safe way to limit
disk size on a daily build scenario would be to set a size quota on each separate slot directory
at a file system level. Otherwise, a single run can generate a slot bigger than the combined size limit
for all slots together.
=head1 USAGE
S<perl PROGRAM_NAME [options] E<lt>containing directory nameE<gt>>
=head1 OPTIONS
=over
=item *
B<-h, --OPT_NAME_HELP>
Print this help text.
=item *
B<--version>
Print this tool's name and version number (SCRIPT_VERSION).
=item *
B<--license>
Print the license.
=item *
B<< --OPT_NAME_SELF_TEST >>
Run the built-in self-tests.
=item *
B<-->
Terminate options processing. Useful to avoid confusion between options and a directory name
that begins with a hyphen ('-'). Recommended when calling this script from another script,
where the directory name comes from a variable or from user input.
=item *
B<--slot-count n>
Maximum number of rotating directores on disk. The default is 3.
This option is incompatible with --no-slot-deletion .
=item *
B<--dir-name-prefix E<lt>prefixE<gt>>
Prefix for the rotated directory names. The default is "rotated-dir-".
Warning: all directories whose names have the given prefix are candidates
for automatic deletion when the maximum slot count is reached.
=item *
B<--dir-naming-scheme E<lt>typeE<gt>>
Naming scheme for the rotated directory names. Possible types are:
=over
=item *
sequence
The default. This is a monotonically-increasing integer number
calculated as "the highest value I see on disk at the moment + 1".
On an empty containing directory, the first sequence number will be 1,
but it's best not to rely on this and always look at RotateDir's output.
=item *
date
A timestamp in the form "yyyy-mm-dd", like "2010-12-31". See option
--timestamp for more information.
=back
=item *
B<--timestamp E<lt>yyyy-mm-ddE<gt>>
This option is only allowed when the naming scheme has been set to a timestamp-based type.
The given timestamp will be used to name the new slot directory. An example
timestamp would be "2010-12-31". In order to avoid surprises, it's best to
zero-fill the date fields, therefore "2010-01-02" is better than "2010-1-2".
The new timestamp must be the equal to or greater than the ones already present in the containing directory.
If that is not the case, an error will be generated.
If the same timestamp is already on disk, a sequence number is appended, like "2010-12-31~2".
The first sequence number for timestamp-based naming is 2, but it's best not to
rely on this and always look at RotateDir's output. Further sequence numbers
are calculated as "the highest value I see on disk at the moment + 1".
A standard epoch-based integer timestamp would have been easier to handle,
but there are still unresolved year 2038 issues in perl, see this tool's source code for details.
The default is to take the current local time. An error will be generated
if the perl environment cannot handle years after 2038,
even if that date has not been reached yet.
This option is incompatible with --no-slot-creation .
=item *
B<--dir-name-suffix E<lt>suffixE<gt>>
An optional suffix for the newly-created directory name. This is intended to be used
as a reminder of why the slot was created, that is, it is only a comment.
A hyphen is always inserted before the given suffix.
The following illustrates why such a suffix can be useful:
basedir/rotated-dir-22-KnownToFail
basedir/rotated-dir-23-FirstWithGccVersion10
basedir/rotated-dir-24
basedir/rotated-dir-25-SameAsBefore
You can manually add or change the suffix after the directory has been created.
In this case, you can use a space as a separator (instead of a hyphen).
=item *
B<< --no-slot-deletion >>
Create a new slot but do not delete any old ones.
This option is incompatible with --slot-count, --no-slot-creation and --deletion-delay.
=item *
B<< --no-slot-creation >>
Make room for a new slot, deleting older slots if necessary,
but do not create a new slot. Therefore, assuming --slot-count is set to 10,
this option will leave a maximum of 9 slots behind.
This option is incompatible with --no-slot-deletion and with --output-only-new-dir-name .
=item *
B<--output-only-new-dir-name>
Print only the new slot's directory name and no other messages.
Useful when running this tool from automated scripts, so that there is no other text output
to parse and discard.
The output includes the containing directory name and a new-line character at the end.
This option is incompatible with --no-slot-creation .
=item *
B<--deletion-delay E<lt>secondsE<gt>>
On Microsoft Windows, sometimes it takes a few seconds for a deleted directory
to actually go away, especially if the user is looking at it
with Windows Explorer. If the delete operation succeeds but the directory
is still visible on the filesystem, RotateDir will wait the given number of seconds
and check again whether the directory continues to exist. If the directory is still there
after the wait, an error will be generated.
The default is 5 seconds. A value of 0 disables the waiting and the second check.
This option is incompatible with --no-slot-deletion .
=back
=head1 EXIT CODE
Exit code: 0 on success, some other value on error.
=head1 FEEDBACK
Please send feedback to rdiezmail-tools at yahoo.de
=head1 LICENSE
Copyright (C) 2011-2022 R. Diez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License version 3 for more details.
You should have received a copy of the GNU Affero General Public License version 3
along with this program. If not, see L<http://www.gnu.org/licenses/>.
=cut
# HelpEndMarker
use strict;
use warnings;
use FindBin qw( $Bin $Script );
use Getopt::Long qw( GetOptionsFromString );
use File::Glob;
use File::Spec qw();
use File::Path;
use IO::Handle;
use Pod::Usage qw();
use Class::Struct qw();
use constant PROGRAM_NAME => "RotateDir.pl";
use constant SCRIPT_VERSION => "2.15";
use constant EXIT_CODE_SUCCESS => 0;
use constant EXIT_CODE_FAILURE_ARGS => 1;
use constant EXIT_CODE_FAILURE_ERROR => 2;
use constant TRUE => 1;
use constant FALSE => 0;
use constant NS_SEQUENCE => "sequence";
use constant NS_DATE => "date";
use constant FIRST_SEQUENCE_SEQUENCE_NUMBER => 1;
use constant FIRST_TIMESTAMP_SEQUENCE_NUMBER => 2;
use constant DATE_SEPARATOR => "-";
# Up until version 2.14 this script used a hyphen ('-'), but from version 2.15 it changed
# to a tilde ('~'), in order to accomodate an optional suffix.
use constant SEQUENCE_NUMBER_SEPARATOR_FOR_DATES => "~";
use constant SEQUENCE_NUMBER_SEPARATOR_FOR_DATES_OLD => "-";
use constant OPT_NAME_HELP =>'help';
use constant OPT_NAME_SELF_TEST => "self-test";
# This is important: if the sequence numbers overflow, we don't want Perl
# to resort to floating-point numbers.
use integer;
Class::Struct::struct( CSlotInfo =>
{
dirName => '$',
slotSubdirName => '$',
afterPrefix => '$', # slotSubdirName minus the prefix
year => '$',
month => '$',
day => '$',
sequenceNumber => '$'
}
);
# ----------- main routine, the script entry point is at the bottom -----------
sub main ()
{
my $arg_help = FALSE;
my $arg_h = FALSE;
my $arg_help_pod = FALSE;
my $arg_version = FALSE;
my $arg_license = FALSE;
my $arg_self_test = FALSE;
my $arg_slotCount;
my $arg_deletionDelay;
my $arg_dirNamePrefix = "rotated-dir-";
my $arg_dirNameSuffix;
my $arg_dirNamingScheme = NS_SEQUENCE;
my $arg_timestamp;
my $arg_outputOnlyNewDir = FALSE;
my $arg_noSlotDeletion = FALSE;
my $arg_noSlotCreation = FALSE;
Getopt::Long::Configure( "no_auto_abbrev", "prefix_pattern=(--|-)", "no_ignore_case", "require_order" );
my $result = GetOptions(
OPT_NAME_HELP() => \$arg_help,
'h' => \$arg_h,
'help-pod' => \$arg_help_pod,
'version' => \$arg_version,
'license' => \$arg_license,
OPT_NAME_SELF_TEST() => \$arg_self_test,
'slot-count=s' => \$arg_slotCount,
'deletion-delay=s' => \$arg_deletionDelay,
'dir-name-prefix=s' => \$arg_dirNamePrefix,
'dir-name-suffix=s' => \$arg_dirNameSuffix,
'dir-naming-scheme=s' => \$arg_dirNamingScheme,
'timestamp=s' => \$arg_timestamp,
'no-slot-deletion' => \$arg_noSlotDeletion,
'no-slot-creation' => \$arg_noSlotCreation,
'output-only-new-dir-name' => \$arg_outputOnlyNewDir
);
if ( not $result )
{
# GetOptions has already printed an error message.
return EXIT_CODE_FAILURE_ARGS;
}
if ( $arg_help || $arg_h )
{
print_help_text();
return EXIT_CODE_SUCCESS;
}
if ( $arg_help_pod )
{
write_stdout( "This file is written in Perl's Plain Old Documentation (POD) format\n" );
write_stdout( "and has been generated with option --help-pod .\n" );
write_stdout( "Run the following Perl commands to convert it to HTML or to plain text for easy reading:\n" );
write_stdout( "\n" );
write_stdout( " pod2html README.pod >README.html\n" );
write_stdout( " pod2text README.pod >README.txt\n" );
write_stdout( "\n\n" );
write_stdout( get_pod_from_this_script() );
write_stdout( "\n" );
return EXIT_CODE_SUCCESS;
}
if ( $arg_version )
{
write_stdout( "RotateDir version " . SCRIPT_VERSION . "\n" );
return EXIT_CODE_SUCCESS;
}
if ( $arg_license )
{
write_stdout( get_license_text() );
return EXIT_CODE_SUCCESS;
}
if ( $arg_self_test )
{
write_stdout( "Running the self-tests...\n" );
self_test();
write_stdout( "\nSelf-tests finished.\n" );
exit EXIT_CODE_SUCCESS;
}
if ( $arg_noSlotDeletion && ( defined( $arg_slotCount ) || $arg_noSlotCreation || defined( $arg_deletionDelay ) ) )
{
die "Option --no-slot-deletion is incompatible with options --slot-count, --no-slot-creation and --deletion-delay .\n";
}
if ( $arg_noSlotCreation && $arg_outputOnlyNewDir )
{
die "Option --no-slot-creation is incompatible with option --output-only-new-dir-name.\n";
}
if ( not defined $arg_slotCount )
{
$arg_slotCount = 3; # Default value.
}
if ( has_non_digits( $arg_slotCount ) )
{
die qq<Invalid slot count "$arg_slotCount".\n>;
}
if ( not defined $arg_deletionDelay )
{
$arg_deletionDelay = 5; # Default value.
}
if ( has_non_digits( $arg_deletionDelay ) )
{
die qq<Invalid deletion delay "$arg_deletionDelay".\n>;
}
if ( $arg_slotCount < 1 )
{
die "The slot count must be at least 1.\n";
}
if ( $arg_dirNamingScheme ne NS_SEQUENCE and
$arg_dirNamingScheme ne NS_DATE )
{
die qq<Invalid naming scheme "$arg_dirNamingScheme".\n>;
}
if ( defined( $arg_timestamp ) )
{
if ( $arg_dirNamingScheme ne NS_DATE )
{
die "Option --timestamp is only allowed together with a timestamp-based naming scheme.\n";
}
if ( $arg_noSlotCreation )
{
die "Option --timestamp is incompatible with option --no-slot-creation.\n";
}
}
if ( 1 != scalar @ARGV )
{
die "Invalid number of arguments. Run this tool with the --help option for usage information.\n";
}
my $baseDir = shift @ARGV;
my @allSlots = scan_slots( $baseDir, $arg_dirNamePrefix );
my $newSlotName;
if ( $arg_dirNamingScheme eq NS_SEQUENCE )
{
$newSlotName = process_sequence_slots( \@allSlots );
}
elsif ( $arg_dirNamingScheme eq NS_DATE )
{
if ( $arg_noSlotCreation )
{
process_timestamp_slots( \@allSlots, undef );
$newSlotName = undef;
}
else
{
my $nextTimestamp = get_next_timestamp( $arg_timestamp );
$newSlotName = process_timestamp_slots( \@allSlots, $nextTimestamp );
}
}
else
{
# This should have been checked before.
die qq<Invalid naming scheme "$arg_dirNamingScheme".\n>;
}
if ( not $arg_noSlotDeletion )
{
delete_old_slots( \@allSlots,
$arg_slotCount,
$arg_outputOnlyNewDir,
$arg_deletionDelay );
}
if ( not $arg_noSlotCreation )
{
my $newSubdirname = $arg_dirNamePrefix . $newSlotName;
if ( defined( $arg_dirNameSuffix ) )
{
$newSubdirname .= "-" . $arg_dirNameSuffix;
}
create_new_slot( $baseDir,
$newSubdirname,
$arg_outputOnlyNewDir );
}
return EXIT_CODE_SUCCESS;
}
sub replace_script_specific_help_placeholders ( $ )
{
my $podAsStr = shift;
$podAsStr =~ s/OPT_NAME_SELF_TEST/@{[ OPT_NAME_SELF_TEST ]}/gs;
return $podAsStr;
}
sub self_test ()
{
self_test_parse_timestamp();
}
sub scan_slots ( $ $ )
{
my $baseDir = shift;
my $prefix = shift;
validate_dir_name_prefix( $prefix );
if ( not -d $baseDir )
{
die qq<The containing directory "$baseDir" does not exist.\n>;
}
my $globPattern = cat_path( $baseDir, "$prefix*" );
my @matchedDirs = File::Glob::bsd_glob( $globPattern, &File::Glob::GLOB_ERR | &File::Glob::GLOB_NOSORT );
if ( &File::Glob::GLOB_ERROR )
{
die "Error listing existing directories: $!\n";
}
if ( FALSE )
{
write_stderr( scalar(@matchedDirs) . " matched dirs:\n" . join( "\n", @matchedDirs ) . "\n" );
}
my @allSlots;
foreach my $dirName ( @matchedDirs )
{
next if not -d $dirName;
my ( $volume, $directories, $fileName ) = File::Spec->splitpath( $dirName );
next if !str_starts_with( $fileName, $prefix );
my $afterPrefix = substr( $fileName, length $prefix );
my $slotFound = CSlotInfo->new( dirName => $dirName ,
slotSubdirName => $fileName,
afterPrefix => $afterPrefix );
if ( FALSE )
{
write_stderr( "Dirname: $dirName, slot subdir name: $fileName, after prefix: $afterPrefix\n" );
}
push @allSlots, $slotFound;
}
return @allSlots;
}
sub validate_dir_name_prefix ( $ )
{
my $prefix = shift;
# Do not allow any special bsd_glob meta characters in the directory name prefix,
# as it could be dangerous.
for ( my $i = 0; $i < length( $prefix ); ++$i )
{
my $c = substr( $prefix, $i, 1 );
if ( $c eq "\\" or
$c eq "[" or
$c eq "]" or
$c eq "{" or
$c eq "}" or
$c eq "*" or
$c eq "?" or
$c eq "~" )
{
die "Character '$c' is not allowed in directory name prefix \"$prefix\".";
}
}
}
sub process_sequence_slots ( $ )
{
my $allSlots = shift;
my $parseSeqNumRegex = "\\A"; # Start of string.
$parseSeqNumRegex .= "(\\d+)"; # Capture the sequence number.
$parseSeqNumRegex .= "([- ].*)?"; # An optional suffix that begins with a '-' or a space and extends until the end of the string.
# The suffix can be empty, but that probably does not make much sense.
# We do not actually need to capture the suffix, but I could not find a way to
# specify a non-capturing group in Perl.
$parseSeqNumRegex .= "\\z"; # End of string.
my $compiledParseSeqNumRegex = qr/$parseSeqNumRegex/as;
my $nextSequenceNumber = FIRST_SEQUENCE_SEQUENCE_NUMBER;
foreach my $slotFound ( @$allSlots )
{
my @seqNumParts = $slotFound->afterPrefix =~ m/$compiledParseSeqNumRegex/;
if ( scalar( @seqNumParts ) < 1 )
{
die "Cannot extract the slot number from directory name \"" . $slotFound->slotSubdirName . "\".\n";
}
my $sequenceNumber = $seqNumParts[ 0 ];
if ( FALSE )
{
write_stdout( "After prefix: <" . $slotFound->afterPrefix . ">\n" );
write_stdout( "Seq number : <" . $sequenceNumber . ">\n" );
}
# If the number is too big, apparently it gets internally converted to zero,
# which will make this test fail.
if ( $sequenceNumber < FIRST_SEQUENCE_SEQUENCE_NUMBER )
{
die "Invalid sequence number \"" . $sequenceNumber . "\".\n";
}
$slotFound->sequenceNumber( $sequenceNumber );
if ( $sequenceNumber >= $nextSequenceNumber )
{
$nextSequenceNumber = $sequenceNumber + 1;
check_valid_sequence_number( $nextSequenceNumber );
}
}
return "$nextSequenceNumber";
}
sub process_timestamp_slots ( $ $ )
{
my $allSlots = shift;
my $nextTimestamp = shift; # If undef, there will be no next slot.
my $nextSequenceNumber = FIRST_TIMESTAMP_SEQUENCE_NUMBER - 1;
foreach my $slotFound ( @$allSlots )
{
eval
{
parse_timestamp( $slotFound->afterPrefix, TRUE, $slotFound );
};
my $errorMessage = $@;
if ( $errorMessage )
{
die "Error extracting the timestamp from slot \"" . $slotFound->slotSubdirName . "\": $errorMessage\n";
}
if ( defined $nextTimestamp )
{
my $cmp = compare_timestamps( $slotFound, $nextTimestamp );
if ( $cmp >= 1 )
{
die "The given or current timestamp \"" .
format_timestamp( $nextTimestamp->year,
$nextTimestamp->month,
$nextTimestamp->day ) .
"\" is less than the timestamp extracted from existing slot \"" .
$slotFound->slotSubdirName . "\".\n";
}
if ( $cmp == 0 )
{
if ( $slotFound->sequenceNumber >= $nextSequenceNumber )
{
$nextSequenceNumber = $slotFound->sequenceNumber + 1;
check_valid_sequence_number( $nextSequenceNumber );
}
}
}
}
if ( defined $nextTimestamp )
{
my $suffix = $nextSequenceNumber < FIRST_TIMESTAMP_SEQUENCE_NUMBER
? ""
: SEQUENCE_NUMBER_SEPARATOR_FOR_DATES . "$nextSequenceNumber";
return format_timestamp( $nextTimestamp->year,
$nextTimestamp->month,
$nextTimestamp->day ) .
$suffix;
}
else
{
return undef;
}
}
# If the integer number overflows, we want to find out straight away.
sub check_valid_sequence_number ( $ )
{
my $val = shift;
if ( has_non_digits( "$val" ) )
{
die "Integer overflow calculating the sequence number.\n";
}
}
sub delete_old_slots ( $ $ $ )
{
my $allSlots = shift;
my $slotCount = shift;
my $outputOnlyNewDir = shift;
my $deletionDelay = shift;
my $currentSlotCount = scalar @$allSlots;
if ( FALSE )
{
write_stderr( $currentSlotCount . " slots:\n" . join( "\n", @$allSlots ) . "\n" );
}
return if ( $currentSlotCount < $slotCount );
my @toDelete = sort compare_slots @$allSlots;
# Shorten the array, leave only the slots to delete.
$#toDelete -= $slotCount - 1;
foreach my $del ( @toDelete )
{
if ( !$outputOnlyNewDir )
{
write_stdout( "Deleting old slot \"" . $del->slotSubdirName . "\" ... ");
}
# Under Linux, rmtree has the bad habit of printing error messages to stderr
# when it cannot delete a directory due to insufficient permissions.
# If we don't flush stdout at this point, the error message may
# come before the progress message.
flush_stdout();
delete_folder( $del->dirName, FALSE, $deletionDelay );
if ( !$outputOnlyNewDir )
{
write_stdout( "\n" );
}
}
}
sub create_new_slot ( $ $ $ )
{
my $baseDir = shift;
my $newSubdirName = shift;
my $outputOnlyNewDir = shift;
if ( ! $outputOnlyNewDir )
{
write_stdout( "Creating new slot \"" . $newSubdirName . "\" ... " );
}
my $fullpath = cat_path( $baseDir, $newSubdirName );
if ( -e $fullpath )
{
die "Unexpected error: filename \"$fullpath\" already exists.\n";
}
mkdir( $fullpath ) or
die "Error creating directory \"$fullpath\": $!\n";
if ( ! $outputOnlyNewDir )
{
write_stdout( "\n" );
}
if ( $outputOnlyNewDir )
{
write_stdout( $fullpath . "\n" );
}
}
sub format_timestamp ( $ $ $ )
{
my $year = shift;
my $month = shift;
my $day = shift;
return sprintf( "%04d" . DATE_SEPARATOR . "%02d" . DATE_SEPARATOR . "%02d",
$year,
$month,
$day );
}
sub get_next_timestamp ( $ )
{
my $timestampStr = shift;
my $nextTimestamp = CSlotInfo->new();
if ( defined $timestampStr )
{
eval
{
parse_timestamp( $timestampStr, FALSE, $nextTimestamp );
};
my $errorMessage = $@;
if ( $errorMessage )
{
die qq<Error parsing timestamp "$timestampStr": $errorMessage\n>;
}
}
else
{
use constant MORE_THAN_32BITS => 2247483650;
my ($sec2,$min2,$hour2,$mday2,$mon2,$year2,$wday2,$yday2,$isdst2) = localtime( MORE_THAN_32BITS );
$mon2 += 1;
$year2 += 1900;
if ( $year2 != 2041 )
{
# Fixing this script (see the error message below) is not so easy.
# There are CPAN modules that can help, but they are not available
# by default on all platforms.
die "This perl environment cannot handle dates greater than 2038. " .
"You can either fix this script or provide the current date with the --timestamp option.\n";
}
eval
{
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( time() );
$mon += 1;
$year += 1900;
my $timestampStr = format_timestamp( $year, $mon, $mday );
parse_timestamp( $timestampStr, FALSE, $nextTimestamp );
};
my $errorMessage = $@;
if ( $errorMessage )
{
die qq<Error retrieving the current date: $errorMessage\n>;
}
}
return $nextTimestamp;
}
sub compare_timestamps ( $ $ )
{
my $left = shift;
my $right = shift;
if ( FALSE )
{
write_stderr( "Comparing timestamps (" .
format_timestamp( $left->year,
$left->month,
$left->day ) .
", " .
$left->sequenceNumber .
") and (" .
format_timestamp( $right->year,
$right->month,
$right->day ) .
", " .
$right->sequenceNumber .
").\n" );
}
my $yearCmp = $left->year <=> $right->year;
return $yearCmp if ( $yearCmp != 0 );
my $monthCmp = $left->month <=> $right->month;
return $monthCmp if ( $monthCmp != 0 );
return $left->day <=> $right->day;
}
# Do not add a space between or around the two $$ in the function prototype below.
# Perl version v5.22.1 on my system does not tolerate spaces there anymore.
sub compare_slots ($$)
{
if ( FALSE )
{
write_stderr( "compare_slots() received " . scalar @_ . " arguments:\n" . join( "\n", @_ ) . "\n" );
}
my $left = shift;
my $right = shift;
if ( FALSE )
{
write_stderr( "Comparing slots \"$left->dirname\" and \"$right->dirname\".\n" );
}
if ( defined( $left->year ) )
{
my $dateCmp = compare_timestamps( $left, $right );
return $dateCmp if ( $dateCmp != 0 );
}
my $result = $left->sequenceNumber <=> $right->sequenceNumber;
if ( $result == 0 )
{
my $errMsg = "Duplicate sequence number " . $left->sequenceNumber . " in " .
format_str_for_message( $left ->slotSubdirName ) . " and " .
format_str_for_message( $right->slotSubdirName ) . ".";
if ( $left->sequenceNumber eq FIRST_TIMESTAMP_SEQUENCE_NUMBER - 1 )
{
$errMsg .= " Are the directory names using the old separator ('@{[ SEQUENCE_NUMBER_SEPARATOR_FOR_DATES_OLD ]}') " .
"instead of ('@{[ SEQUENCE_NUMBER_SEPARATOR_FOR_DATES ]}') for the sequence number?";
}
die $errMsg . "\n";
}
return $result;
}
my $timestampRegex = "\\A"; # Start of string.
$timestampRegex .= "(\\d+)"; # Match the year as a number.
$timestampRegex .= DATE_SEPARATOR;
$timestampRegex .= "(\\d+)"; # Match the month as a number.
$timestampRegex .= DATE_SEPARATOR;
$timestampRegex .= "(\\d+)"; # Match the day as a number.
$timestampRegex .= "(" . SEQUENCE_NUMBER_SEPARATOR_FOR_DATES . "\\d+" . ")?"; # An optional sequence number.