This file is indexed.

/usr/lib/arc/cache-clean is in nordugrid-arc-arex 1.1.1-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/perl -w

#
#    Copyright 2008 Niklas Edmundsson <nikke@acc.umu.se>,
#                   Tomas Ögren <stric@acc.umu.se>,
#                   David Cameron <cameron@ndgf.org>
#
#    Originally developed by Niklas Edmundsson and Tomas Ögren as
#    cleanbyage. Modified, renamed cache-clean and maintained
#    for ARC by David Cameron.
#
#    Released under Apache License Version 2.0
#

use Sys::Hostname;
use File::Find ();
use File::Path;
use Getopt::Std;
use Fcntl ':mode';
use DirHandle;
use File::Basename;

use strict;
use warnings;


BEGIN {
    unshift @INC, dirname($0).'/../../share/arc';
}

use ConfigCentral;

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

sub wanted;
sub debug;
sub printsize;
sub diskspace;

my(%opts);

my $configfile;

# Min free percentage
my $minfree = 0;
my $mincleanfree = 0;
my $expirytime = 0;

my %files;
my %expiredfiles;
my $totsize = 0;
my $totlocksize = 0;
my $totlockfiles = 0;

my $debuglevel = 'INFO';
LogUtils::level($debuglevel);
LogUtils::timestamps(1);
my $log = LogUtils->getLogger('cache-clean');

my $currenttime = time();

getopts('hsc:m:M:E:D:', \%opts);

if(defined($opts{c})) {
    $configfile = $opts{c};
}
if(defined($opts{m})) {
    $minfree = $opts{m};
}
if(defined($opts{M})) {
    $mincleanfree = $opts{M};
}
if(defined($opts{D})) {
    $debuglevel = $opts{D};
    LogUtils::level($debuglevel);
}
if(defined($opts{s})) {
    $debuglevel = 'ERROR';
    LogUtils::level($debuglevel);
}

if($minfree < 0 || $minfree > 100) {
    die "Bad value for -m: $minfree\n";
}
if($mincleanfree < 0 || $mincleanfree > 100) {
    die "Bad value for -M: $mincleanfree\n";
}
if($mincleanfree < $minfree) {
    die "-M can't be smaller than -m (now $mincleanfree/$minfree)\n";
}

if(defined($opts{E})) {
    if ($opts{E} =~ m/^(\d+)(\D)$/) {
        if ($2 eq 'd') {
        $expirytime = $1 * 86400;
        } elsif ($2 eq 'h') {
            $expirytime = $1 * 3600;
        } elsif ($2 eq 'm') {
            $expirytime = $1 * 60;
        } elsif ($2 eq 's') {
            $expirytime = $1;
        } else {
            die "Bad format in -E option value\n";
        }
    } elsif ($opts{E} =~ m/^\d+$/) {
        $expirytime = $opts{E};
    } else {
        die "Bad format in -E option value\n";
    }
}

sub usage {
    print <<EOH;
   usage: cache-clean [-h] [-s] [-m <NN> -M <NN>] [-E N] [-D debug_level]
            [ -c <arex_config_file> | <dir1> [<dir2> [...]] ]
    -h       - This help
    -s       - Statistics mode, show cache usage stats, dont delete anything
    -c       - path to an A-REX config file, xml or ini format
    -m NN    - Min free space to start cleaning (percent)
    -M NN    - Free space to stop cleaning (percent)
    -E N     - Delete all files whose access time is older than N. Examples
                 of N are 1800, 90s, 24h, 30d (default is seconds)
    -D level - Debug level, FATAL, ERROR, WARNING, INFO, VERBOSE or DEBUG.
                 Default is INFO

   Caches are given by dir1, dir2.. or taken from the config file specified
   by -c or ARC_CONFIG

EOH
    exit 1;
}

usage() if(defined($opts{'h'}) || ((!defined($opts{'M'}) || !defined($opts{'m'})) && !defined($opts{'E'}) && !defined($opts{'s'})));

if (!$configfile && $ENV{'ARC_CONFIG'} && -e $ENV{'ARC_CONFIG'}) {
    $configfile = $ENV{'ARC_CONFIG'};
}

$log->info('Cache cleaning started');

my @caches = @ARGV;

if (!@caches) {
    die "No config file found and no caches specified\n" unless $configfile;
    my $config = ConfigCentral::parseConfig($configfile);
    die "Failed parsing A-REX config file '$configfile'\n" unless $config;
    die "No users set up in config file '$configfile'\n"
        unless $config->{control} and ref $config->{control} eq 'HASH';
    for my $control (values %{$config->{control}}) {
        next unless ref $control eq 'HASH';
        next unless $control->{cachedir} and ref $control->{cachedir} eq 'ARRAY';
        for (@{$control->{cachedir}}) {
            $log->warning("\n Warning: cache-clean cannot deal with substitutions - $_") and next if /%/;
            $log->warning("\n Warning: ignoring malformed cahe location - $_\n") and next unless m{^(/\S+)};
            push @caches, $1;
        }
    }
    die "No caches found in config file '$configfile'\n" unless @caches;
}

# ConfigCentral sets debug level to level in conf file, so we have to reset it here
LogUtils::level($debuglevel);

foreach my $filesystem (@caches) {

    $filesystem =~ s|/+$|| unless $filesystem eq "/";
    next if $filesystem eq "";

    if ($filesystem =~ /%/) {
        $log->warning("$filesystem: Warning: cache-clean cannot deal with substitutions");
        next;
    }

    if (! -d $filesystem || ! -d $filesystem."/data") {
        $log->info("$filesystem: Cache is empty");
        next;
    }

    # follow sym links to real filesystem
    my $symlinkdest = $filesystem;
    while ($symlinkdest) {
        $filesystem = $symlinkdest;
        $symlinkdest = readlink($symlinkdest);
        $symlinkdest =~ s|/+$|| if $symlinkdest;
    }

    my $fsvalues = diskspace($filesystem);

    if(!($fsvalues)) {
        $log->warning("Unable to stat $filesystem");
        next;
    }

    my $fssize = $fsvalues->{total};
    my $fsfree = $fsvalues->{free};

    my $maxfbytes=$fssize*$minfree/100;
    $log->info(join("", "$filesystem: used space ", printsize($fssize-$fsfree), " / ", printsize($fssize), " (", sprintf("%.2f",100-100*$fsfree/$fssize), "%)"));
    if ($expirytime == 0 && $fsfree > $maxfbytes && !$opts{'s'}) {
        $log->info(join("", "Used space is lower than upper limit (", 100-$minfree, "%)"));
        next;
    }

    my $minfbytes=$fssize*$mincleanfree/100;
    
    %files = ();
    %expiredfiles = ();
    $totsize = 0;
    $totlocksize = 0;
    $totlockfiles = 0;

    File::Find::find({wanted => \&wanted}, $filesystem."/data");

    if($opts{'s'}) {
    my %allfiles = (%files, %expiredfiles);
        print "\nUsage statistics: $filesystem\n";
        print "Total deletable files found: ",scalar keys %allfiles," ($totlockfiles files locked or in use)\n";
        print "Total size of deletable files found: ",printsize($totsize)," (",printsize($totlocksize)," locked or in use)\n";
        print "Used space on file system: ",printsize($fssize-$fsfree)," / ",printsize($fssize), " (",sprintf("%.2f",100-100*$fsfree/$fssize),"%)\n";
        my $increment = $totsize / 10;
        if($increment < 1) {
            print "Total size too small to show usage histogram\n";
            next;
        }

        printf "%-21s %-25s %s\n", "At size (% of total)", "Newest file", "Oldest file";
        my $nextinc = $increment;
        my $accumulated = 0;
        my ($newatime, $lastatime);

        foreach my $fil (sort { $allfiles{$b}{atime} <=> $allfiles{$a}{atime} } 
              keys %allfiles) {
            $accumulated += $allfiles{$fil}{size};
            if(!$newatime) {
                $newatime = $allfiles{$fil}{atime};
            }

            if($accumulated > $nextinc) {
                printf "%-21s %-25s %s\n", 
                printsize($accumulated)." (".int(($accumulated/$totsize)*100)."%)",
                scalar localtime($newatime),
                scalar localtime($allfiles{$fil}{atime});
                while($nextinc < $accumulated) {
                    $nextinc += $increment;
                }
                $newatime = undef;
                $lastatime = undef;
            }
            else {
                $lastatime = $allfiles{$fil}{atime};
            }
        }
        printf "%-21s %-25s %s\n", 
        printsize($accumulated)." (100%)", "-",
        scalar localtime($lastatime) if($lastatime);
        next;
    }

    # remove expired files
    if ($expirytime > 0) {
        foreach my $fil (keys %expiredfiles) {
            next if (-d "$fil");
            if (-e "$fil.lock") {
                my $atime = (stat("$fil.lock"))[8];
                next if ( defined $atime && ($currenttime - $atime) <= 86400);
                unlink "$fil.lock";
            }

            if ( unlink $fil ) {
                $fsfree+=$expiredfiles{$fil}{size};
                if (defined($opts{'D'}) && -e "$fil.meta") {
                    open FILE, "$fil.meta";
                    my @lines = <FILE>;
                    close FILE;
                    my @values = split(' ', $lines[0]);
                    $log->verbose(join("", "Deleting expired file: $fil  atime: ", scalar localtime($expiredfiles{$fil}{atime}), "  size: $expiredfiles{$fil}{size}  url: $values[0]"));
                }
                else {
                    $log->verbose(join("", "Deleting expired file: $fil  atime: ", scalar localtime($expiredfiles{$fil}{atime}), "  size: $expiredfiles{$fil}{size}"));
                }
            } else {
                $log->warning("Error deleting file '$fil': $!");
            }

            # not critical if this fails
            next if (! -e "$fil.meta");
            if ( unlink "$fil.meta" ) {
                my $lastslash = rindex($fil, "/");
                if ( rmdir(substr($fil, 0, $lastslash))) {
                     $log->verbose("Deleting directory ".substr($fil, 0, $lastslash));
                }
            } else {
                $log->warning("Error deleting file '$fil.meta': $!");
            } 
        }
    }

    if ($fsfree < $maxfbytes) {
        # delete in order of access
        foreach my $fil (sort { $files{$a}{atime} <=> $files{$b}{atime} } keys %files) {
            last if $fsfree > $minfbytes;
            next if (-d "$fil");
            if (-e "$fil.lock") {
                my $atime = (stat("$fil.lock"))[8];
                next if ( defined $atime && ($currenttime - $atime) <= 86400);
                unlink "$fil.lock"
            }

            if ( unlink $fil ) {
                $fsfree+=$files{$fil}{size};
                if (defined($opts{'D'}) && -e "$fil.meta") {
                    open FILE, "$fil.meta";
                    my $line = <FILE>;
                    close FILE;
                    chomp($line);
                    $log->verbose(join("", "Deleting file: $fil  atime: ", scalar localtime($files{$fil}{atime}), "  size: $files{$fil}{size}  url: $line"));
                }
                else {
                    $log->verbose(join("","Deleting file: $fil  atime: ", scalar localtime($files{$fil}{atime}), "  size: $files{$fil}{size}"));
                }
            } else {
                $log->warning("Error deleting file '$fil': $!");
            }
            next if (! -e "$fil.meta");
            # not critical if this fails
            if ( unlink "$fil.meta" ) {
                my $lastslash = rindex($fil, "/");
                if ( rmdir(substr($fil, 0, $lastslash))) {
                    $log->verbose("Deleting directory ".substr($fil, 0, $lastslash));
                }
            } else {
                $log->warning("Error deleting file '$fil.meta': $!");
            } 
        }
    }
    $log->info(join("", "Cleaning finished, used space now ", printsize($fssize-$fsfree), " / ", printsize($fssize), " (", sprintf("%.2f",100-100*$fsfree/$fssize),"%)"));
}
exit 0;

sub wanted {

    return if $name =~ m|\.lock$|;
    return if $name =~ m|\.meta$|;

    my ($links, $atime, $blocks);

    ($links, $atime, $blocks) = (lstat($_))[3,8,12];

    return unless defined $atime;

    return unless !(-d _) || -f _;
       
    if ($links != 1) {
        $totlocksize += 512 * $blocks;
        $totlockfiles++;
        return;
    }
    
    if (-e "$name.lock") {
        # check if lock is still valid
        my $lockatime = (stat("$name.lock"))[8];
        if ( defined $lockatime && ($currenttime - $lockatime) <= 86400) {
            $totlocksize += 512 * $blocks;
            $totlockfiles++;
            return;
        }
    }

    if ($expirytime > 0 && ($currenttime - $atime) >= $expirytime) {
        $expiredfiles{$name}{atime}=$atime;
        $expiredfiles{$name}{size}= 512 * $blocks;
    }
    else {
        $files{$name}{atime}=$atime;
        $files{$name}{size}= 512 * $blocks;
    }
    $totsize += 512 * $blocks;
}

sub printsize($)
{
    my $size = shift;

    if($size > 1024*1024*1024*1024) {
        $size = int($size/(1024*1024*1024*1024));
        return "$size TB";
    }
    if($size > 1024*1024*1024) {
        $size = int($size/(1024*1024*1024));
        return "$size GB";
    }
    if($size > 1024*1024) {
        $size = int($size/(1024*1024));
        return "$size MB";
    }
    if($size > 1024) {
        $size = int($size/1024);
        return "$size kB";
    }

    return $size;
}

#
# Returns disk space (total and free) in bytes on a filesystem
# Taken from arc1/trunk/src/services/a-rex/infoproviders/HostInfo.pm
# TODO: Put in common place
#
sub diskspace ($) {
    my $path = shift;
    my ($diskfree, $disktotal);

    if ( -d "$path") {
        # check if on afs
        if ($path =~ m#/afs/#) {
            my @dfstring =`fs listquota $path 2>/dev/null`;
            if ($? != 0) {
                $log->warning("Failed running: fs listquota $path");
            } elsif ($dfstring[-1] =~ /\s+(\d+)\s+(\d+)\s+\d+%\s+\d+%/) {
                $disktotal = int $1/1024;
                $diskfree  = int(($1 - $2)/1024);
            } else {
                $log->warning("Failed interpreting output of: fs listquota $path");
            }
        # "ordinary" disk
        } else {
            my @dfstring =`df -k $path 2>/dev/null`;
            if ($? != 0) {
                $log->warning("Failed running: df -k $path");

            # The first column may be printed on a separate line.
            # The relevant numbers are always on the last line.
            } elsif ($dfstring[-1] =~ /\s+(\d+)\s+\d+\s+(\d+)\s+\d+%\s+\//) {
                $disktotal = $1*1024;
                $diskfree  = $2*1024;
            } else {
                $log->warning("Failed interpreting output of: df -k $path");
            }
        }
    } else {
        $log->warning("Not a directory: $path");
    }

    return undef unless defined($disktotal) and defined($diskfree);
    return {total => $disktotal, free => $diskfree};
}