-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtsmdeleter.pl
executable file
·504 lines (425 loc) · 12.9 KB
/
tsmdeleter.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
#!/usr/bin/perl
# ENDIT - Efficient Northern Dcache Interface to TSM
# Copyright (C) 2006-2017 Mattias Wadenstein <maswan@hpc2n.umu.se>
# Copyright (C) 2018-2023 <Niklas.Edmundsson@hpc2n.umu.se>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
use warnings;
use strict;
use POSIX qw(strftime);
use File::Temp qw /tempfile/;
use File::Basename;
use JSON;
use JSON::XS;
# Be flexible in handling Schedule::Cron presence.
my $have_schedule_cron = eval
{
# Silence errors
local $SIG{__WARN__} = sub {};
local $SIG{__DIE__} = sub {};
# use is really the same as require+import
require Schedule::Cron;
Schedule::Cron->import();
1;
};
# Add directory of script to module search path
use lib dirname (__FILE__);
use Endit qw(%conf readconf printlog readconfoverride getgitversiontag);
###########
# Variables
$Endit::logname = 'tsmdeleter';
my $filelist = "tsm-delete-files.XXXXXX";
my $dounlink = 1;
my $dsmcpid;
my $needretry = 0;
my $flushqueue = 0;
# deleter_queueprocinterval shortcut mappings
# crontab-style requires Schedule::Cron
my %text2cron = (
minutely =>'* * * * *',
hourly => '0 * * * *',
daily => '0 0 * * *',
weekly => '0 0 * * 1',
monthly => '0 0 1 * *',
);
# fallback triggers when strftime() output changes
my %text2fmt = (
minutely =>'%M',
hourly => '%H',
daily => '%d',
weekly => '%V',
monthly => '%m',
);
##################
# Helper functions
sub killchild() {
if(defined($dsmcpid)) {
# IBM actually recommends using KILL to avoid core dumps due to
# signal handling issues wrt multi-threading.
# See https://www.ibm.com/docs/en/storage-protect/8.1.20?topic=started-ending-session
kill("KILL", $dsmcpid);
}
}
# Performs dsmc delete of files in the specifiled filelist.
# Returns: undef on success
# Listref of 0 or more successful deletions on (partial) failure
sub rundelete {
my ($filelist) = @_;
my($out, $err);
my @dsmcopts = split(/, /, $conf{'dsmc_displayopts'});
push @dsmcopts, split(/, /, $conf{'dsmcopts'});
my @cmd = ('dsmc','delete','archive','-noprompt',
@dsmcopts,"-filelist=$filelist");
my $cmdstr = "ulimit -t $conf{dsmc_cpulimit} ; ";
$cmdstr .= "exec '" . join("' '", @cmd) . "' 2>&1";
printlog "Executing: $cmdstr" if($conf{debug});
my $dsmcfh;
my @errmsgs;
my @out;
if($dsmcpid = open($dsmcfh, "-|", $cmdstr)) {
while(<$dsmcfh>) {
chomp;
# Catch error messages.
if(/^AN\w\d\d\d\d\w/) {
push @errmsgs, $_;
}
# Save all output
push @out, $_;
}
}
if(!close($dsmcfh) && $!) {
warn "closing pipe from dsmc: $!";
}
$dsmcpid = undef;
if($? != 0) {
my $reallybroken=0;
my @deleted = ();
# Some kind of problem occurred. The dsmc return code
# is just mapped to the class of the error message, so
# we need to investigate the actual messages.
# Ignore known benign messages:
# - ANS1278W Virtual mount point 'filespace-name' is a file
# system. It will be backed up as a file system.
# => benign config warning, you have a redundant
# VIRTUALMOUNTPOINT entry in your dsm.sys.
# - ANS1898I ***** Processed count files *****
# => progress information
# These errors gives information when some/all files
# have already been deleted:
# - ANS1345E No objects on the server match object-name
# => file already deleted
# - ANS1302E No objects on server match query
# => all files already deleted
# FIXME: We only have positive feedback on files that are
# already deleted (ie nonexistant on server). We could
# check if the summary reported by dsmc adds up to our
# deletion file counts, ie dsmc output:
# Total number of objects deleted: 2
# Total number of objects failed: 4
foreach (@errmsgs) {
if(/^ANS1278W/ or /^ANS1898I/) {
next;
}
elsif(/^ANS1302E/) {
printlog "All files already deleted: $_" if $conf{'verbose'};
}
elsif(/^ANS1345E.*'(.*)'$/) {
my $s = $1;
$s =~ s _^.*/__;
push @deleted, $s;
printlog "File already deleted: $s" if $conf{'verbose'};
}
elsif(/^ANS1345E/) {
# Catch if we fail to parse partial deletion
warn "Failed to parse: $_";
}
else {
$reallybroken=1;
}
}
if($reallybroken) {
# something went wrong. log and hope for better luck next time?
my $msg = "dsmc delete failure: ";
if ($? == -1) {
$msg .= "failed to execute: $!";
}
elsif ($? & 127) {
$msg .= sprintf "died with signal %d, %s coredump", ($? & 127), ($? & 128) ? 'with' : 'without';
}
else {
$msg .= sprintf "exited with value %d", $? >> 8;
}
printlog "$msg";
if($conf{verbose}) {
printlog "dsmc output: " . join("\n", @out);
}
else {
# At a minimum, log the errors!
printlog "dsmc errors: " . join("\n", @errmsgs);
}
# Return successful deletions, if any.
return \@deleted;
}
}
return undef; # Success!
}
# Add deletion requests to our queue, removing the request files which
# signals the deletion as handled to the dCache ENDIT plugin.
sub addtoqueue
{
my @files = @_;
my $fn;
do {
# Might have a corner case with a tight loop causing a file
# collision, so just handle that.
my $now = time();
$fn = "$conf{dir_queue}/$now";
sleep(1) if(-f $fn);
} while(-f $fn);
open(my $fh, ">", $fn) or die "Failed to open $fn for writing: $!";
print $fh encode_json(\@files),"\n";
close($fh) or die "Failed closing $fn: $!";
my $debugdir = "$conf{dir_trash}/debug";
if($conf{debug}) {
if(! -d $debugdir && !mkdir($debugdir)) {
die "mkdir $debugdir: $!";
}
}
foreach my $f (@files) {
next unless(-f "$conf{dir_trash}/$f"); # Skip already deleted files
if($conf{debug}) {
rename("$conf{dir_trash}/$f", "$debugdir/$f") or warn "Failed to move $f to $debugdir/ : $!";
}
else {
if(!unlink("$conf{dir_trash}/$f")) {
printlog "unlink '$conf{dir_trash}/$f' failed: $!";
}
}
}
my $logstr = "Queued " . scalar(@files) . " files for deletion";
if($conf{verbose}) {
$logstr .= " (files: " . join(" ", @files) . ")";
}
printlog $logstr;
}
# Check trash directory and add deletion requests to queue.
sub checktrashdir
{
opendir(my $td, $conf{dir_trash}) || die "opendir $conf{dir_trash}: $!";
my @files = grep { /^[0-9A-Fa-f]+$/ } readdir($td);
closedir($td);
if (@files > 0) {
addtoqueue(@files);
}
}
# Process the queue of pending deletions.
sub processqueue
{
printlog "Processing deletion queue start" if($conf{debug});
opendir(my $td, $conf{dir_queue}) || die "opendir $conf{dir_queue}: $!";
my @qfiles = grep { /^[0-9]+$/ } readdir($td);
closedir($td);
my @files;
foreach my $qf (@qfiles) {
local $/; # slurp whole file
my $qfd;
if(!open $qfd, '<', "$conf{dir_queue}/$qf") {
warn "Opening $conf{dir_queue}/$qf: $!";
next;
}
my $json_text = <$qfd>;
my $qentries = decode_json($json_text);
close $qfd;
push @files, @{$qentries};
if($conf{debug}) {
printlog "Read " . scalar(@{$qentries}) . " entries from $conf{dir_queue}/$qf";
}
}
printlog scalar(@files) . " files in deletion queue" if($conf{verbose});
# Do deletions and update @files to reflect files left to delete
if(@files) {
my ($fh, $filename) = eval { tempfile($filelist, DIR=>"$conf{dir_requestlists}", UNLINK=>$dounlink); };
if(!$fh) {
warn "Failed opening filelist: $@";
return 0;
}
print $fh map { "$conf{dir_out}/$_\n"; } @files;
if(!close($fh)) {
warn "Failed writing to $filename: $!";
if(!unlink($filename)) {
printlog "unlink '$filename' failed: $!";
}
return 0;
}
my $logstr = "Trying to delete " . scalar(@files) . " files";
if($conf{debug}) {
$logstr .= " using file list $filename";
}
if($conf{verbose}) {
$logstr .= " (files: " . join(" ", @files) . ")";
}
printlog $logstr;
my $partial = rundelete($filename);
if(!defined($partial)) {
# Success!
printlog "Successfully deleted " . scalar(@files) . " files";
@files = ();
}
elsif(@{$partial}) {
printlog "Partial success, deleted " . scalar(@{$partial}) . " of " . scalar(@files) . " files";
# Filter out the partial successes from @files
my %f;
@f{ @files } = ();
delete @f{ @{$partial} };
@files = keys %f;
}
if(!$conf{debug}) {
if(!unlink($filename)) {
printlog "unlink '$filename' failed: $!";
}
}
}
$needretry = scalar(@files);
# Add files that failed to delete back into queue
if(@files) {
addtoqueue(@files); # Will die() on error
}
# Remove old queue files
foreach my $qf (@qfiles) {
if(!unlink("$conf{dir_queue}/$qf")) {
printlog "unlink '$conf{dir_queue}/$qf' failed: $!";
}
}
printlog "Processing deletion queue done" if($conf{debug});
return 0;
}
# sleep-hook for Schedule::Cron, sleeps at most $conf{sleeptime} seconds
# at a time.
# We use this to drive our main loop iteration, both when using
# Schedule::Cron and the while-loop fallback.
sub cronsleep
{
my ($time, $cron) = @_;
# Perform these actions on each iteration.
readconfoverride('deleter');
checktrashdir();
if($flushqueue) {
printlog "Flushing deletion queue as instructed by USR1 signal";
$flushqueue = 0;
processqueue();
}
elsif($needretry) {
processqueue();
}
# Don't sleep longer than our configured sleeptime.
if($time > $conf{sleeptime}) {
$time = $conf{sleeptime};
}
printlog "cronsleep() for $time seconds" if($conf{debug});
sleep($time);
return;
}
#################
# Implicit main()
# Try to send warn/die messages to log file, this is run just before the Perl
# runtime begins execution.
INIT {
$SIG{__DIE__}=sub {
printlog("DIE: $_[0]");
};
$SIG{__WARN__}=sub {
print STDERR "$_[0]";
printlog("WARN: $_[0]");
};
}
# Turn off output buffering
$| = 1;
readconf();
$dounlink=0 if($conf{debug});
chdir('/') || die "chdir /: $!";
$SIG{INT} = sub { warn("Got SIGINT, exiting...\n"); killchild(); exit; };
$SIG{QUIT} = sub { warn("Got SIGQUIT, exiting...\n"); killchild(); exit; };
$SIG{TERM} = sub { warn("Got SIGTERM, exiting...\n"); killchild(); exit; };
$SIG{HUP} = sub { warn("Got SIGHUP, exiting...\n"); killchild(); exit; };
$SIG{USR1} = sub { $flushqueue = 1; };
my $desclong="";
if($conf{'desc-long'}) {
$desclong = " $conf{'desc-long'}";
}
my $verstr = "";
my $vertag = getgitversiontag();
if($vertag) {
$verstr = " version $vertag";
}
printlog("$0$verstr: Starting$desclong...");
# Basic sanity-checking of deleter_queueprocinterval argument
my $crontime;
if($conf{deleter_queueprocinterval} =~ /\s/) {
if(scalar(split/\s+/, $conf{deleter_queueprocinterval}) eq 5) {
$crontime = $conf{deleter_queueprocinterval};
}
}
elsif($text2cron{$conf{deleter_queueprocinterval}}) {
$crontime = $text2cron{$conf{deleter_queueprocinterval}};
}
if(!$crontime) {
die "Bad config: deleter_queueprocinterval: $conf{deleter_queueprocinterval}";
}
my $skew = int(rand(60)); # Avoid executing exactly at second 0
if($have_schedule_cron) {
my $cron = new Schedule::Cron( \&processqueue,
{ sleep => \&cronsleep, nofork => 1, nostatus => 1 } );
# Strip quotes in case someone has been ambitious in the config
$crontime =~ s/^"//;
$crontime =~ s/"$//;
# Schedule::Cron has a 6th field for seconds, use this to avoid
# executing exactly at second 0.
$crontime .= " $skew";
printlog "Scheduling queue processing using $crontime" if($conf{debug});
my $next;
# Catch bad entries to give sane error message
eval {
$cron->add_entry($crontime);
$next = $cron->get_next_execution_time($crontime);
};
if($@) {
die "Bad config: deleter_queueprocinterval: $conf{deleter_queueprocinterval}";
}
if($conf{debug} || ($conf{verbose} && $next - time() > 3600)) {
printlog "Next deletion queue processing at " . scalar(localtime($next));
}
# Start scheduler and wait forever.
# Queueing of incoming requests and other housekeeping is done in
# cronsleep()
$cron->run();
}
else {
my $fmt = $text2fmt{$conf{deleter_queueprocinterval}};
if(!$fmt) {
warn "crontab style timespec requires Perl module Schedule::Cron";
die "Unable to handle deleter_queueprocinterval: $conf{deleter_queueprocinterval}";
}
my $t = strftime($fmt, localtime(time()-$skew));
# Fallback to while-loop if no scheduler
while(1) {
# Queueing of incoming requests and other housekeeping is done
# in cronsleep()
cronsleep $conf{sleeptime};
# Trigger queue processing when output from strftime() changes
if($t ne strftime($fmt, localtime(time()-$skew))) {
$t = strftime($fmt, localtime());
processqueue();
}
}
}