Subversion Repositories DevTools

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7396 dpurdie 1
#! /usr/bin/perl
2
########################################################################
3
# COPYRIGHT - VIX IP PTY LTD ("VIX"). ALL RIGHTS RESERVED.
4
#
5
# Module name   : blatS3Sync.pl
6
# Module type   :
7
# Compiler(s)   : Perl
8
# Environment(s):
9
#
10
# Description   :   This is a blat related task that will perform S3 SYNC
11
#                   transfers for configured releases
12
#
13
# Usage         :   ARGV[0] - Path to config file for this instance
14
#
15
#......................................................................#
16
 
17
require 5.008_002;
18
use strict;
19
use warnings;
20
use Getopt::Long;
21
use File::Basename;
22
use Data::Dumper;
23
use File::Spec::Functions;
24
use POSIX ":sys_wait_h";
25
use File::Temp qw/tempfile/;
26
use Digest::MD5 qw(md5_base64 md5_hex);
27
use File::Path qw( rmtree );
28
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
29
use JSON;
30
 
31
use FindBin;                                    # Determine the current directory
32
use lib "$FindBin::Bin/lib";                    # Allow local libraries
33
 
34
use Utils;
35
use StdLogger;                                  # Log to sdtout
36
use Logger;                                     # Log to file
37
 
38
#
39
#   Database interface
40
#   Pinched from jats and modified so that this software is not dependent on JATS
41
#
42
use IO::Handle;
43
use JatsRmApi;
44
use DBI;
45
 
46
#
47
#   Globals
48
#
49
my $logger = StdLogger->new();                  # Stdout logger. Only during config
50
$logger->err("No config file specified") unless (defined $ARGV[0]);
51
$logger->err("Config File does not exist: $ARGV[0]") unless (-f $ARGV[0]);
52
my $name = basename( $ARGV[0]);
53
   $name =~ s~.conf$~~;
54
my $now = 0;
55
my $startTime = 0;
56
my $tagDirTime = 0;
57
my $lastDirScan = 0;
58
my $lastS3Refresh =  0;
59
my $lastTagListUpdate = 0;
60
my $mtimeConfig = 0;
61
my $conf;
62
my $yday = -1;
63
my $linkUp = 1;
64
my $RM_DB;
65
my $activeReleases;
66
 
67
#
68
#   Contain statisics maintained while operating
69
#       Can be dumped with a kill -USR2
70
#       List here for documentation
71
#  
72
 
73
my %statistics = (
74
    SeqNum => 0,                        # Bumped when $statistics are dumped
75
    timeStamp => 0,                     # DateTime when statistics are dumped
76
    upTime => 0,                        # Seconds since program start
77
    Cycle => 0,                         # Major process loop counter
78
    phase => 'Init',                    # Current phase of operation
79
    state => 'OK',                      # Nagios state
80
                                        # 
81
                                        # The following are reset each day
82
    dayStart => 0,                      # DateTime when daily data was reset
83
    txCount => 0,                       # Packages Transferred
84
    delCount => 0,                      # Packages marked for deletion
85
    linkErrors => 0,                    # Transfer (S3) errors
86
                                        # 
87
                                        # Per Cycle Data - Calculated each processing Cycle
88
);
89
 
90
#
91
#   Describe configuration parameters
92
#
93
my %cdata = (
94
    'piddir'          => {'mandatory' => 1      , 'fmt' => 'dir'},
95
    'sleep'           => {'default'   => 5      , 'fmt' => 'period'},
96
    'sleepLinkDown'   => {'default'   => '1m'   , 'fmt' => 'period'},
97
    'dpkg_archive'    => {'mandatory' => 1      , 'fmt' => 'dir'},
98
    'logfile'         => {'mandatory' => 1      , 'fmt' => 'vfile'},
99
    'logfile.size'    => {'default'   => '1M'   , 'fmt' => 'size'},
100
    'logfile.count'   => {'default'   => 9      , 'fmt' => 'int'},
101
 
102
    'verbose'         => {'default'   => 0      , 'fmt' => 'int'},                  # Debug ...
103
    'active'          => {'default'   => 1      , 'fmt' => 'bool'},                 # Disable alltogether
104
    'debug'           => {'default'   => 0      , 'fmt' => 'bool'},                 # Log to screen
105
    'txdetail'        => {'default'   => 0      , 'fmt' => 'bool'},                 # Show transfer times
106
    'noTransfers'     => {'default'   => 0      , 'fmt' => 'bool'},                 # Debugging option to prevent transfers
107
 
108
    'tagdir'          => {'mandatory' => 1      , 'fmt' => 'dir'},
109
    'workdir'         => {'mandatory' => 1      , 'fmt' => 'dir'},
110
    'forcedirscan'    => {'default'   => 100    , 'fmt' => 'period'},
111
    'forces3update'   => {'default'   => '30m'  , 'fmt' => 'period'},
112
    'tagListUpdate'   => {'default'   => '1h'   , 'fmt' => 'period'},
113
    'S3Bucket'        => {'mandatory' => 1      , 'fmt' => 'text'},
114
    'S3Profile'       => {'mandatory' => 1      , 'fmt' => 'text'},
115
 
116
);
117
 
118
 
119
#
120
#   Read in the configuration
121
#       Set up a logger
122
#       Write a pidfile - thats not used
123
$now = $startTime = time();
124
readConfig();
125
Utils::writepid($conf);
126
$logger->logmsg("Starting...");
127
readStatistics();
128
sighandlers($conf);
129
 
130
#
131
#   Main processing loop
132
#   Will exit when terminated by parent
133
#
134
while (1)
135
{
136
    $logger->verbose3("Processing");
137
    $statistics{Cycle}++;
138
    $now = time();
139
 
140
    $statistics{phase} = 'ReadConfig';
141
    readConfig();
142
    if ( $conf->{'active'} )
143
    {
144
        $statistics{phase} = 'Refresh S3 Info';
145
        refreshS3Info();
146
        if( $linkUp )
147
        {
148
            $statistics{phase} = 'Monitor Requests';
149
            monitorRequests();
150
 
151
            $statistics{phase} = 'maintainTagList';
152
            maintainTagList();
153
        }
154
    }
155
 
156
    $statistics{phase} = 'Sleep';
157
    sleep( $linkUp ? $conf->{'sleep'} : $conf->{'sleepLinkDown'} );
158
    reapChildren();
159
 
160
    #   If my PID file ceases to be, then exit the daemon
161
    #   Used to force daemon to restart
162
    #
163
    unless ( -f $conf->{'pidfile'} )
164
    {
165
        $logger->logmsg("Terminate. Pid file removed");
166
        last;
167
    }
168
}
169
$statistics{phase} = 'Terminated';
170
$logger->logmsg("Child End");
171
exit 0;
172
 
173
#-------------------------------------------------------------------------------
174
# Function        : reapChildren 
175
#
176
# Description     : Reap any and all dead children
177
#                   Call in major loops to prevent zombies accumulating 
178
#
179
# Inputs          : None
180
#
181
# Returns         : 
182
#
183
sub reapChildren
184
{
185
    my $currentPhase = $statistics{phase};
186
    $statistics{phase} = 'Reaping';
187
 
188
    my $kid;
189
    do {
190
        $kid = waitpid(-1, WNOHANG);
191
    } while ( $kid > 0 );
192
 
193
    $statistics{phase} = $currentPhase;
194
}
195
 
196
 
197
#-------------------------------------------------------------------------------
198
# Function        : readConfig
199
#
200
# Description     : Re read the config file if it modification time has changed
201
#
202
# Inputs          : Nothing
203
#
204
# Returns         : 0       - Config not read
205
#                   1       - Config read
206
#                             Config file has changed
207
#
208
sub readConfig
209
{
210
    my ($mtime) = Utils::mtime($ARGV[0]);
211
    my $rv = 0;
212
 
213
    if ( $mtimeConfig != $mtime )
214
    {
215
        $logger->logmsg("Reading config file: $ARGV[0]");
216
        $mtimeConfig = $mtime;
217
        my $errors;
218
        ($conf, $errors) = Utils::readconf ( $ARGV[0], \%cdata );
219
        if ( scalar @{$errors} > 0 )
220
        {
221
            warn "$_\n" foreach (@{$errors});
222
            die ("Config contained errors\n");
223
        }
224
 
225
        #
226
        #   Reset some information
227
        #   Create a new logger
228
        #
229
        $logger = Logger->new($conf) unless $conf->{debug};
230
        $conf->{logger} = $logger;
231
        $conf->{'pidfile'} = $conf->{'piddir'} . '/' . $name . '.pid';
232
        $logger->setVerbose($conf->{verbose});
233
        $logger->verbose("Log Levl: $conf->{verbose}");
234
 
235
        #
236
        #   Setup statistics filename
237
        $conf->{'statsfile'} = $conf->{'piddir'} . '/' . $name . '.stats';
238
        $conf->{'statsfiletmp'} = $conf->{'piddir'} . '/' . $name . '.stats.tmp';
239
 
240
        #
241
        #   When config is read force some actions
242
        #       - Force tagList to be created
243
        #       - Force refresh from S3
244
        $lastTagListUpdate = 0;
245
        $lastS3Refresh = 0;
246
    }
247
 
248
    #
249
    #   When config is read force some actions
250
 
251
#Utils::DebugDumpData ("Config", $conf);
252
 
253
    $logger->warn("All Transfers disabled") if ( $conf->{'noTransfers'} );
254
    $logger->warn("S3Sync is inactive") unless ( $conf->{'active'} );
255
    return $rv;
256
}
257
 
258
#-------------------------------------------------------------------------------
259
# Function        : refreshS3Info 
260
#
261
# Description     : At startup, and at time after startup examine the S3 bucket
262
#                   and recover information from it 
263
#
264
# Inputs          : 
265
#
266
# Returns         : 0 - Gross error ( Bucket access) 
267
#
268
sub refreshS3Info
269
{
270
    my $rv = 1;
271
    if ( !$linkUp || ($now > ($lastS3Refresh + $conf->{'forces3update'})) )
272
    {
273
        $logger->verbose2("refreshS3Info");
274
        $lastS3Refresh = $now;
275
 
276
        #
277
        #   Examine the s3 bucket and extract useful information
278
        #
279
        my $startTime = time;
280
        $linkUp = 1;
281
        $rv =  examineS3Bucket();
282
         unless ($rv) {
283
            $statistics{linkErrors}++;
284
            $linkUp = 0;
285
         }
286
 
287
         #
288
         #   Display the duration of the refresh
289
         #       Diagnostic use
290
         #
291
         if ($conf->{txdetail}) {
292
             my $duration = time - $startTime;
293
             $logger->logmsg("refreshS3Info: Stats: $duration Secs");
294
         }
295
 
296
    }
297
    return $rv;
298
}
299
 
300
 
301
 
302
#-------------------------------------------------------------------------------
303
# Function        : monitorRequests
304
#
305
# Description     : Monitor S3Sync requests
306
#                   This is simply done my polling Release Manager - at the moment
307
#
308
# Inputs          : None
309
#
310
# Returns         : Nothing
311
#
312
sub monitorRequests
313
{
314
    #
315
    #   Determine if new tags are present by examining the time
316
    #   that the directory was last modified.
317
    #
318
    #   Allow for a forced scan to catch packages that did not transfer
319
    #   on the first attempt
320
    #
321
    my $tagCount = 0;
322
    my ($mtime) = Utils::mtime($conf->{'tagdir'} );
323
    if ( ($mtime > $tagDirTime) || ($now > ($lastDirScan + $conf->{'forcedirscan'})) )
324
    {
325
        $logger->verbose2("monitorRequests: $conf->{'tagdir'}");
326
        #$logger->verbose2("monitorRequests: mtime:" . ($mtime > $tagDirTime));
327
        #$logger->verbose2("monitorRequests: last:" . ($now > ($lastDirScan + $conf->{'forcedirscan'})));
328
 
329
        #
330
        #   Package tags information is not really used
331
        #       Just delete all the tags
332
        #       Used to trigger the scan - rather than rely on the slow data
333
        #       base poll. Still need a change in release sequence number
334
        #   
335
        my $dh;
336
        unless (opendir($dh, $conf->{'tagdir'}))
337
        {
338
            $logger->warn ("can't opendir $conf->{'tagdir'}: $!");
339
            return;
340
        }
341
 
342
        #
343
        #   Process each entry
344
        #       Ignore those that start with a .
345
        #       Remove all files
346
        #
347
        while (my $tag = readdir($dh) )
348
        {
349
            next if ( $tag =~ m~^\.~ );
350
            my $file = "$conf->{'tagdir'}/$tag";
351
            $logger->verbose3("processTags: $file");
352
 
353
            next unless ( -f $file );
354
            unlink $file;
355
        }
356
 
357
        #
358
        #   Reset the scan time triggers
359
        #   
360
        $tagDirTime = $mtime;
361
        $lastDirScan = $now;
362
 
363
        #
364
        #   Examine Release Manager looking for active releases that have S3Sync support
365
        #   Purpose is to:
366
        #       Detect new Releases
367
        #       Detect dead Releases
368
        #       Detect changed Releases
369
        #
370
        connectRM(\$RM_DB, $conf->{verbose} > 3);
371
 
372
        foreach my $rtag_id (keys %{$activeReleases}) {
373
            $activeReleases->{$rtag_id}{exists} = 0;
374
        }
375
        my $m_sqlstr = "SELECT rt.rtag_id,rm.seqnum, rt.s3sync, rt.official, rm.timestamp " . 
376
                       "FROM RELEASE_MANAGER.release_tags rt, RELEASE_MANAGER.release_modified rm " .
377
                       "WHERE rt.s3sync = 'Y' AND rm.rtag_id = rt.rtag_id AND rt.official in ('N', 'R', 'C')";
378
 
379
        my $curData = getDataFromRm ('monitorRequests', $m_sqlstr, {data => 0} );
380
        foreach my $entry (@{$curData}) {
381
            my ($rtag_id, $seqnum) = @{$entry};
382
 
383
            if (! exists $activeReleases->{$rtag_id} || ! exists $activeReleases->{$rtag_id}{s3}  ) {
384
                $logger->logmsg("New Release Detected. rtag_id: $rtag_id, seq:$seqnum");
385
                processChangedRelease($rtag_id, $seqnum);
386
                $lastTagListUpdate = 0;
387
 
388
            } elsif (($activeReleases->{$rtag_id}{seqnum} || 0) ne ($seqnum || 0) ) {
389
                $logger->logmsg("Change Release Detected. rtag_id: $rtag_id, seq:$seqnum");
390
                processChangedRelease($rtag_id, $seqnum);
391
            }
392
 
393
            # Update activeReleases so that changes will be detected
394
            $activeReleases->{$rtag_id}{exists} = 1;
395
        }
396
 
397
        # Detect Releases that are no longer active
398
        foreach my $rtag_id (keys %{$activeReleases}) {
399
            unless ($activeReleases->{$rtag_id}{exists}) {
400
                $logger->logmsg("Dead Release Detected. rtag_id: $rtag_id");
401
                removeDeadRelease($rtag_id);
402
                delete $activeReleases->{$rtag_id};
403
                $lastTagListUpdate = 0;
404
            }
405
        }
406
 
407
        disconnectRM(\$RM_DB);
408
    }
409
}
410
 
411
#-------------------------------------------------------------------------------
412
# Function        : examineS3Bucket 
413
#
414
# Description     : Scan the S3 bucket looking for Releases
415
#                   Used to pre-populate the process so that we:
416
#                       - Delete dead releases
417
#                       - Don't do excessive work on startup
418
#                       
419
# Inputs          : Nothing 
420
#
421
# Returns         : Updates global structure ($activeReleases) 
422
# Returns         : 0 - Gross error ( Bucket access) 
423
#
424
sub examineS3Bucket
425
{
426
    #
427
    #   Remove data collected from s3
428
    #
429
    foreach my $rtag_id (keys %{$activeReleases}) {
430
        delete $activeReleases->{$rtag_id}{s3}  ;
431
    }
432
 
433
    $conf->{'S3Bucket'} =~ m~(.*?)/(.*)~;
434
    my $bucket = $1;
435
    my $prefix = $2;
436
 
437
    my $s3_cmd = "aws --profile $conf->{'S3Profile'} s3api list-objects --bucket $bucket --prefix $prefix";
438
    $logger->verbose2("examineS3Bucket:s3_cmd:$s3_cmd");
439
 
440
    my $ph;
441
    my $jsontxt = "";
442
    open ($ph, "$s3_cmd |");
443
    while ( <$ph> ) {
444
        chomp;
445
        $logger->verbose3("examineS3Bucket:Data: $_");
446
        $jsontxt .= $_;
447
    }
448
    close ($ph);
449
    my $cmdRv = $?;
450
    if ($cmdRv != 0) {
451
        $logger->warn("Cannot read S3 Bucket Data");
452
        return 0;
453
    }
454
 
455
    if ($jsontxt) {
456
        my $json = from_json ($jsontxt);
457
        #Utils::DebugDumpData("JSON",$json->{'Contents'});
458
        foreach my $item ( @{$json->{'Contents'}})
459
        {
460
            if ($item->{Key} =~ m~/Release-(.*)\.zip$~ ) {
461
 
462
                my $rtag_id = $1;
463
                my $metaData = gets3ObjectMetaData($item->{Key});
464
 
465
                #
466
                #   Update info in the global structure ($activeReleases)
467
                #   This data could be discarded - only needed for diagnostics   
468
                #
469
                $activeReleases->{$rtag_id}{s3}{seqnum} = $metaData->{'releaseseq'};   
470
                $activeReleases->{$rtag_id}{s3}{md5}    = $metaData->{'md5'};   
471
                $activeReleases->{$rtag_id}{s3}{depsig} = $metaData->{'depsig'};
472
 
473
                #
474
                #   Recover information from S3
475
                #   Should only be done on the first call after restart
476
                #   
477
                if (! exists $activeReleases->{$rtag_id}{md5} ) {
478
                    $activeReleases->{$rtag_id}{md5} = $activeReleases->{$rtag_id}{s3}{md5};
479
                    $activeReleases->{$rtag_id}{depsig} = $activeReleases->{$rtag_id}{s3}{depsig};
480
                }
481
 
482
 
483
            } else {
484
                $logger->warn("Unknown item in bucket: $item->{Key}");
485
            }
486
        }
487
    }
488
#Utils::DebugDumpData("activeReleases",$activeReleases);
489
    return 1;
490
}
491
 
492
#-------------------------------------------------------------------------------
493
# Function        : gets3ObjectMetaData 
494
#
495
# Description     : Get Metadata about one object
496
#                   Must do object by object :( 
497
#
498
# Inputs          : $key    - Key 
499
#
500
# Returns         : 
501
#
502
 
503
sub gets3ObjectMetaData
504
{
505
    my ($key) = @_;
506
 
507
    $conf->{'S3Bucket'} =~ m~(.*?)/(.*)~;
508
    my $bucket = $1;
509
    my $prefix = $2;
510
 
511
    my $s3_cmd = "aws --profile $conf->{'S3Profile'} s3api head-object --bucket $bucket --key $key";
512
    $logger->verbose2("gets3ObjectMetaData:s3_cmd:$s3_cmd");
513
 
514
    my $ph;
515
    my $jsontxt = "";
516
    open ($ph, "$s3_cmd |");
517
    while ( <$ph> ) {
518
        chomp;
519
        $logger->verbose3("gets3ObjectMetaData:Data: $_");
520
        $jsontxt .= $_;
521
    }
522
    close ($ph);
523
 
524
    my $json;
525
    $json->{Metadata} = {};
526
 
527
    if ($jsontxt) {
528
        $json = from_json ($jsontxt);
529
        #Utils::DebugDumpData("JSON",$json);
530
    }
531
    return $json->{Metadata};
532
}
533
 
534
 
535
#-------------------------------------------------------------------------------
536
# Function        : removeDeadRelease 
537
#
538
# Description     : Remove a Dead Release from the S3 bucket 
539
#
540
# Inputs          : $rtag_id    - Release identifier 
541
#
542
# Returns         : 0   - Nothing deleted
543
#                   1   - Something deleted 
544
#
545
sub removeDeadRelease {
546
    my ($rtag_id) = @_;
547
    my $cmdRv;
548
    my $rv = 0;
549
 
550
    #   Create the process pipe to delete the package
551
 
552
    my $targetPath = generateBucketZipName($rtag_id);
553
    my $s3_cmd = "aws --profile $conf->{'S3Profile'} s3 rm s3://$targetPath";
554
    $logger->logmsg("removeDeadRelease:$targetPath");
555
    $logger->verbose2("removeDeadRelease:s3_cmd:$s3_cmd");
556
 
557
    my $ph;
558
    open ($ph, "$s3_cmd |");
559
    while ( <$ph> ) {
560
        chomp;
561
        $logger->verbose2("removeDeadRelease:Data: $_");
562
    }
563
    close ($ph);
564
    $cmdRv = $?;
565
 
566
    #
567
    #   Common code
568
    #
569
    $logger->verbose("removeDeadRelease:End: $cmdRv");
570
    if ( $cmdRv == 0 ) {
571
        $rv = 1;
572
        $statistics{delCount}++;
573
 
574
    } else {
575
        $logger->warn("removeDeadRelease:Error: $rtag_id, $?");
576
    }
577
    return $rv;
578
}
579
 
580
#-------------------------------------------------------------------------------
581
# Function        : processChangedRelease 
582
#
583
# Description     : Create/Update a release to the S3 bucket
584
# 
585
#   Various attempts are made to reduce the work that needs to be done
586
#   There are three checks to skip a transfer
587
#       1) The Release sequence number - must be diff for processing to occur
588
#       2) Packages inserted into the image
589
#           Dependent package versions are used to generate a MD5
590
#           If this does not change then there is no need to do work
591
#       3) An MD5 over the zip Image
592
#          If this is the same as the one in S3, then don't upload
593
#          
594
#   These three pices of information are held as metadata along with the
595
#   package. These are read at start up.
596
#
597
#
598
# Inputs          : $rtag_id    - Release identifier
599
#                   $seqnum     - Release sequence number
600
#                                 Added as metadata to objects 
601
#
602
# Returns         : Nothing 
603
#
604
sub processChangedRelease {
605
    my ($rtag_id, $seqnum) = @_;
606
 
607
    #
608
    #   Cleanout previous zip files
609
    #   
610
    my @files = glob($conf->{'workdir'} . '/*.zip');
611
    $logger->verbose("Delete old zips: @files");
612
    unlink @files;
613
 
614
    #
615
    #   Create an image of the data to be transferred
616
    #   Based on packages that support S3Sync
617
    #   
618
    my $m_sqlstr = "SELECT p.pkg_name, pv.pkg_version, pv.pv_id " .
619
                   " FROM RELEASE_MANAGER.release_content rc, RELEASE_MANAGER.packages p, RELEASE_MANAGER.package_versions  pv " .
620
                    " WHERE rc.rtag_id = " . $rtag_id .
621
                    "      AND rc.s3sync = 'Y' " .
622
                    "      AND rc.pv_id = pv.pv_id " .
623
                    "      AND pv.pkg_id = p.pkg_id " .
624
                    " ORDER by pv.pv_id";
625
 
626
    my $curData = getDataFromRm ('s3Pkgs', $m_sqlstr, {data => 0, dump => 0} );
627
#Utils::DebugDumpData("activeReleases",$activeReleases);
628
 
629
    #
630
    #   Generate a md5 of the PVIDs of the packages that will go into the image
631
    #   Used to detect true changes - only of the packages we are interested in
632
    #   
633
    my $signature = Digest::MD5->new;
634
    foreach my $entry (@{$curData}) {
635
        $signature->add( $entry->[2] )
636
    }
637
    my $depsig = $signature->hexdigest();
638
    my $reason = "";
639
    if ( !exists $activeReleases->{$rtag_id}{s3} ) {
640
        $reason = 'NoS3Data';
641
 
642
    } elsif (! exists $activeReleases->{$rtag_id}{depsig}) {
643
        $reason = 'NoSavedData';
644
 
645
    } elsif ($activeReleases->{$rtag_id}{depsig} ne $depsig ) {
646
        $reason = "Mismatch: $activeReleases->{$rtag_id}{depsig} ne $depsig";
647
 
648
    } else {
649
        $logger->verbose("Dependencies unchanged - upload skipped");
650
        $activeReleases->{$rtag_id}{seqnum} = $seqnum;
651
        return;
652
    }
653
    $logger->verbose("Dependency Test: $reason");
654
 
655
    #
656
    #   Generate the zip of the obejcets to be pushed to S3
657
    #
658
    my $startTime = time;
659
    my $zip = Archive::Zip->new();
660
    foreach my $entry (@{$curData}) {
661
        my $src = getPackageBase($entry->[0], $entry->[1]);
662
        if (defined $src) {
663
            $logger->verbose("Zip addTree Src: $src");
664
 
665
            if ( $zip->addTree( $src, '' ) != AZ_OK ) {
666
                $logger->warn("Zip addTree Error: $rtag_id");
667
                return;
668
            }
669
        }
670
    }
671
 
672
    my $zipFile = catdir( $conf->{'workdir'} , 'Images-' . $rtag_id . '.zip');
673
    if ( $zip->writeToFileNamed($zipFile) != AZ_OK ) {
674
        $logger->warn("Zip write Error: $rtag_id");
675
        return;
676
    }
677
    $logger->verbose("Zip created: $zipFile");
678
 
679
    #
680
    #   Display the size of the package (zipped)
681
    #       Diagnostic use
682
    #
683
    if ($conf->{txdetail}) {
684
        my $tzfsize = -s $zipFile;
685
        my $size = sprintf "%.3f", $tzfsize / 1024 / 1024 / 1024 ;
686
        my $duration = time - $startTime;
687
        $logger->logmsg("zipImage: Stats: $rtag_id, $size Gb, $duration Secs");
688
    }
689
 
690
    #
691
    #   Have a ZIP file of the desired contents
692
    #   Could try to detect if it differs from the one already in the bucket
693
    #       Don't want to trigger CI/CD pipeline operations unless we need to
694
    #       
695
    my $digest = md5_hex($zipFile);
696
    $reason = "";
697
    if ( !exists $activeReleases->{$rtag_id}{s3} ) {
698
        $reason = 'NoS3Data';
699
 
700
    } elsif (! exists $activeReleases->{$rtag_id}{md5}) {
701
        $reason = 'NoSavedMd5';
702
 
703
    } elsif ($activeReleases->{$rtag_id}{md5} ne $digest ) {
704
        $reason = "Mismatch: $activeReleases->{$rtag_id}{md5} ne $digest";
705
 
706
    } else {
707
        $logger->verbose("Zip file has same md5 hash - upload skipped");
708
        #
709
        #   Update the known signature
710
        $activeReleases->{$rtag_id}{depsig} = $depsig;
711
        $activeReleases->{$rtag_id}{seqnum} = $seqnum;
712
        $activeReleases->{$rtag_id}{md5} = $digest;
713
        return;
714
    }
715
    $logger->verbose("ZipMd5 Test: $reason");
716
 
717
    #   Create a command to transfer the file to AWS use the cli tools
718
    #   Note: Ive seen problem with this when used from Perth to AWS (Sydney)
719
    #         If this is an issue use curl - see the savePkgToS3.sh for an implementation
720
    #
721
    $startTime = time;
722
    my $targetPath = generateBucketZipName($rtag_id);
723
    my $s3_cmd = "aws --profile $conf->{'S3Profile'} s3 cp $zipFile s3://$targetPath --metadata releaseseq=$seqnum,md5=$digest,depsig=$depsig";
724
    $logger->logmsg("transferPackage:$targetPath");
725
    $logger->verbose2("transferPackage:s3_cmd:$s3_cmd");
726
 
727
    my $cmdRv;
728
    unless ($conf->{'noTransfers'}) {
729
        my $ph;
730
        open ($ph, "$s3_cmd |");
731
        while ( <$ph> )
732
        {
733
            chomp;
734
            $logger->verbose2("transferPackage:Data: $_");
735
        }
736
        close ($ph);
737
        $cmdRv = $?;
738
        $logger->verbose("transferPackage:End: $cmdRv");
739
    }
740
    #
741
    #   Display the size of the package (zipped)
742
    #       Diagnostic use
743
    #
744
    if ($conf->{txdetail}) {
745
        my $tzfsize = -s $zipFile;
746
        my $size = sprintf "%.3f", $tzfsize / 1024 / 1024 / 1024 ;
747
        my $duration = time - $startTime;
748
        $logger->logmsg("S3 Copy: Stats: $rtag_id, $size Gb, $duration Secs");
749
    }
750
 
751
    if ($cmdRv == 0) {
752
        $statistics{txCount}++;
753
 
754
        #
755
        #   Mark the current entry as having been processed
756
        #
757
        $activeReleases->{$rtag_id}{depsig} = $depsig;
758
        $activeReleases->{$rtag_id}{md5} = $digest;
759
        $activeReleases->{$rtag_id}{seqnum} = $seqnum;
760
        $activeReleases->{$rtag_id}{s3}{sent} = 1;
761
    }
762
}
763
 
764
#-------------------------------------------------------------------------------
765
# Function        : getPackageBase 
766
#
767
# Description     : Calculate the base of a package in dpkg_archive
768
#                   With errors and wanings
769
#
770
# Inputs          : $pname      - Package name
771
#                   $pver       - Package version
772
#
773
#
774
# Returns         : undef - bad
775
#                   Path to the S3TRANSFER section within the archive
776
sub getPackageBase {
777
    my ($pname, $pver) = @_;
778
 
779
    #
780
    #   Locate package
781
    #
782
    unless ( -d $conf->{'dpkg_archive'}) {
783
        $logger->warn("addPartsToImage: dpkg_archive not found");
784
        return undef;
785
    }
786
 
787
    my $src = catdir($conf->{'dpkg_archive'}, $pname, $pver);
788
    unless ( -d $src ) {
789
        $logger->warn("addPartsToImage: Package not found: $pname, $pver");
790
        return undef;
791
    }
792
 
793
    #$src = catdir( $src, 'pkg', 'S3TRANSFER');
794
    $src = catdir( $src, 'bin');
795
    unless ( -d $src ) {
796
        $logger->verbose("addPartsToImage: Package has no pkg/S3TRANSFER: $pname, $pver");
797
        return undef;
798
    }
799
    return $src;
800
}
801
 
802
#-------------------------------------------------------------------------------
803
# Function        : generateBucketZipName 
804
#
805
# Description     : Generate the name of the zipfile created within the bucket  
806
#
807
# Inputs          : $rtag_id 
808
#
809
# Returns         : Full name - including bucket name
810
#
811
sub generateBucketZipName
812
{
813
    my ($rtag_id) = @_;
814
    my $targetName = 'Release-' . $rtag_id . '.zip';
815
    my $targetPath = catdir ($conf->{'S3Bucket'}, $targetName );
816
    return $targetPath;
817
}
818
 
819
 
820
#-------------------------------------------------------------------------------
821
# Function        : getDataFromRm 
822
#
823
# Description     : Get an array of data from RM
824
#                   Normally an array of arrays 
825
#
826
# Inputs          : $name           - Query Name
827
#                   $m_sqlstr       - Query
828
#                   $options        - Ref to a hash of options
829
#                                       sql     - show sql
830
#                                       data    - show data
831
#                                       dump    - show results
832
#                                       oneRow  - Only fetch one row
833
#                                       error   - Must find data
834
#                                       
835
# Returns         : ref to array of data
836
#
837
sub getDataFromRm
838
{
839
    my ($name,$m_sqlstr, $options ) = @_;
840
    my @row;
841
    my $data;
842
 
843
    if (ref $options ne 'HASH') {
844
        $options = {}; 
845
    }
846
 
847
    if ($options->{sql}) {
848
        $logger->logmsg("$name: $m_sqlstr")
849
    }
850
    my $sth = $RM_DB->prepare($m_sqlstr);
851
    if ( defined($sth) )
852
    {
853
        if ( $sth->execute( ) ) {
854
            if ( $sth->rows ) {
855
                while ( @row = $sth->fetchrow_array ) {
856
                    if ($options->{data}) {
857
                        $logger->warn ("$name: @row");
858
                    }
859
                    #Debug0("$name: @row");
860
                    push @{$data}, [@row];
861
 
862
                    last if $options->{oneRow};
863
                }
864
            }
865
            $sth->finish();
866
        } else {
867
            $logger->warn("Execute failure:$name: $m_sqlstr", $sth->errstr() );
868
        }
869
    } else {
870
        $logger->warn("Prepare failure:$name" );
871
    }
872
 
873
    if (!$data && $options->{error}) {
874
        $logger->warn( $options->{error} );
875
    }
876
 
877
    if ($data && $options->{oneRow}) {
878
        $data = $data->[0];
879
    }
880
 
881
    if ($options->{dump}) {
882
        Utils::DebugDumpData("$name", $data);
883
    }
884
    return $data;
885
}
886
 
887
#-------------------------------------------------------------------------------
888
# Function        : maintainTagList
889
#
890
# Description     : Maintain a data structure for the maintenance of the
891
#                   tags directory
892
#
893
# Inputs          : None
894
#
895
# Returns         : Nothing
896
#
897
sub maintainTagList
898
{
899
    #
900
    #   Time to perform the scan
901
    #   Will do at startup and every time period there after
902
    #
903
    return unless ( $now > ($lastTagListUpdate + $conf->{tagListUpdate} ));
904
    $logger->verbose("maintainTagList");
905
    $lastTagListUpdate = $now;
906
 
907
    #
908
    #   Generate new configuration
909
    #
910
    my %config;
911
    $config{s3Sync} = 1;                # Indicate that it may be special
912
 
913
    %{$config{releases}} = map { $_ => 1 } keys %{$activeReleases};
914
 
915
    #
916
    #   Save data
917
    #
918
    my $dump =  Data::Dumper->new([\%config], [qw(*config)]);
919
#print $dump->Dump;
920
#$dump->Reset;
921
 
922
    #
923
    #   Save config data
924
    #
925
    my $conf_file = catfile( $conf->{'tagdir'},'.config' );
926
    $logger->verbose3("maintainTagList: Writting $conf_file");
927
 
928
    my $fh;
929
    open ( $fh, '>', $conf_file ) or $logger->err("Can't create $conf_file: $!");
930
    print $fh $dump->Dump;
931
    close $fh;
932
}
933
 
934
#-------------------------------------------------------------------------------
935
# Function        : resetDailyStatistics 
936
#
937
# Description     : Called periodically to reset the daily statistics
938
#
939
# Inputs          : $time       - Current time
940
#
941
# Returns         : 
942
#
943
sub resetDailyStatistics
944
{
945
    my ($time) = @_;
946
 
947
    #
948
    #   Detect a new day
949
    #
950
    my $today = (localtime($time))[7];
951
    if ($yday != $today)
952
    {
953
        $yday = $today;
954
        $logger->logmsg('Resetting daily statistics' );
955
 
956
        # Note: Must match @recoverTags in readStatistics
957
        $statistics{dayStart} = $time;
958
        $statistics{txCount} = 0;
959
        $statistics{delCount} = 0;
960
        $statistics{linkErrors} = 0;
961
    }
962
}
963
 
964
#-------------------------------------------------------------------------------
965
# Function        : readStatistics 
966
#
967
# Description     : Read in the last set of stats
968
#                   Used after a restart to recover daily statistics
969
#
970
# Inputs          : 
971
#
972
# Returns         : 
973
#
974
sub readStatistics
975
{
976
    my @recoverTags = qw(dayStart txCount delCount linkErrors);
977
 
978
    if ($conf->{'statsfile'} and -f $conf->{'statsfile'})
979
    {
980
        if (open my $fh, $conf->{'statsfile'})
981
        {
982
            while (<$fh>)
983
            {
984
                m~(.*):(.*)~;
985
                if ( grep( /^$1$/, @recoverTags ) ) 
986
                {
987
                    $statistics{$1} = $2;
988
                    $logger->verbose("readStatistics $1, $2");
989
                }
990
            }
991
            close $fh;
992
            $yday = (localtime($statistics{dayStart}))[7];
993
        }
994
    }
995
}
996
 
997
 
998
#-------------------------------------------------------------------------------
999
# Function        : periodicStatistics 
1000
#
1001
# Description     : Called on a regular basis to write out statistics
1002
#                   Used to feed information into Nagios
1003
#                   
1004
#                   This function is called via an alarm and may be outside the normal
1005
#                   processing loop. Don't make assumptions on the value of $now
1006
#
1007
# Inputs          : 
1008
#
1009
# Returns         : 
1010
#
1011
sub periodicStatistics
1012
{
1013
    #
1014
    #   A few local stats
1015
    #
1016
    $statistics{SeqNum}++;
1017
    $statistics{timeStamp} = time();
1018
    $statistics{upTime} = $statistics{timeStamp} - $startTime;
1019
 
1020
    #   Reset daily accumulations - on first use each day
1021
    resetDailyStatistics($statistics{timeStamp});
1022
 
1023
    #
1024
    #   Write statistics to a file
1025
    #       Write to a tmp file, then rename.
1026
    #       Attempt to make the operation atomic - so that the file consumer
1027
    #       doesn't get a badly formed file.
1028
    #   
1029
    if ($conf->{'statsfiletmp'})
1030
    {
1031
        my $fh;
1032
        unless (open ($fh, '>', $conf->{'statsfiletmp'}))
1033
        {
1034
            $fh = undef;
1035
            $logger->warn("Cannot create temp stats file: $!");
1036
        }
1037
        else
1038
        {
1039
            foreach my $key ( sort { lc($a) cmp lc($b) } keys %statistics)
1040
            {
1041
                print $fh $key . ':' . $statistics{$key} . "\n";
1042
                $logger->verbose2('Statistics:'. $key . ':' . $statistics{$key});
1043
            }
1044
            close $fh;
1045
 
1046
            # Rename temp to real file
1047
            rename  $conf->{'statsfiletmp'},  $conf->{'statsfile'} ;
1048
        }
1049
    }
1050
}
1051
 
1052
#-------------------------------------------------------------------------------
1053
# Function        : sighandlers
1054
#
1055
# Description     : Install signal handlers
1056
#
1057
# Inputs          : $conf           - System config
1058
#
1059
# Returns         : Nothing
1060
#
1061
sub sighandlers
1062
{
1063
    my $conf = shift;
1064
    my $logger = $conf->{logger};
1065
 
1066
    $SIG{TERM} = sub {
1067
        # On shutdown
1068
        $logger->logmsg('Received SIGTERM. Shutting down....' );
1069
        unlink $conf->{'pidfile'} if (-f $conf->{'pidfile'});
1070
        exit 0;
1071
    };
1072
 
1073
    $SIG{HUP} = sub {
1074
        # On logrotate
1075
        $logger->logmsg('Received SIGHUP.');
1076
        $logger->rotatelog();
1077
    };
1078
 
1079
    $SIG{USR1} = sub {
1080
        # On Force Rescans
1081
        $logger->logmsg('Received SIGUSR1.');
1082
        $lastTagListUpdate = 0;
1083
        $lastS3Refresh = 0;
1084
    };
1085
 
1086
    alarm 60;
1087
    $SIG{ALRM} = sub {
1088
        # On Dump Statistics
1089
        $logger->verbose2('Received SIGUSR2.');
1090
        periodicStatistics();
1091
        alarm 60;
1092
    };
1093
 
1094
    $SIG{__WARN__} = sub { $logger->warn("@_") };
1095
    $SIG{__DIE__} = sub { $logger->err("@_") };
1096
}
1097
 
1098
 
1099
#-------------------------------------------------------------------------------
1100
# Function        : Error, Verbose, Warning
1101
#
1102
# Description     : Support for JatsRmApi
1103
#
1104
# Inputs          : Message
1105
#
1106
# Returns         : Nothing
1107
#
1108
sub Error
1109
{
1110
    $logger->err("@_");
1111
}
1112
 
1113
sub Verbose
1114
{
1115
    $logger->verbose2("@_");
1116
}
1117
 
1118
sub Warning
1119
{
1120
    $logger->warn("@_");
1121
}
1122
 
1123