Subversion Repositories DevTools

Rev

Rev 5405 | Rev 6148 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1038 dpurdie 1
#! /usr/bin/perl
2
########################################################################
3
# Copyright (C) 2011 Vix-ERG Limited, All rights reserved
4
#
5
# Module name   : blatDaemon.pl
6
# Module type   :
7
# Compiler(s)   : Perl
8
# Environment(s):
9
#
10
# Description   :
11
#
12
# Usage         :   ARGV[0] - Path to config file for this instance
13
#
14
#......................................................................#
15
 
16
require 5.008_002;
17
use strict;
18
use warnings;
19
use Getopt::Long;
20
use File::Basename;
1040 dpurdie 21
use Data::Dumper;
22
use File::Spec::Functions;
1038 dpurdie 23
use POSIX ":sys_wait_h";
24
use File::Temp qw/tempfile/;
25
 
26
use FindBin;                                    # Determine the current directory
27
use lib "$FindBin::Bin/lib";                    # Allow local libraries
28
 
29
use Utils;
30
use StdLogger;                                  # Log to sdtout
31
use Logger;                                     # Log to file
32
 
33
#
34
#   Database interface
35
#   Pinched from jats and modified so that this software is not dependent on JATS
36
#
37
use IO::Handle;
38
use JatsRmApi;
39
use DBI;
40
 
41
#
42
#   Globals
43
#
44
my $logger = StdLogger->new();                  # Stdout logger. Only during config
45
my $name = basename( $ARGV[0]);
46
   $name =~ s~.conf$~~;
47
my $now = 0;
5398 dpurdie 48
my $startTime = 0;
3515 dpurdie 49
my $tar = 'tar';
50
my $gzip = 'gzip';
1038 dpurdie 51
my $tagDirTime = 0;
52
my $lastDirScan = 0;
53
my $lastReleaseScan = 0;
1040 dpurdie 54
my $releaseScanMode = 0;
55
my $lastTagListScan = 0;
1038 dpurdie 56
my $transferred;
57
my $mtimeConfig = 0;
58
my $conf;
59
my $extraPkgs;
1040 dpurdie 60
my $excludePkgs;
61
my %releaseData;
3515 dpurdie 62
my $comError = 0;
5398 dpurdie 63
my $yday = -1;
1038 dpurdie 64
 
65
#
5398 dpurdie 66
#   Contain statisics maintained while operating
67
#       Can be dumped with a kill -USR2
68
#       List here for documentation
69
#  
70
 
71
my %statistics = (
72
    SeqNum => 0,                        # Bumped when $statistics are dumped
73
    timeStamp => 0,                     # DateTime when statistics are dumped
74
    upTime => 0,                        # Seconds since program start
75
    Cycle => 0,                         # Major process loop counter
76
    phase => 'Init',                    # Current phase of operation
77
    state => 'OK',                      # Nagios state
78
                                        # 
79
                                        # The following are reset each day
80
    dayStart => 0,                      # DateTime when daily data was reset
81
    txCount => 0,                       # Packages Transferred
82
    delCount => 0,                      # Packages marked for deletion
83
    staleTags => 0,                     # Stale Tags
84
    linkErrors => 0,                    # Transfer errors
85
                                        # 
86
                                        # Per Cycle Data - Calculated each processing Cycle
5399 dpurdie 87
    total    => 0,                      # Packages to be synced
5398 dpurdie 88
    delete   => 0,                      # Packages to delete
89
    excluded => 0,                      # Packages excluded    
90
    filtered => 0,                      # Packages filtered out
91
    missing  => 0,                      # Packages missing
92
    transfer => 0,                      # Packages to transfer
93
    writable => 0,                      # Packages still writable - thus not transferred
94
    tagCount => 0,                      # Packages tagged to be transferred
5404 dpurdie 95
                                        #
96
                                        # Expected from the Target 
97
#   Target.Hostname => '',              # Target Hostname
98
#   Target.avail    => 0,               # Information from 'df' 1Kblocks 
99
#   Target.pcent    => 0,
100
#   Target.size     => 0,
101
#   Target.used     => 0,
102
#   Target.iavail   => 0,               # Inode information from 'df'
103
#   Target.ipcent   => 0,
104
#   Target.isize    => 0,
105
#   Target.iused    => 0,
106
#   Target.Total    => 0,               # Number of Package Versions in the archive
107
#   Target.Damaged  => 0,               # Number that are damaged
108
#   Target.Delete   => 0,               # Number marked for future deletion
109
#   Target.Missing  => 0,               # Number missing
5398 dpurdie 110
);
111
 
1038 dpurdie 112
#
5398 dpurdie 113
#   Describe configuration parameters
114
#
1038 dpurdie 115
my %cdata = (
116
    '.ignore'         => {'pkg\.(.+)' => 'pkgs' },
1048 dpurdie 117
    'piddir'          => {'mandatory' => 1      , 'fmt' => 'dir'},
118
    'sleep'           => {'default'   => 5      , 'fmt' => 'period'},
119
    'dpkg_archive'    => {'mandatory' => 1      , 'fmt' => 'dir'},
120
    'logfile'         => {'mandatory' => 1      , 'fmt' => 'vfile'},
121
    'logfile.size'    => {'default'   => '1M'   , 'fmt' => 'size'},
122
    'logfile.count'   => {'default'   => 9      , 'fmt' => 'int'},
123
    'verbose'         => {'default'   => 0      , 'fmt' => 'int'},
124
    'user'            => {'mandatory' => 1      , 'fmt' => 'text'},
125
    'hostname'        => {'mandatory' => 1      , 'fmt' => 'text'},
3847 dpurdie 126
    'sshport'         => {'default'   => 0      , 'fmt' => 'int'},
1048 dpurdie 127
    'identity'        => {'mandatory' => 1      , 'fmt' => 'file'},
128
    'bindir'          => {'mandatory' => 1      , 'fmt' => 'text'},
129
    'tagdir'          => {'mandatory' => 1      , 'fmt' => 'dir'},
130
    'forcedirscan'    => {'default'   => 100    , 'fmt' => 'period'},
131
    'tagage'          => {'default'   => '10m'  , 'fmt' => 'period'},
132
    'tagListUpdate'   => {'default'   => '1h'   , 'fmt' => 'period'},
133
    'synctime'        => {'default'   => '2h'   , 'fmt' => 'period'},
134
    'syncretry'       => {'default'   => '5m'   , 'fmt' => 'period'},
135
    'allProjects'     => {'default'   => 0      , 'fmt' => 'bool'},
4456 dpurdie 136
    'allArchive'      => {'default'   => 0      , 'fmt' => 'bool'},
1048 dpurdie 137
    'project'         => {'mandatory' => 0      , 'fmt' => 'int_list'},
138
    'release'         => {'mandatory' => 0      , 'fmt' => 'int_list'},
139
    'writewindow'     => {'default'   => '3h'   , 'fmt' => 'period'},
140
    'maxpackages'     => {'default'   => 5      , 'fmt' => 'int'},
141
    'deletePackages'  => {'default'   => 0      , 'fmt' => 'bool'},
142
    'deleteImmediate' => {'default'   => 0      , 'fmt' => 'bool'},
143
    'deleteAge'       => {'default'   => 0      , 'fmt' => 'period'},
144
    'packageFilter'   => {'default'   => undef  , 'fmt' => 'text'},
145
    'active'          => {'default'   => 1      , 'fmt' => 'bool'},
1038 dpurdie 146
);
147
 
148
 
149
#
150
#   Read in the configuration
151
#       Set up a logger
152
#       Write a pidfile - thats not used
153
readConfig();
154
Utils::writepid($conf);
155
$logger->logmsg("Starting...");
5404 dpurdie 156
readStatistics();
1038 dpurdie 157
sighandlers($conf);
5398 dpurdie 158
$startTime = time();
1038 dpurdie 159
 
160
#
161
#   Main processing loop
162
#   Will exit when terminated by parent
163
#
3847 dpurdie 164
while (1 )
1038 dpurdie 165
{
166
    $logger->verbose3("Processing");
5398 dpurdie 167
    $statistics{Cycle}++;
1038 dpurdie 168
    $now = time();
1040 dpurdie 169
 
1038 dpurdie 170
    $transferred = {};
5398 dpurdie 171
    $statistics{phase} = 'ReadConfig';
1038 dpurdie 172
    readConfig();
1048 dpurdie 173
    if ( $conf->{'active'} )
174
    {
5398 dpurdie 175
        $statistics{phase} = 'ProcessReleaseList';
1048 dpurdie 176
        processReleaseList();
5398 dpurdie 177
        $statistics{phase} = 'processTags';
1048 dpurdie 178
        processTags();
5398 dpurdie 179
        $statistics{phase} = 'maintainTagList';
1048 dpurdie 180
        maintainTagList();
181
    }
1040 dpurdie 182
    %releaseData = ();
183
 
5398 dpurdie 184
    $statistics{phase} = 'Sleep';
1038 dpurdie 185
    sleep( $conf->{'sleep'} );
1050 dpurdie 186
 
187
    #
188
    #   Reap any and all dead children
189
    #
5398 dpurdie 190
    $statistics{phase} = 'Reaping';
1050 dpurdie 191
    my $kid;
192
    do {
193
        $kid = waitpid(-1, WNOHANG);
194
    } while ( $kid > 0 );
3847 dpurdie 195
 
196
    #   If my PID file ceases to be, then exit the daemon
197
    #   Used to force daemon to restart
198
    #
199
    unless ( -f $conf->{'pidfile'} )
200
    {
201
        $logger->logmsg("Terminate. Pid file removed");
202
        last;
203
    }
1038 dpurdie 204
}
5398 dpurdie 205
$statistics{phase} = 'Terminated';
1038 dpurdie 206
$logger->logmsg("Child End");
207
exit 0;
208
 
209
#-------------------------------------------------------------------------------
210
# Function        : readConfig
211
#
212
# Description     : Re read the config file if it modification time has changed
213
#
214
# Inputs          : Nothing
215
#
1289 dpurdie 216
# Returns         : 0       - Config not read
217
#                   1       - Config read
218
#                             Config file has changed
1038 dpurdie 219
#
220
sub readConfig
221
{
222
    my ($mtime) = Utils::mtime($ARGV[0]);
1289 dpurdie 223
    my $rv = 0;
224
 
1038 dpurdie 225
    if ( $mtimeConfig != $mtime )
226
    {
227
        $logger->logmsg("Reading config file: $ARGV[0]");
228
        $mtimeConfig = $mtime;
229
        my $errors;
230
        ($conf, $errors) = Utils::readconf ( $ARGV[0], \%cdata );
231
        if ( scalar @{$errors} > 0 )
232
        {
233
            warn "$_\n" foreach (@{$errors});
234
            die ("Config contained errors\n");
235
        }
236
 
237
        #
238
        #   Reset some information
239
        #   Create a new logger
240
        #
241
        $logger = Logger->new($conf);
242
        $conf->{logger} = $logger;
243
        $conf->{'pidfile'} = $conf->{'piddir'} . '/' . $name . '.pid';
244
        $logger->verbose("Log Levl: $conf->{verbose}");
245
 
246
        #
5398 dpurdie 247
        #   Setup statistics filename
248
        $conf->{'statsfile'} = $conf->{'piddir'} . '/' . $name . '.stats';
249
        $conf->{'statsfiletmp'} = $conf->{'piddir'} . '/' . $name . '.stats.tmp';
250
 
251
        #
1038 dpurdie 252
        #   Extract extra package config
253
        #
254
        $extraPkgs = {};
1040 dpurdie 255
        $excludePkgs = {};
1038 dpurdie 256
        while (my($key, $data) = each ( %{$conf->{pkgs}} ))
257
        {
3846 dpurdie 258
            if ( $data eq 'EXCLUDE' ) {
1040 dpurdie 259
                $excludePkgs->{$key} = 1;
260
                $logger->verbose("Exclude Pkg: $key");
3846 dpurdie 261
 
262
            } elsif ( $data eq 'ALL' ) {
263
                foreach my $pver (getPackageVersions($key))
264
                {
265
                    $extraPkgs->{$key}{$pver} = 1;
266
                    $logger->verbose("Extra Pkg: $key -> $pver");
267
                }
268
            } else {
1040 dpurdie 269
                $extraPkgs->{$key}{$data} = 1;
270
                $logger->verbose("Extra Pkg: $key -> $data");
271
            }
1038 dpurdie 272
        }
1046 dpurdie 273
 
1048 dpurdie 274
        $logger->verbose("Filter Packages: " . $conf->{'packageFilter'})
275
            if ( defined $conf->{'packageFilter'} );
276
 
3847 dpurdie 277
        $logger->warn("Non standard ssh port: " . $conf->{'sshport'})
278
            if ( $conf->{'sshport'} );
279
 
1048 dpurdie 280
        $logger->warn("Transfer session configured as not active")
281
            unless ( $conf->{'active'} );
282
 
283
        $logger->warn("Transfer all projects packages")
1050 dpurdie 284
            if ( $conf->{'allProjects'} );
4456 dpurdie 285
        $logger->warn("Transfer entire package archive")
286
            if ( $conf->{'allArchive'} );
1048 dpurdie 287
 
4456 dpurdie 288
 
1046 dpurdie 289
        #
290
        #   When config is read force some actions
291
        #       - Force tagList to be created
1050 dpurdie 292
        #       - Force release scan
1048 dpurdie 293
        $lastTagListScan = 0;
1050 dpurdie 294
        $lastReleaseScan = 0;
1289 dpurdie 295
        $rv = 1;
1038 dpurdie 296
    }
1289 dpurdie 297
    return $rv;
1038 dpurdie 298
}
299
 
300
 
301
#-------------------------------------------------------------------------------
302
# Function        : processReleaseList
303
#
304
# Description     : Process the release list
305
#                       Determine if its time to process release list
306
#                       Determine release list
307
#                       Determine release content
308
#                       Determine new items
309
#
310
# Inputs          : None
311
#
312
# Returns         : Nothing
313
#
314
sub processReleaseList
315
{
316
    #
1044 dpurdie 317
    #   Is Release List Processing active
318
    #   Can configure blat to disable release sync
319
    #   This will then allow 'new' packages to be sent
320
    #
321
    if ( $conf->{maxpackages} == 0 || $conf->{'synctime'} <= 0)
322
    {
323
        $logger->verbose2("processReleaseList disabled");
324
        return;
325
    }
326
 
327
    #
1038 dpurdie 328
    #   Time to perform the scan
329
    #   Will do at startup and every time period there after
330
    #
1040 dpurdie 331
    my $wtime = $releaseScanMode ? $conf->{'syncretry'} : $conf->{'synctime'};
332
    return unless ( $now > ($lastReleaseScan + $wtime ));
1038 dpurdie 333
    $logger->verbose("processReleaseList");
334
    $lastReleaseScan = $now;
1040 dpurdie 335
    $releaseScanMode = 1;                                   # Assume error
1038 dpurdie 336
 
337
    #
338
    #   Get list of packages from Remote site
339
    #   Invoke a program on the remote site and parse the results
340
    #
341
    #   Returned data looks like:
1042 dpurdie 342
    #   1141792602 GMT(Wed Mar  8 04:36:42 2006) [DL] ishieldmodules/11.5.0.cots
1038 dpurdie 343
    #   
344
    #
345
    my $remotePkgList;
5404 dpurdie 346
    my $remoteData;
1038 dpurdie 347
    my $ph;
1040 dpurdie 348
    my $tgt_cmd = "$conf->{'bindir'}/get_plist.pl";
3515 dpurdie 349
    my $ssh_cmd = sshCmd($tgt_cmd);
1038 dpurdie 350
 
351
    $logger->verbose2("processReleaseList:ssh_cmd:$ssh_cmd");
352
    open ($ph, "$ssh_cmd |");
353
    while ( <$ph> )
354
    {
355
        chomp;
5404 dpurdie 356
        if ($_ =~ m~^Metadata\s+~)
1038 dpurdie 357
        {
5404 dpurdie 358
            parsePkgMetaData($_, \%{$remoteData})
1038 dpurdie 359
        }
360
        else
361
        {
5404 dpurdie 362
            if ( parsePkgList($_, \%{$remotePkgList} ) )
363
            {
364
                $logger->verbose2("processReleaseList:Data: $_");
365
            }
366
            else
367
            {
368
                $logger->warn("processReleaseList:Bad Data: $_");
369
            }
1038 dpurdie 370
        }
371
    }
372
    close ($ph);
373
    $logger->verbose("processReleaseList:End: $?");
3515 dpurdie 374
    LogTxError ($?);
1038 dpurdie 375
    if ( $? != 0 )
376
    {
377
        $logger->warn("Cannot retrieve package list: $?");
5398 dpurdie 378
        $statistics{state} = 'No Remote Package List';
1038 dpurdie 379
        return;
380
    }
3515 dpurdie 381
 
1042 dpurdie 382
#Utils::DebugDumpData ("remotePkgList", $remotePkgList);
4456 dpurdie 383
 
1038 dpurdie 384
    #
385
    #   Determine the set of packages in the releases to be transferred
4456 dpurdie 386
    # 
387
    my $pkgList;
388
    if ( $conf->{'allArchive'} )
1040 dpurdie 389
    {
4456 dpurdie 390
        #   Examine entire archive
391
        #
392
        $pkgList = getArchiveList();
1040 dpurdie 393
    }
4456 dpurdie 394
    else
395
    {
396
        #   Examine Releases
397
        #
398
        my @rlist = getReleaseList();
399
        unless ( @rlist )
400
        {
401
            $logger->verbose2("No Releases to Process");
5398 dpurdie 402
            $statistics{state} = 'No Releases found';
4456 dpurdie 403
            return;
404
        }
405
        $pkgList = getPkgList(@rlist);
406
    }
1038 dpurdie 407
 
408
    #
409
    #   Append extra packages
410
    #   These are packages that are specifically named by the user
411
    #
412
    #   Note: If there are symbolic links, then the target of the
413
    #         link is treated used as the package name
414
    #
415
    #         Symlink MUST be within the same directory
3846 dpurdie 416
    #           Used to transfer jats2_current
1038 dpurdie 417
    #
418
    my $pkgLink;
419
    while ( (my ($pname, $pvers)) = each %{$extraPkgs} ) {
420
        while ( (my ($pver, $pdata) ) = each %{$pvers} ) {
421
 
1040 dpurdie 422
            my $epath = catfile( $conf->{'dpkg_archive'} , $pname, $pver );
1038 dpurdie 423
            if ( -l $epath )
424
            {
425
                my $lver = readlink( $epath );
426
                if ( ! defined $lver )
427
                {
3846 dpurdie 428
                    $logger->warn("Can't resolve symlink: $pname, $pver");
1038 dpurdie 429
                    next;
430
                }
431
 
432
                if ( $lver =~ m ~/~ )
433
                {
434
                    $logger->warn("Won't resolve symlink: $pname, $pver, $lver");
435
                    next;
436
                }
437
                $pkgLink->{$pname}{$pver} = $lver;
438
                $pdata = $pver;
439
                $pver = $lver;
6098 dpurdie 440
 
441
                # Delete all instances of this package so that the symlink can be replicated correctly
442
                delete $pkgList->{$pname};
1038 dpurdie 443
            }
444
 
445
            $logger->verbose2("Add extra package: $pname, $pver, $pdata");
446
            $pkgList->{$pname}{$pver} = $pdata;
447
        }
448
    }
449
 
1040 dpurdie 450
    #
451
    #   If there are no packages to process, then assume that this is an error
452
    #   condition. Retry the operation soon.
453
    #
454
    unless ( keys %{$pkgList} )
455
    {
456
 
457
        $logger->verbose2("No packages to process");
5398 dpurdie 458
        $statistics{state} = 'No Packages found';
1040 dpurdie 459
        return;
460
    }
461
 
1038 dpurdie 462
#    while ( (my ($pname, $pvers)) = each %{$pkgList} )
463
#    {
464
#        while ( (my ($pver, $ptime) ) = each %{$pvers} )
465
#        {
466
#            print "L-- $pname, $pver, $ptime \n";
467
#
468
#        }
469
#    }
470
 
471
    #
1040 dpurdie 472
    #   Delete Excess Packages
1038 dpurdie 473
    #       Packages not required on the target
1042 dpurdie 474
    #           KLUDGE: Don't delete links to packages
475
    #           Don't delete packages marked for deletion
1038 dpurdie 476
    #
477
    my $excessPkgList;
1048 dpurdie 478
    my $excessPkgListCount = 0;
1038 dpurdie 479
    if ( $conf->{deletePackages} )
480
    {
481
        while ( (my ($pname, $pvers)) = each %{$remotePkgList} )
482
        {
483
            while ( (my ($pver, $pdata) ) = each %{$pvers} )
484
            {
485
                if ( !exists $pkgList->{$pname}{$pver} )
486
                {
487
                    if ( exists $pkgLink->{$pname}{$pver} )
488
                    {
489
                        $logger->verbose2("Keep Excess package-link: ${pname}/${pver}");
490
                        next;
491
                    }
1040 dpurdie 492
 
493
                    if ( exists $excludePkgs->{$pname} )
494
                    {
495
                        $logger->verbose2("Keep Excluded package: ${pname}");
496
                        next;
497
                    }
498
 
1042 dpurdie 499
                    if ( exists $pdata->{deleted} )
500
                    {
501
                        if ( $conf->{deleteAge} )
502
                        {
503
                            if ( $pdata->{deleted} <= $conf->{deleteAge} )
504
                            {
505
                                $logger->verbose2("Already marked for future age deletion: ${pname}/${pver}, $pdata->{deleted}");
506
                                next;
507
                            }
508
                            $pdata->{FORCEDELETE} = 1;
509
                        }
510
 
511
                        if ( !$conf->{deleteImmediate} )
512
                        {
513
                            $logger->verbose2("Already marked for deletion: ${pname}/${pver}");
514
                            next;
515
                        }
516
                    }
517
 
518
                    #
519
                    #   Force deletion
520
                    #       deleteImmediate mode
521
                    #       target is a broken link
522
                    #
523
                    $pdata->{FORCEDELETE} = 1
524
                        if ($conf->{deleteImmediate} || $pdata->{broken});
525
 
1038 dpurdie 526
                    $excessPkgList->{$pname}{$pver} = $pdata;
1048 dpurdie 527
                    $excessPkgListCount++;
1038 dpurdie 528
                    $logger->verbose("Excess package: ${pname}/${pver}");
529
                }
1050 dpurdie 530
#                else
531
#                {
532
#                        $logger->verbose3("Retain package: ${pname}/${pver}");
533
#                }
1038 dpurdie 534
            }
535
        }
536
    }
537
 
538
    #
539
    #   Process the remote list and the local list
540
    #   The remote time-stamp is the modification time of the packages descpkg file
541
    #
542
    #   Mark for transfer packages that
1040 dpurdie 543
    #       Are in the local set but not the remote set
1038 dpurdie 544
    #       Have a different time stamp
545
    #
546
    #   Ignore packages not in the local archive
547
    #   Ignore packages that don't have a descpkg
548
    #   Ignore packages that are writable - still being formed
549
    #
550
    my $needPkgList;
1048 dpurdie 551
    my $needPkgListCount = 0;
552
    my $filteredCount = 0;
553
    my $missingCount = 0;
554
    my $writableCount = 0;
555
    my $excludeCount = 0;
5404 dpurdie 556
    my $packageVersionCount = 0;
1038 dpurdie 557
    while ( (my ($pname, $pvers)) = each %{$pkgList} )
558
    {
1040 dpurdie 559
        #
560
        #   Ignore excluded packages
561
        #
1048 dpurdie 562
        if ( exists $excludePkgs->{$pname} )
563
        {
564
            $excludeCount++;
565
            next;
566
        }
1040 dpurdie 567
 
1048 dpurdie 568
        #
569
        #   Ignore packages that are filtered out
570
        #
571
        if ( defined $conf->{'packageFilter'} )
572
        {
573
            unless ( $pname =~ m~$conf->{'packageFilter'}~ )
574
            {
575
                $logger->verbose3("Filtering out: ${pname}");
576
                $filteredCount++;
577
                next;
578
            }
579
        }
580
 
1038 dpurdie 581
        while ( (my ($pver, $pdata) ) = each %{$pvers} )
582
        {
1042 dpurdie 583
            my $tmtime = $remotePkgList->{$pname}{$pver}{time} || 0;
5404 dpurdie 584
            $packageVersionCount++;
1038 dpurdie 585
 
586
            # Package is present in both list
1040 dpurdie 587
            my ($mtime, $mode) = Utils::mtime( catfile( $conf->{'dpkg_archive'} , $pname, $pver, 'descpkg' ));
1038 dpurdie 588
            if ( $mtime == 0 )
589
            {
590
                # PackageVersion not in local archive (at least the descpkg file is not)
591
                # Skip now - will pick it up later
592
                $logger->verbose("Package not in dpkg_archive: $pname, $pver");
1048 dpurdie 593
                $missingCount++;
1038 dpurdie 594
                next;
595
            }
596
 
597
            if ( $mode & 0222 )
598
            {
599
                # Descpkg file is writable
600
                # Package may be in the process of being created
1048 dpurdie 601
                # If the package has been writable for a long time, then
1038 dpurdie 602
                # consider for transfer
603
                my $age = $now - $mtime;
604
                if ( $age < ($conf->{'writewindow '} || 600) )
605
                {
606
                    $logger->verbose("Package is writable: $pname, $pver, ", $now - $mtime);
1048 dpurdie 607
                    $writableCount++;
1038 dpurdie 608
                    next;
609
                }
610
            }
611
 
612
            if ( $mtime != $tmtime )
613
            {
614
                # Package not present on target, or timestamps differ
615
                $logger->verbose("Package Needs to be transferred: $pname, $pver, $mtime, $tmtime");
616
                $needPkgList->{$pname}{$pver} = $pdata;
1048 dpurdie 617
                $needPkgListCount++;
1038 dpurdie 618
                next;
619
            }
620
        }
621
    }
622
 
1048 dpurdie 623
 
1038 dpurdie 624
    #
625
    #   Debug output only
626
    #   Display what we need to transfer
627
    #
628
    if ( $conf->{verbose} > 2 )
629
    {
630
        while ( (my ($pname, $pvers)) = each %{$needPkgList} )
631
        {
632
            while ( (my ($pver, $pdata) ) = each %{$pvers} )
633
            {
634
                $logger->verbose("Need to transfer: $pname, $pver, $pdata");
635
            }
636
        }
637
    }
1048 dpurdie 638
    if ( $conf->{verbose}  )
639
    {
640
        $logger->verbose("Packages to transfer: $needPkgListCount");
641
        $logger->verbose("Packages to delete: $excessPkgListCount");
642
        $logger->verbose("Packages filtered out: $filteredCount");
643
        $logger->verbose("Packages missing: $missingCount");
644
        $logger->verbose("Packages still writable: $writableCount");
645
        $logger->verbose("Packages excluded: $excludeCount");
646
    }
1038 dpurdie 647
 
648
    #
5398 dpurdie 649
    #   Update stats
650
    #   At this point we are looking pretty good
651
    #   
652
    $statistics{state} = 'OK';
5404 dpurdie 653
    $statistics{total} = $packageVersionCount;
5398 dpurdie 654
    $statistics{transfer} = $needPkgListCount;
655
    $statistics{delete} = $excessPkgListCount;
656
    $statistics{filtered} = $filteredCount;
657
    $statistics{missing} = $missingCount;
658
    $statistics{writable} = $writableCount;
659
    $statistics{excluded} = $excludeCount;
660
 
661
    #
1038 dpurdie 662
    #   Time to do the real work
663
    #   Transfer packages and delete excess packages
664
    #   Note: Perform the transfers first
665
    #         Limit the number of packages processed in one pass
666
    #
667
    my $txcount = $conf->{maxpackages};
668
 
669
    #
670
    #   Transfer packages that we have identified
671
    #
672
    send_pkgs:
673
    while ( (my ($pname, $pvers)) = each %{$needPkgList} )
674
    {
675
        while ( (my ($pver, $pdata) ) = each %{$pvers} )
676
        {
677
            if ( --$txcount <= 0 )
678
            {
1050 dpurdie 679
                $logger->warn("Max transfer count exceeded: $needPkgListCount transfer remaining");
1038 dpurdie 680
                $lastReleaseScan = 0;
681
                last send_pkgs;
682
            }
1289 dpurdie 683
 
684
            if ( readConfig() )
685
            {
686
                $logger->warn("Config file changed");
687
                $lastReleaseScan = 0;
688
                $txcount = 0;
689
                last send_pkgs;
690
            }
691
 
1044 dpurdie 692
            transferPackage ($pname, $pver, $pdata);
1048 dpurdie 693
            $needPkgListCount--;
1038 dpurdie 694
        }
695
    }
696
 
697
    #
698
    #   Delete packages that have been identified as excess
699
    #
700
    delete_pkgs:
701
    while ( (my ($pname, $pvers)) = each %{$excessPkgList} )
702
    {
703
        while ( (my ($pver, $pdata) ) = each %{$pvers} )
704
        {
705
            if ( --$txcount <= 0 )
706
            {
1050 dpurdie 707
                $logger->warn("Max transfer count exceeded: $excessPkgListCount deletion remaining");
1038 dpurdie 708
                $lastReleaseScan = 0;
709
                last delete_pkgs;
710
            }
1289 dpurdie 711
 
712
            if ( readConfig() )
713
            {
714
                $logger->warn("Config file changed");
715
                $lastReleaseScan = 0;
716
                $txcount = 0;
717
                last send_pkgs;
718
            }
719
 
1044 dpurdie 720
            deletePackage ($pname, $pver, $pdata);
1048 dpurdie 721
            $excessPkgListCount--;
1038 dpurdie 722
        }
723
    }
724
 
725
    #
726
    #   Send package list to the target
727
    #
728
    sendPackageList ($pkgList);
1040 dpurdie 729
 
730
    #
731
    #   On a successful transfer
732
    #       Force tag processing
733
    #       Set scan Mode to normal
734
    #
735
    $tagDirTime = 0;
736
    $releaseScanMode = 0;
1038 dpurdie 737
}
738
 
739
#-------------------------------------------------------------------------------
740
# Function        : sendPackageList
741
#
742
# Description     : Transfer package list to the target
743
#
744
# Inputs          : $pkgList            - Ref to hash of package names and versions
745
#
1040 dpurdie 746
# Returns         : Nothing
747
#                   Don't really care about any errors from this process
748
#                   Its not essential
1038 dpurdie 749
#
750
sub sendPackageList
751
{
752
    my ($pkgList) = @_;
753
    my ($fh, $filename) = tempfile( "/tmp/blat.$$.XXXX", SUFFIX => '.txt');
754
    $logger->verbose("sendPackageList:TmpFile: $filename");
755
 
756
    #
757
    #   Create a temp file with data
758
    #
759
    foreach my $pname ( sort keys %{$pkgList} )
760
    {
761
        foreach my $pver ( sort keys %{$pkgList->{$pname}} )
762
        {
763
            print $fh "$pname/$pver\n";
764
        }
765
    }
766
    close $fh;
767
 
768
    #
769
    #   Transfer to target
770
    #   Create the process pipe to transfer the file
771
    #   gzip the file and pipe the result through a ssh session to the target machine
3515 dpurdie 772
    #   gzip -c filename |  ssh  ... "./receive_file filename"
1038 dpurdie 773
    #
774
    my $ph;
3515 dpurdie 775
    my $gzip_cmd = "$gzip --no-name -c \"$filename\"";
1040 dpurdie 776
    my $tgt_cmd = "$conf->{'bindir'}/receive_file \"ArchiveList\"";
3515 dpurdie 777
    my $ssh_cmd = sshCmd($tgt_cmd);
1038 dpurdie 778
 
779
    $logger->verbose2("sendPackageList:gzip_cmd:$gzip_cmd");
780
    $logger->verbose2("sendPackageList:tgt_cmd:$tgt_cmd");
781
    $logger->verbose2("sendPackageList:ssh_cmd:$ssh_cmd");
782
 
783
    open ($ph, "$gzip_cmd | $ssh_cmd |");
784
    while ( <$ph> )
785
    {
786
        chomp;
787
        $logger->verbose2("sendPackageList:Data: $_");
788
    }
789
    close ($ph);
3515 dpurdie 790
    unlink $filename;
1038 dpurdie 791
    $logger->verbose("sendPackageList:End: $?");
3515 dpurdie 792
    LogTxError ($?);
1038 dpurdie 793
}
794
 
795
 
796
#-------------------------------------------------------------------------------
797
# Function        : getPkgList
798
#
799
# Description     : Determine a set of package versions within the list
800
#                   of provided releases
801
#
802
# Inputs          : @rlist              - A list of releases to examine
803
#
804
# Returns         : Ref to a hask of package versions
805
#
806
sub getPkgList
807
{
808
    my %pdata;
809
    my $RM_DB;
810
    connectRM(\$RM_DB);
811
    $logger->verbose("getPkgList");
812
 
813
    #
814
    #   Determine the releases that are in this project
815
    #   Build up an sql query
816
    #
817
    my @m_rlist;
818
    push @m_rlist,"rc.RTAG_ID=$_" foreach ( @_ );
819
    my $m_rlist = join ' OR ', @m_rlist;
1048 dpurdie 820
    my $m_sqlstr = "SELECT DISTINCT pv.PV_ID, pkg.PKG_NAME, pv.PKG_VERSION, pv.IS_DEPLOYABLE" .
1038 dpurdie 821
                    " FROM RELEASE_MANAGER.RELEASE_CONTENT rc, RELEASE_MANAGER.PACKAGE_VERSIONS pv, RELEASE_MANAGER.PACKAGES pkg" .
822
                    " WHERE ( $m_rlist ) AND rc.PV_ID = pv.PV_ID AND pv.PKG_ID = pkg.PKG_ID" .
823
                    " ORDER by PKG_NAME DESC";
824
    $logger->verbose3("getPkgList:Sql:$m_sqlstr");
825
 
826
    my $sth = $RM_DB->prepare($m_sqlstr);
827
    if ( defined($sth) )
828
    {
829
        if ( $sth->execute( ) )
830
        {
831
            if ( $sth->rows )
832
            {
833
                while (my @row = $sth->fetchrow_array )
834
                {
835
                    $logger->verbose2("getPkgList:Data:@row");
836
                    $pdata{$row[1]}{$row[2]} = 1;
837
                }
838
            }
839
            $sth->finish();
840
        }
841
    }
842
    else
843
    {
844
        $logger->warn("getPkgList: SQL Prepare failure");
845
    }
1050 dpurdie 846
 
847
   disconnectRM(\$RM_DB);
1038 dpurdie 848
   return \%pdata;
849
}
850
 
851
 
852
#-------------------------------------------------------------------------------
853
# Function        : getReleaseList
854
#
855
# Description     : Determine the list of releases to be proccessed
1040 dpurdie 856
#                   From:
857
#                       Convert projects to a list of releases
858
#                       Configured list of releases
1038 dpurdie 859
#
860
# Inputs          : None
861
#
862
# Returns         : A list of releases to be processed
863
#
864
sub getReleaseList
865
{
866
    my $RM_DB;
867
    my %rlist;
1048 dpurdie 868
    my $m_sqlstr;
1038 dpurdie 869
    $logger->verbose("getReleaseList");
870
 
871
    #
1040 dpurdie 872
    #   Cache data
873
    #   Only for one cycle of the main loop
874
    #
875
    if ( exists $releaseData{getReleaseList} )
876
    {
877
        $logger->verbose3("getReleaseList:Cache hit");
878
        return @{$releaseData{getReleaseList}};
879
    }
880
 
881
    #
1048 dpurdie 882
    #   All projects
1038 dpurdie 883
    #
1048 dpurdie 884
    if ( $conf->{'allProjects'} )
1038 dpurdie 885
    {
1048 dpurdie 886
        $m_sqlstr = "SELECT rt.RTAG_ID" .
887
                    " FROM RELEASE_MANAGER.RELEASE_TAGS rt" .
1050 dpurdie 888
                    " WHERE rt.OFFICIAL != 'A'";
889
                    #" AND rt.OFFICIAL != 'Y'";
1048 dpurdie 890
    }
891
    else
892
    {
1038 dpurdie 893
        #
1048 dpurdie 894
        #   Convert list of projects into a list of releases
1038 dpurdie 895
        #
1048 dpurdie 896
        my @plist = split /[,\s]+/, $conf->{'project'} || '';
897
        if ( @plist )
898
        {
899
            #
900
            #   Determine the releases that are in this project
901
            #   Build up an sql query
902
            #
903
            my @m_plist;
904
            push @m_plist,"PROJ_ID=$_" foreach ( @plist );
905
            my $m_plist = join ' OR ', @m_plist;
906
            $m_sqlstr = "SELECT rt.RTAG_ID" .
907
                        " FROM RELEASE_MANAGER.RELEASE_TAGS rt" .
5300 dpurdie 908
                        " WHERE ( $m_plist ) AND rt.OFFICIAL != 'A'";
909
                        #" AND rt.OFFICIAL != 'Y'";
1048 dpurdie 910
        }
911
    }
1038 dpurdie 912
 
1048 dpurdie 913
    if ( defined $m_sqlstr )
914
    {
1038 dpurdie 915
        $logger->verbose3("getReleaseList:Sql:$m_sqlstr");
1048 dpurdie 916
        connectRM(\$RM_DB);
1038 dpurdie 917
        my $sth = $RM_DB->prepare($m_sqlstr);
918
        if ( defined($sth) )
919
        {
920
            if ( $sth->execute( ) )
921
            {
922
                if ( $sth->rows )
923
                {
924
                    while (my @row = $sth->fetchrow_array )
925
                    {
926
                        $logger->verbose2("getReleaseList:Data:@row");
927
                        $rlist{$row[0]} = 1;
928
                    }
929
                }
930
                $sth->finish();
931
            }
932
        }
933
        else
934
        {
935
            $logger->warn("getReleaseList: SQL Prepare failure");
936
        }
1050 dpurdie 937
        disconnectRM(\$RM_DB);
1038 dpurdie 938
    }
939
 
940
    #
941
    #   Add in the user specified list of releases
942
    #
943
    my @rlist = split /[,\s]+/, $conf->{'release'} || '';
944
    $rlist{$_} = 1 foreach(@rlist);
945
 
946
    #
947
    #   Sort for pretty display only
948
    #
1040 dpurdie 949
    @{$releaseData{getReleaseList}} = sort {$a <=> $b} keys %rlist;
950
 
951
    return @{$releaseData{getReleaseList}};
1038 dpurdie 952
}
953
 
1040 dpurdie 954
#-------------------------------------------------------------------------------
3846 dpurdie 955
# Function        : getPackageVersions
956
#
957
# Description     : Get the list of package-versions available in the package
958
#                   store.
959
#
960
# Inputs          : pkgName             - The package name
961
#
962
# Returns         : Array of versions
963
#
964
sub getPackageVersions
965
{
966
    my ($pkgName) = @_;
967
    my @versionList;
968
 
969
    my $pkgDir = catfile($conf->{'dpkg_archive'} , $pkgName );
970
    my $dh;
971
 
972
    unless (opendir($dh, $pkgDir))
973
    {
974
        $logger->warn ("Can't opendir $pkgDir: $!");
975
        return @versionList;
976
    }
977
 
978
    #
979
    #   Process each entry
980
    #   Ignore those that start with a .
981
    #
982
    while (my $version = readdir($dh) )
983
    {
984
        next if ( $version =~ m~^\.~ );
985
        my $file = catfile($pkgDir, $version);
986
 
987
        next unless ( -d $file );
988
 
989
        push @versionList, $version;
990
        $logger->verbose3("getPackageVersions: $pkgName, $version");
991
    }
992
    closedir $dh;
993
    return @versionList;
994
}
995
 
996
#-------------------------------------------------------------------------------
4456 dpurdie 997
# Function        : getArchiveList 
998
#
999
# Description     : Get the entire set of package versions in the archive
1000
#
1001
# Inputs          : 
1002
#
1003
# Returns         : Ref to a hask of package versions
1004
#
1005
sub getArchiveList
1006
{
1007
    my $pkgDir = $conf->{'dpkg_archive'};
1008
    my %archiveList;
1009
    my $dh;
1010
    my @pkgList;
1011
 
1012
    unless (opendir($dh, $pkgDir))
1013
    {
1014
        $logger->warn ("Can't opendir $pkgDir: $!");
1015
        return \%archiveList;
1016
    }
1017
 
1018
    #
1019
    #   Process each entry
1020
    #   Ignore those that start with a .
1021
    #   Ignore files
1022
    #
1023
    while (my $pkgName = readdir($dh) )
1024
    {
1025
        next if ( $pkgName =~ m~^\.~ );
1026
        my $file = catfile($pkgDir, $pkgName);
1027
 
1028
        next unless ( -d $file );
1029
        $logger->verbose3("getArchiveList: $pkgName");
1030
        push @pkgList, $pkgName;
1031
    }
1032
    closedir $dh;
1033
 
1034
    #   Now get the package versions
1035
    #       Sort for pretty display
1036
    foreach my $pname (sort @pkgList)
1037
    {
1038
        foreach my $pver (getPackageVersions($pname))
1039
        {
1040
            $archiveList{$pname}{$pver} = 1;
1041
        }
1042
    }
1043
 
1044
    return \%archiveList;
1045
}
1046
 
1047
#-------------------------------------------------------------------------------
1040 dpurdie 1048
# Function        : maintainTagList
1049
#
1050
# Description     : Maintain a data structure for the maintenance of the
1051
#                   tags directory
1052
#
1053
# Inputs          : None
1054
#
1055
# Returns         : Nothing
1056
#
1057
sub maintainTagList
1058
{
1059
    #
1060
    #   Time to perform the scan
1061
    #   Will do at startup and every time period there after
1062
    #
1063
    return unless ( $now > ($lastTagListScan + $conf->{tagListUpdate} ));
1064
    $logger->verbose("maintainTagList");
1065
    $lastTagListScan = $now;
1038 dpurdie 1066
 
1040 dpurdie 1067
    #
1068
    #   Get list of things
1069
    #
1070
    my %config;
4457 dpurdie 1071
    if ($conf->{'allArchive'} )
1072
    {
1073
        $config{allArchive} = 1
1074
    }
1075
    elsif ($conf->{'allProjects'} )
1076
    {
1077
        $config{allProjects} = 1;
1078
    }
1079
    else
1080
    {
1081
        %{$config{projects}} = map { $_ => 1 } split (/[,\s]+/, $conf->{'project'} || '');
1082
        %{$config{releases}} = map { $_ => 1 } getReleaseList();
1083
    }
1040 dpurdie 1084
 
1085
    #
1086
    #   Save data
1087
    #
1088
    my $dump =  Data::Dumper->new([\%config], [qw(*config)]);
1089
#print $dump->Dump;
1090
#$dump->Reset;
1091
 
1092
    #
1093
    #   Save config data
1094
    #
1095
    my $conf_file = catfile( $conf->{'tagdir'},'.config' );
1096
    $logger->verbose3("maintainTagList: Writting $conf_file");
1097
 
1098
    my $fh;
1099
    open ( $fh, '>', $conf_file ) or $logger->err("Can't create $conf_file: $!");
1100
    print $fh $dump->Dump;
1101
    close $fh;
1102
}
1103
 
1104
 
1038 dpurdie 1105
#-------------------------------------------------------------------------------
1106
# Function        : processTags
1107
#
1108
# Description     : Process tags and send marked package versions to the target
1109
#                       Determine if new tags are present
1110
#                       Process each tag
1111
#
1112
# Inputs          : None
1113
#
1114
# Returns         : Nothing
1115
#
1116
sub processTags
1117
{
1118
    #
1119
    #   Determine if new tags are present by examining the time
1120
    #   that the directory was last modified.
1121
    #
1122
    #   Allow for a forced scan to catch packages that did not transfer
1123
    #   on the first attempt
1124
    #
5398 dpurdie 1125
    my $tagCount = 0;
1038 dpurdie 1126
    my ($mtime) = Utils::mtime($conf->{'tagdir'} );
1127
    if ( ($mtime > $tagDirTime) || ($now > ($lastDirScan + $conf->{'forcedirscan'})) )
1128
    {
1042 dpurdie 1129
        $logger->verbose2("processTags: ",$conf->{'tagdir'}, $mtime - $tagDirTime, $now - $lastDirScan);
1038 dpurdie 1130
        $tagDirTime = $mtime;
1131
        $lastDirScan = $now;
1132
 
1133
        my $dh;
1134
        unless (opendir($dh, $conf->{'tagdir'}))
1135
        {
1136
            $logger->warn ("can't opendir $conf->{'tagdir'}: $!");
1137
            return;
1138
        }
1139
 
1140
        #
1141
        #   Process each entry
1142
        #   Ignore those that start with a .
1143
        #
1144
        while (my $tag = readdir($dh) )
1145
        {
1146
            next if ( $tag =~ m~^\.~ );
1147
            my $file = "$conf->{'tagdir'}/$tag";
1042 dpurdie 1148
            $logger->verbose3("processTags: $file");
1149
 
1038 dpurdie 1150
            next unless ( -f $file );
1151
            next if ( $tag  eq 'ReleaseList' );
1152
 
1153
            if ( $tag =~ m~(.+)::(.+)~  )
1154
            {
1155
                my $package = $1;
1156
                my $version = $2;
5398 dpurdie 1157
                $tagCount++;
6098 dpurdie 1158
 
1159
                #
1160
                #   Don't transfer 'extra' packages
1161
                #
1162
                if (exists ($extraPkgs->{$package}) ) 
1038 dpurdie 1163
                {
6098 dpurdie 1164
                    $logger->warn ("Delete excess package tag: $tag");
1038 dpurdie 1165
                    unlink $file;
1166
                }
6098 dpurdie 1167
                elsif ( transferPackage( $package, $version ))
1168
                {
1169
                    unlink $file;
1170
                }
1038 dpurdie 1171
                else
1172
                {
1173
                    my ($mtime) = Utils::mtime( $file );
1174
                    if ( $now - $mtime > $conf->{'tagage'} )
1175
                    {
1176
                        $logger->warn ("Delete unsatisfied tag: $tag");
1177
                        unlink $file;
5398 dpurdie 1178
                        $statistics{staleTags}++;
1038 dpurdie 1179
                    }
1180
                }
1181
            }
1182
        }
1183
        closedir $dh;
1184
    }
5398 dpurdie 1185
    $statistics{tagCount} = $tagCount;
1038 dpurdie 1186
}
1187
 
1188
#-------------------------------------------------------------------------------
1189
# Function        : transferPackage
1190
#
1191
# Description     : Transfer specified package to target system
1192
#
1193
# Inputs          : $pname          - Name of the package
1194
#                   $pver           - Package version
1195
#                   $plink          - (optional) Symlink in same package
1196
#
1197
# Returns         : true    - Package transferred
1198
#                   false   - Package not transferred
1199
#
1200
sub transferPackage
1201
{
1202
    my ($pname, $pver, $plink ) = @_;
1203
    my $rv = 0;
1204
    $logger->logmsg("transferPackage: @_");
1205
 
1206
    #
1040 dpurdie 1207
    #   Do not transfer excluded files
1208
    #
1209
    if ( exists $excludePkgs->{$pname} )
1210
    {
1048 dpurdie 1211
        $logger->warn("transferPackage: Excluded package not transferred: $pname, $pver");
1040 dpurdie 1212
        return 1;
1213
    }
1048 dpurdie 1214
 
1040 dpurdie 1215
    #
1048 dpurdie 1216
    #   Apply package filter
1217
    #
1218
    if ( defined $conf->{'packageFilter'} )
1219
    {
1220
        unless ( $pname =~ m~$conf->{'packageFilter'}~ )
1221
        {
1222
            $logger->warn("transferPackage: Filtered out package not transferred: $pname, $pver");
1223
            return 1;
1224
        }
1225
    }
1226
 
1227
    #
1038 dpurdie 1228
    #   plink of 1 is not a symlink
1229
    #
1230
    $plink = undef if ( defined($plink) && $plink eq '1' );
1231
 
1232
    #
1233
    #   If its been transferred in the current scan, then
1234
    #   indicate that all is well
1235
    #
1236
    if ( $transferred->{$pname}{$pver}  )
1237
    {
1238
        $logger->verbose("transferPackage: Already transferred");
1239
        return 1;
1240
    }
1241
 
1040 dpurdie 1242
    my $sfile = catfile( $conf->{'dpkg_archive'} , $pname, $pver );
1038 dpurdie 1243
    unless ( -d $sfile )
1244
    {
1245
        $logger->warn("transferPackage:Package not found: $pname, $pver");
1246
        return $rv;
1247
    }
1248
 
1249
    #
4456 dpurdie 1250
    #   Create the process pipe to transfer the package
1038 dpurdie 1251
    #   Tar the directory and pipe the result through a ssh session to
1252
    #   the target machine
3515 dpurdie 1253
    #   $tar -czf - -C "$dpkg/${pname}/${pver}" . |  ssh  ... "./receive_package pname pver"
1038 dpurdie 1254
    #
1255
    my $ph;
3515 dpurdie 1256
    my $tar_cmd = "$tar -czf - -C \"$sfile\" .";
1038 dpurdie 1257
    my $tgt_opts = defined($plink) ? "\"-L$plink\"" : '';
1040 dpurdie 1258
    my $tgt_cmd = "$conf->{'bindir'}/receive_package $tgt_opts \"$pname\" \"$pver\"";
3515 dpurdie 1259
    my $ssh_cmd = sshCmd($tgt_cmd);
1038 dpurdie 1260
 
1261
    $logger->verbose2("transferPackage:tar_cmd:$tar_cmd");
1262
    $logger->verbose2("transferPackage:tgt_cmd:$tgt_cmd");
1263
    $logger->verbose2("transferPackage:ssh_cmd:$ssh_cmd");
1264
 
1265
    open ($ph, "$tar_cmd | $ssh_cmd |");
1266
    while ( <$ph> )
1267
    {
1268
        chomp;
1269
        $logger->verbose2("transferPackage:Data: $_");
1270
    }
1271
    close ($ph);
1272
    $logger->verbose("transferPackage:End: $?");
1273
    if ( $? == 0 )
1274
    {
1275
        #
1276
        #   Mark has having been transferred in the current cycle
1277
        #
1278
        $transferred->{$pname}{$pver} = 1;
1279
        $rv = 1;
5398 dpurdie 1280
        $statistics{txCount}++;
1038 dpurdie 1281
    }
1282
    else
1283
    {
1284
        $logger->warn("transferPackage:Transfer Error: $pname, $pver, $?");
1285
    }
3515 dpurdie 1286
    LogTxError ($?);
1038 dpurdie 1287
    return $rv;
1288
}
1289
 
1290
#-------------------------------------------------------------------------------
1291
# Function        : deletePackage
1292
#
1293
# Description     : Delete specified package to target system
1294
#
1295
# Inputs          : $pname          - Name of the package
1296
#                   $pver           - Package version
1042 dpurdie 1297
#                   $pdata          - Hash of extra data
1038 dpurdie 1298
#
1299
# Returns         : true    - Package transferred
1300
#                   false   - Package not transferred
1301
#
1302
sub deletePackage
1303
{
1042 dpurdie 1304
    my ($pname, $pver, $pdata ) = @_;
1038 dpurdie 1305
    my $rv = 0;
1042 dpurdie 1306
    $logger->logmsg("deletePackage: $pname, $pver");
1038 dpurdie 1307
 
1308
    #
1309
    #   Create the process pipe to delete the package
3515 dpurdie 1310
    #   ssh  ... "./delete_package ${rx_opts} \"$pname\" \"$pver\""
1038 dpurdie 1311
    #
1312
    my $ph;
1042 dpurdie 1313
    my $flags = $pdata->{FORCEDELETE}  ? '' : ' -T';
1314
    my $tgt_cmd = "$conf->{'bindir'}/delete_package $flags \"$pname\" \"$pver\"";
3515 dpurdie 1315
    my $ssh_cmd = sshCmd($tgt_cmd);
1038 dpurdie 1316
 
1040 dpurdie 1317
    $logger->verbose2("deletePackage:tgt_cmd:$tgt_cmd");
1318
    $logger->verbose2("deletePackage:ssh_cmd:$ssh_cmd");
1038 dpurdie 1319
 
1320
    open ($ph, "$ssh_cmd |");
1321
    while ( <$ph> )
1322
    {
1323
        chomp;
1324
        $logger->verbose2("deletePackage:Data: $_");
1325
    }
1326
    close ($ph);
1327
    $logger->verbose("deletePackage:End: $?");
1328
    if ( $? == 0 )
1329
    {
1330
        $rv = 1;
5398 dpurdie 1331
        $statistics{delCount}++;
1038 dpurdie 1332
    }
1333
    else
1334
    {
1335
        $logger->warn("deletePackage:Error: $pname, $pver, $?");
1336
    }
3515 dpurdie 1337
    LogTxError ($?);
1038 dpurdie 1338
    return $rv;
1339
}
1340
 
3515 dpurdie 1341
#-------------------------------------------------------------------------------
1342
# Function        : sshCmd
1343
#
1344
# Description     : Generate a ssh based command
1345
#
1346
# Inputs          : Target command
1347
#
1348
# Returns         : An shh command string
1349
#
1350
sub sshCmd
1351
{
1352
    my ($tgt_cmd) = @_;
3847 dpurdie 1353
    my $sshPort = '';
1354
    $sshPort = "-p $conf->{'sshport'}"
1355
        if ($conf->{'sshport'});
1356
 
1357
    return "ssh -o \"BatchMode yes\" -i $conf->{'identity'} ${sshPort} $conf->{'user'}\@$conf->{'hostname'} \"$tgt_cmd\" 2>&1";
3515 dpurdie 1358
}
1038 dpurdie 1359
 
3515 dpurdie 1360
 
1038 dpurdie 1361
#-------------------------------------------------------------------------------
1042 dpurdie 1362
# Function        : parsePkgList
1363
#
1364
# Description     : Parse one line from a pkgList
1365
#                   Lines are multiple item="data" items
1366
#
1367
# Inputs          : $line                   - Line of data
1368
#                   $hashp                  - Ref to hash to populate
1369
#
1370
# Returns         : A hash of data items
1371
#
1372
sub parsePkgList
1373
{
1374
    my ($line, $hashp) = @_;
1375
    my $rv;
1376
 
1377
    while ( $line =~ m~\s*(.+?)="(.+?)"~ )
1378
    {
1379
        $rv->{$1} = $2;
1380
        $line = $';
1381
    }
1382
#Utils::DebugDumpData ("parsePkgList", $rv);
1383
 
1384
    my $pname = $rv->{pname};
1385
    my $pver =  $rv->{pver};
1386
    return undef unless ( $pname && $pver );
1387
 
1388
    delete $rv->{pname};
1389
    delete $rv->{pver};
1390
    delete $rv->{GMT};
1391
 
1392
    $hashp->{$pname}{$pver} = $rv;
1393
    return $hashp;
1394
}
1395
 
5398 dpurdie 1396
#-------------------------------------------------------------------------------
5404 dpurdie 1397
# Function        : parsePkgMetaData
1398
#
1399
# Description     : Parse one line of meta data from a pkgList
1400
#                   Lines are multiple item="data" items
1401
#
1402
# Inputs          : $line                   - Line of data
1403
#                   $hashp                  - Ref to hash to populate
1404
#
1405
# Returns         : Nothing
1406
#
1407
sub parsePkgMetaData
1408
{
1409
    my ($line, $hashp) = @_;
1410
 
1411
    if ( $line =~ m~\s+(.+?)="(.+?)"~ )
1412
    {
1413
        $hashp->{$1} = $2;
1414
        $statistics{'Target.' . $1} = $2;
1415
        $line = $';
1416
 
1417
        $logger->verbose2("parsePkgMetaData: $1 = $2");
1418
    }
1419
}
1420
 
1421
 
1422
#-------------------------------------------------------------------------------
5398 dpurdie 1423
# Function        : resetDailyStatistics 
1424
#
1425
# Description     : Called periodically to reset the daily statistics
1426
#
1427
# Inputs          : $time       - Current time
1428
#
1429
# Returns         : 
1430
#
1431
sub resetDailyStatistics
1432
{
1433
    my ($time) = @_;
1042 dpurdie 1434
 
5398 dpurdie 1435
    #
1436
    #   Detect a new day
1437
    #
1438
    my $today = (localtime($time))[7];
1439
    if ($yday != $today)
1440
    {
1441
        $yday = $today;
1442
        $logger->logmsg('Resetting daily statistics' );
1443
 
5404 dpurdie 1444
        # Note: Must match @recoverTags in readStatistics
5398 dpurdie 1445
        $statistics{dayStart} = $time;
1446
        $statistics{txCount} = 0;
1447
        $statistics{delCount} = 0;
1448
        $statistics{staleTags} = 0;
1449
        $statistics{linkErrors} = 0;
1450
    }
1451
}
1452
 
1042 dpurdie 1453
#-------------------------------------------------------------------------------
5404 dpurdie 1454
# Function        : readStatistics 
1455
#
1456
# Description     : Read in the last set of stats
1457
#                   Used after a restart to recover daily statistics
1458
#
1459
# Inputs          : 
1460
#
1461
# Returns         : 
1462
#
1463
sub readStatistics
1464
{
1465
    my @recoverTags = qw(dayStart txCount delCount staleTags linkErrors);
1466
 
1467
    if ($conf->{'statsfile'} and -f $conf->{'statsfile'})
1468
    {
1469
        if (open my $fh, $conf->{'statsfile'})
1470
        {
1471
            while (<$fh>)
1472
            {
1473
                m~(.*):(.*)~;
1474
                if ( grep( /^$1$/, @recoverTags ) ) 
1475
                {
1476
                    $statistics{$1} = $2;
1477
                    $logger->verbose("readStatistics $1, $2\n");
1478
                }
1479
            }
1480
            close $fh;
1481
            $yday = (localtime($statistics{dayStart}))[7];
1482
        }
1483
    }
1484
}
1485
 
1486
 
1487
#-------------------------------------------------------------------------------
5398 dpurdie 1488
# Function        : periodicStatistics 
1489
#
1490
# Description     : Called on a regular basis to write out statistics
1491
#                   Used to feed information into Nagios
1492
#                   
1493
#                   This function is called via an alarm and may be outside the normal
1494
#                   processing loop. Don't make assumptions on the value of $now
1495
#
1496
# Inputs          : 
1497
#
1498
# Returns         : 
1499
#
1500
sub periodicStatistics
1501
{
1502
    #
1503
    #   A few local stats
1504
    #
1505
    $statistics{SeqNum}++;
1506
    $statistics{timeStamp} = time();
1507
    $statistics{upTime} = $statistics{timeStamp} - $startTime;
1508
 
1509
    #   Reset daily accumulations - on first use each day
1510
    resetDailyStatistics($statistics{timeStamp});
1511
 
1512
    #
1513
    #   Write statistics to a file
1514
    #       Write to a tmp file, then rename.
1515
    #       Attempt to make the operation atomic - so that the file consumer
1516
    #       doesn't get a badly formed file.
1517
    #   
1518
    if ($conf->{'statsfiletmp'})
1519
    {
1520
        my $fh;
1521
        unless (open ($fh, '>', $conf->{'statsfiletmp'}))
1522
        {
1523
            $fh = undef;
1524
            $logger->warn("Cannot create temp stats file: $!");
1525
        }
1526
        else
1527
        {
5404 dpurdie 1528
            foreach my $key ( sort { lc($a) cmp lc($b) } keys %statistics)
5398 dpurdie 1529
            {
1530
                print $fh $key . ':' . $statistics{$key} . "\n";
1531
                $logger->verbose2('Statistics:'. $key . ':' . $statistics{$key});
1532
            }
1533
            close $fh;
1534
 
1535
            # Rename temp to real file
1536
            rename  $conf->{'statsfiletmp'},  $conf->{'statsfile'} ;
1537
        }
1538
    }
1539
}
1540
 
1541
#-------------------------------------------------------------------------------
1038 dpurdie 1542
# Function        : sighandlers
1543
#
1544
# Description     : Install signal handlers
1545
#
1546
# Inputs          : $conf           - System config
1547
#
1548
# Returns         : Nothing
1549
#
1550
sub sighandlers
1551
{
5398 dpurdie 1552
    my $conf = shift;
1553
    my $logger = $conf->{logger};
1038 dpurdie 1554
 
5398 dpurdie 1555
    $SIG{TERM} = sub {
1556
        # On shutdown
1557
        $logger->logmsg('Received SIGTERM. Shutting down....' );
1558
        unlink $conf->{'pidfile'} if (-f $conf->{'pidfile'});
1559
        exit 0;
1560
    };
1038 dpurdie 1561
 
5398 dpurdie 1562
    $SIG{HUP} = sub {
1563
        # On logrotate
1564
        $logger->logmsg('Received SIGHUP.');
1565
        $logger->rotatelog();
1566
    };
1038 dpurdie 1567
 
5398 dpurdie 1568
    $SIG{USR1} = sub {
1569
        # On Force Archive Sync
1570
        $logger->logmsg('Received SIGUSR1.');
1046 dpurdie 1571
        $lastReleaseScan = 0;
1572
        $lastTagListScan = 0;
5398 dpurdie 1573
    };
1038 dpurdie 1574
 
5398 dpurdie 1575
    alarm 60;
1576
    $SIG{ALRM} = sub {
1577
        # On Dump Statistics
1578
        $logger->verbose2('Received SIGUSR2.');
1579
        periodicStatistics();
1580
        alarm 60;
1581
    };
1582
 
1038 dpurdie 1583
    $SIG{__WARN__} = sub { $logger->warn("@_") };
1584
    $SIG{__DIE__} = sub { $logger->err("@_") };
1585
}
1586
 
1587
#-------------------------------------------------------------------------------
3515 dpurdie 1588
# Function        : LogTxError
1589
#
1590
# Description     : Detect restoration of communication and log such
1591
#                   Don't log failures as the user will do that
1592
#
1593
# Inputs          : $state                  - 0 - All is well
1594
#                                           !0  - Error
1595
#
1596
# Returns         : Nothing
1597
#
1598
sub LogTxError
1599
{
1600
    my ($state) = $@;
1601
    if ( $state )
1602
    {
5398 dpurdie 1603
        $statistics{linkErrors}++ unless($comError);
3515 dpurdie 1604
        $comError++;
5398 dpurdie 1605
        $statistics{state} = 'No Communication';
3515 dpurdie 1606
    }
1607
    elsif ( $comError )
1608
    {
1609
        $logger->warn("Communication Restored");
1610
        $comError = 0;
5398 dpurdie 1611
        $statistics{state} = 'OK';
3515 dpurdie 1612
    }
1613
}
1614
 
1615
 
1616
#-------------------------------------------------------------------------------
1038 dpurdie 1617
# Function        : Error, Verbose, Warning
1618
#
1619
# Description     : Support for JatsRmApi
1620
#
1621
# Inputs          : Message
1622
#
1623
# Returns         : Nothing
1624
#
1625
sub Error
1626
{
1627
    $logger->err("@_");
1628
}
1629
 
1630
sub Verbose
1631
{
1042 dpurdie 1632
    $logger->verbose2("@_");
1038 dpurdie 1633
}
1634
 
1635
sub Warning
1636
{
1637
    $logger->warn("@_");
1638
}
1639
 
1640
 
1641
 
1642