Subversion Repositories DevTools

Rev

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

Rev Author Line No. Line
6914 dpurdie 1
package com.erggroup.buildtool.ripple;
2
 
3
import java.sql.SQLException;
4
import java.util.ArrayList;
5
import java.util.Collections;
6
import java.util.Iterator;
7
import java.util.List;
8
import java.util.ListIterator;
9
 
7033 dpurdie 10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
6914 dpurdie 12
 
13
import com.erggroup.buildtool.ripple.BuildFile.BuildFileState;
14
import com.erggroup.buildtool.ripple.ReleaseManager.BuildReason;
15
import com.erggroup.buildtool.smtp.CreateUrls;
16
import com.erggroup.buildtool.smtp.Smtpsend;
17
import com.erggroup.buildtool.utilities.StringAppender;
18
import com.erggroup.buildtool.utilities.XmlBuilder;
19
 
20
/**Plans release impact by generating a set of Strings containing build file content.
21
 */
22
public class RippleEngine
23
{
24
 
25
    /**configured mail server
26
     * @attribute
27
     */
28
    private String mMailServer = "";
29
 
30
    /**configured mail sender user
31
     * @attribute
32
     */
33
    private String mMailSender = "";
34
 
35
    /**configured global email target
36
     * @attribute
37
     */
38
    private String mMailGlobalTarget = "";
39
 
40
    /** Vector of email addresses for global and project wide use
41
     *  Most emails will be sent to this list of email recipients
42
     */
43
    public List<String> mMailGlobalCollection = new ArrayList<String>();
44
 
45
    /**name associated with the baseline
46
     * @attribute
47
     */
48
    public String mBaselineName = "";
49
 
50
    /**Collection of build exceptions associated with the baseline
51
     * Used to determine (and report) what change in build exceptions happens as part of planRelease
52
     * Daemon centric
53
     * @aggregation shared
54
     * @attribute
55
     */
56
    ArrayList<BuildExclusion> mBuildExclusionCollection = new ArrayList<BuildExclusion>();
57
 
58
    /**Logger
59
     * @attribute
60
     */
7033 dpurdie 61
    private static final Logger mLogger = LoggerFactory.getLogger(RippleEngine.class);
6914 dpurdie 62
 
63
    /** Escrow information - commands to set up escrow
64
     * @attribute
65
     */
66
    private String mEscrowSetup;
67
 
68
    /** Escrow information - Raw data (May not be used)
69
     * @attribute
70
     */
71
    private String mEscrowRawData;
72
 
7048 dpurdie 73
    /** Collections of packages
6914 dpurdie 74
     */
75
    private ArrayList<Package> mPackageCollection = new ArrayList<Package>();
7048 dpurdie 76
    private ArrayList<Package> mPackageCollectionWip = new ArrayList<Package>();
77
    private ArrayList<Package> mPackageCollectionTest = new ArrayList<Package>();
78
    private ArrayList<Package> mPackageCollectionRipple = new ArrayList<Package>();
79
    private ArrayList<Package> mPackageCollectionAll = new ArrayList<Package>();
80
 
6914 dpurdie 81
 
82
    /**index to current String item
83
     * @attribute
84
     */
85
    private int mBuildIndex;
86
 
87
    /**Database abstraction
88
     * @attribute
89
     */
90
    ReleaseManager mReleaseManager;
91
 
92
    /**Baseline identifier (rtag_id for a release manager baseline, bom_id for deployment manager baseline)
93
     * @attribute
94
     */
95
    private int mBaseline;
96
 
97
    /** Escrow Only: SBOM_ID
98
     */
99
    private int mSbomId;
100
 
101
    /** RTAG_ID
102
     *  Set from mBaseline
103
     */
104
    private int mRtagId;
105
 
106
    /**When true, mBuildCollection contains one item based on a release manager rtag_id and contains a daemon property
107
     * When false, mBuildCollection contains at least one item based on a deployment manager bom_id
108
     * Will be accessed by the Package class to calculate its mAlias
109
     * @attribute
110
     */
111
    public boolean mDaemon;
112
 
113
    /**collection of build file content in String form
114
     * @attribute
115
     */
116
    private ArrayList<BuildFile> mBuildCollection = new ArrayList<BuildFile>();
117
 
118
    /** List of packages that we plan to build
119
     * Used to provide feedback into RM
120
     * Only the first entry is about to be built as we re-plan every cycle
121
     */
122
    private ArrayList<Package> mBuildOrder = new ArrayList  <Package>();
123
    /**Warning message
124
     * @attribute
125
     */
126
    private static final String mAnyBuildPlatforms = "Warning. The following package versions are not reproducible on any build platform: ";
127
 
128
    /**Flag to control output to standard out
129
     * @attribute
130
     */
131
    private boolean mAnyBuildPlatformsFlag = true;
132
 
133
    /**Warning message
134
     * @attribute
135
     */
136
    private static final String mAssocBuildPlatforms = "Warning. The following package versions are not reproducible on the build platforms associated with this baseline: ";
137
 
138
    /**Flag to control output to standard out
139
     * @attribute
140
     */
141
    private boolean mAssocBuildPlatformsFlag = true;
142
 
143
    /**Warning message
144
     * @attribute
145
     */
146
    private static final String mNotInBaseline = "Warning. The following package versions are not reproducible as they are directly dependent upon package versions not in the baseline: ";
147
 
148
    /**Flag to control output to standard out
149
     * @attribute
150
     */
151
    private boolean mNotInBaselineFlag = true;
152
 
153
    /**Warning message
154
     * @attribute
155
     */
156
    private static final String mDependent = "Warning. The following package versions are not reproducible as they are directly/indirectly dependent upon not reproducible package versions: ";
157
 
158
    /**Flag to control output to standard out
159
     * @attribute
160
     */
161
    private boolean mDependentFlag = true;
162
 
163
    /**Warning message
164
     * @attribute
165
     */
166
    private static final String mCircularDependency = "Warning. The following package versions are not reproducible as they have circular dependencies: ";
167
 
168
    /**Flag to control output to standard out
169
     * @attribute
170
     */
171
    private boolean mCircularDependencyFlag = true;
172
 
173
    /** String used to terminate lines
174
     * @attribute
175
     */
176
    private static final  String mlf = System.getProperty("line.separator");
177
 
178
    /** XML File Prefix
179
     */
180
    private static final String mXmlHeader = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>" + mlf;
181
 
182
    /**RippleEngine constructor
183
     * @param releaseManager  - Associated releaseManager instance
184
     * @param rtagId         - Release Identifier
185
     * @param isDaemon        - Mode of operation. False: Escrow, True: Daemon
186
     */
187
    public RippleEngine(ReleaseManager releaseManager, int rtagId, boolean isDaemon)
188
    {
7048 dpurdie 189
        mLogger.debug("RippleEngine rtag_id {} isDaemon {}", rtagId, isDaemon);
6914 dpurdie 190
        mReleaseManager = releaseManager;
191
        mBaseline = rtagId;
192
        mRtagId = rtagId;
193
        mDaemon = isDaemon;
194
        mReleaseManager.setDaemonMode(mDaemon);
195
    }
196
 
197
    /**
198
     * getRtagId
7048 dpurdie 199
     * @return The rtagId of the Release attached to this instance of the RippleEngine
6914 dpurdie 200
     */
201
    public int getRtagId()
202
    {
203
        return mRtagId;
204
    }
205
 
206
    /**Plan what is to be built
207
     * 	<br>Discards all build file content
208
     * 	<br>Generates new build file content
209
     * 
210
     * @param lastBuildActive 		- False. Daemon Mode. The last build was a dummy. 
211
     *                                This planning session may not result in a build
212
     *                              - True. Daemon Mode. The last build was not a dummy.
213
     *                                There is a very good chance that this planning session
214
     *                                will result in a build, so it is given priority to connect 
215
     *                                to the database.	
216
     */
217
    public void planRelease(final boolean lastBuildActive) throws SQLException, Exception
218
    {
7048 dpurdie 219
        mLogger.warn("planRelease mDaemon {}", mDaemon);
6914 dpurdie 220
 
221
        mBuildCollection.clear();
222
        mPackageCollection.clear();
7048 dpurdie 223
        mPackageCollectionRipple.clear();
224
        mPackageCollectionTest.clear();
225
        mPackageCollectionWip.clear();
6914 dpurdie 226
        mBuildOrder.clear();
227
        mEscrowRawData = "";
228
        mEscrowSetup = "";
229
        Phase phase = new Phase("Plan");
230
 
231
        // use finally block in planRelease to ensure the connection is released
232
        try
233
        {
234
            phase.setPhase("connectForPlanning");
235
            mReleaseManager.connectForPlanning(lastBuildActive);
236
 
237
            if ( mDaemon )
238
            {
239
                // claim the mutex
240
                mLogger.warn("planRelease claimMutex");
241
                phase.setPhase("claimMutex");
242
                mReleaseManager.claimMutex();
243
 
244
                // Populate the mBuildExclusionCollection
245
                //
246
                // Builds are either 'Directly excluded' or 'Indirectly excluded'
247
                // Direct excludes result from:
248
                //      User request
249
                //      Build failure
250
                //      Inability to build package
251
                // Indirectly excluded packages result from have a build dependency on a package
252
                // that is directly excluded.
253
                //  
254
                // In the following code we will extract from the Database all build exclusions
255
                // We will then add 'Relevant' entries to mBuildExclusionCollection
256
                // and delete, from the database those that are no longer relevant - ie indirectly excluded
257
                // items where the root cause is no longer in the set.
258
                phase.setPhase("mBuildExclusionCollection");
259
                mBuildExclusionCollection.clear();
260
                ArrayList<BuildExclusion> tempBuildExclusionCollection = new ArrayList<BuildExclusion>();
261
 
262
                mLogger.debug("planRelease queryBuildExclusions");
263
                mReleaseManager.queryBuildExclusions(tempBuildExclusionCollection, mBaseline);
264
 
265
                // only populate mBuildExclusionCollection with tempBuildExclusionCollection entries which have a relevant root_pv_id
266
                // The entry is relevant if:
267
                //     It is for a directly excluded package,other than a RippleStop
268
                //     It is for an indirectly excluded package AND the reason for exclusion still exists
269
                //
270
 
271
                for (Iterator<BuildExclusion> it = tempBuildExclusionCollection.iterator(); it.hasNext(); )
272
                {
273
                    BuildExclusion buildExclusion = it.next();
274
 
275
                    if ( buildExclusion.isRelevant(tempBuildExclusionCollection) )
276
                    {
277
                        mBuildExclusionCollection.add(buildExclusion);
278
                    }
279
                    else
280
                    {
281
                        // Remove the indirectly excluded entry as its root cause
282
                        // is no longer present.
283
                        buildExclusion.includeToBuild(mReleaseManager, mBaseline);
284
                    }
285
                }
286
            }
287
 
288
            //-----------------------------------------------------------------------
289
            //	Query package versions
290
            //
291
            phase.setPhase("queryPackageVersions");
292
            mLogger.debug("planRelease queryPackageVersions");
293
            mReleaseManager.queryPackageVersions(this, mPackageCollection, mBaseline);
7048 dpurdie 294
            mReleaseManager.queryWips(this, mPackageCollectionWip, mBaseline);
295
            mReleaseManager.queryTest(this, mPackageCollectionTest, mBaseline);
296
            mReleaseManager.queryRipples(this, mPackageCollectionRipple, mBaseline);
297
            mPackageCollectionAll.addAll(mPackageCollection);
298
            mPackageCollectionAll.addAll(mPackageCollectionWip);
299
            mPackageCollectionAll.addAll(mPackageCollectionTest);
300
            mPackageCollectionAll.addAll(mPackageCollectionRipple);
301
 
302
            // Sort the collection by PVID
303
            //      Unit Test output order is known
304
            //      May assist in creating repeatable build orders
305
            //
306
            Collections.sort(mPackageCollectionAll, Package.SeqComparator);
6914 dpurdie 307
 
308
            //------------------------------------------------------------------------
309
            //    Process packages collected
310
            //    Determine and tag those we can't build
311
            phase.setPhase("processPackages");
312
            processPackages();
313
 
314
            //-----------------------------------------------------------------------
315
            //    At this point we have tagged all the packages that we cannot build
316
            //    Now we can determine what we are building
317
            phase.setPhase("planBuildOrder");
318
            mLogger.debug("planRelease process Remaining");
319
            planBuildOrder();
320
 
321
            //  Report excluded packages and the build plan
322
            //  This is being done with the MUTEX being held, but the 
323
            //  trade off is the cost of getting a connection.
324
            //
325
            if ( mDaemon )
326
            {
327
                phase.setPhase("Report Change");
328
                reportChange();
329
                phase.setPhase("Report Plan");            
330
                reportPlan();
331
            }
332
 
333
            //
334
            //	Generate the build Files
335
            //
336
            phase.setPhase("generateBuildFiles");
337
            generateBuildFiles();
338
        }
339
        finally
340
        {
341
            mLogger.debug("planRelease finally");
342
            // this block is executed regardless of what happens in the try block
343
            // even if an exception is thrown
344
            // ensure the SELECT FOR UPDATE is released
345
            try
346
            {
347
                if ( mDaemon )
348
                {
349
                    // attempt to release the SELECT FOR UPDATE through a commit
350
                    // a commit must be done in the normal case
351
                    // a commit may as well be done in the Exception case
352
                    // in the case of a SQLException indicating database connectivity has been lost
353
                    // having a go at the commit is superfluous
354
                    // as the SELECT FOR UPDATE will have been released upon disconnection
355
                    phase.setPhase("releaseMutex");
356
                    mReleaseManager.releaseMutex();
357
                }
358
            }
359
            finally
360
            {
361
                // ensure disconnect under all error conditions
362
                phase.setPhase("disconnectForPlanning");
363
                mReleaseManager.disconnectForPlanning(lastBuildActive);
364
            }
365
        }
366
 
7048 dpurdie 367
        mLogger.warn("planRelease mDaemon {} returned", mDaemon);
6914 dpurdie 368
        phase.setPhase("EndPlan");
369
    }
370
 
371
    /** Process packages that have been collected as a part of the plan
372
     * @param phase
373
     * @throws SQLException
374
     * @throws Exception
375
     */
376
    private void processPackages() throws SQLException, Exception {
377
 
378
        // Deal with test builds here as they may impact upon package attributes
7048 dpurdie 379
        //    eg: dependency collection and build standard differences
6914 dpurdie 380
        //    Note: Done before mPackageDependencyCollection is setup
381
        //
382
        if ( mDaemon )
383
        {
7048 dpurdie 384
            // Process test builds - they are in their own collection
385
            for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
6914 dpurdie 386
            {
387
                Package p = it.next();
7048 dpurdie 388
                mLogger.info("planRelease package test build {}", p.mAlias);
6914 dpurdie 389
 
7048 dpurdie 390
                //
391
                //    Cannot test build an SDK based package or a Pegged Package
392
                //        Remove the test build request from the database
393
                //        Send a warning email
394
                //
395
                if(p.mIsPegged || p.mIsSdk)
6914 dpurdie 396
                {
7048 dpurdie 397
                    String reason;
398
                    reason = (p.mIsPegged) ? "Pegged" : "SDK Based";
6914 dpurdie 399
 
7048 dpurdie 400
                    mLogger.error("planRelease Daemon Instruction (testBuild) of {} package deleted: {}", reason, p.mAlias);
401
                    mReleaseManager.markDaemonInstCompleted( p.mTestBuildInstruction );
402
                    emailRejectedDaemonInstruction("Cannot 'Test Build' a " + reason + " package",p);
403
                }
6914 dpurdie 404
 
7048 dpurdie 405
                // force patch for test build numbering
406
                p.mDirectlyPlanned = true;
407
                p.mChangeType.setPatch();
408
                p.mRequiresSourceControlInteraction = false;
409
                p.mBuildReason = BuildReason.Test;
410
                p.mIndirectlyPlanned = true;
6914 dpurdie 411
            }
412
        }
413
 
414
        // Set up mPackageDependencyCollection on each package
415
        //    Examine the dependencies by alias and convert this to a 'package' selected from the released package set
7048 dpurdie 416
        mLogger.debug("planRelease setup setPackageDependencyCollection");
417
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 418
        {
419
            Package p = it.next();
420
 
421
            for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
422
            {
423
                String alias = it2.next();
424
                Package dependency = findPackage(alias);
425
                p.mPackageDependencyCollection.add(dependency);
426
            }
7048 dpurdie 427
        }    
6914 dpurdie 428
 
7048 dpurdie 429
        // Detect and deal with circular dependencies
430
        // Examine all packages under consideration
431
        //
6914 dpurdie 432
        mLogger.debug("planRelease deal with circular dependencies");
7048 dpurdie 433
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 434
        {
435
            Package p = it.next();
436
 
437
            if ( p.hasCircularDependency( this ) )
438
            {
7048 dpurdie 439
                mLogger.info("planRelease circular dependency detected {}", p.mAlias);
6914 dpurdie 440
 
441
                //  Force this package to be marked as having a circular dependency - even if its been excluded
442
                p.mBuildFile = 0;
443
 
444
                // exclude all dependent packages
445
                // max 50 chars
446
                rippleBuildExclude(p, p.mId, "Package has circular dependency", null, null, true);
447
 
448
                // take the package out of the build
449
                p.mBuildFile = -6;
7048 dpurdie 450
                mLogger.info("planRelease set mBuildFile to -6 for package {}", p.mAlias );
6914 dpurdie 451
                standardOut(mCircularDependency, p.mAlias, mCircularDependencyFlag);
452
                mCircularDependencyFlag = false;
453
            }
454
        }
455
 
456
        // Scan for packages with missing dependencies
457
        //    ie: The dependent package is not in the package Collection
458
        //        DEVI 55483 now use the fully built mPackageDependencyCollection (in rippleBuildExclude)
459
        mLogger.debug("planRelease use the fully built mPackageDependencyCollection");
7048 dpurdie 460
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 461
        {
462
            Package p = it.next();
463
 
464
            if ( mDaemon )
465
            {
466
                //  Daemon Mode Only
467
                //  Not interested in the dependencies of a pegged package or a package provided from an SDK.
468
                //  Such packages will be deemed to not have missing dependencies
469
                if (p.mIsPegged || p.mIsSdk)
470
                {
471
                    continue;
472
                }
473
            }
474
 
475
            for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
476
            {
477
                String alias = it2.next();
478
                Package dependency = findPackage(alias);
479
 
480
                if (dependency == ReleaseManager.NULL_PACKAGE)
481
                {
7048 dpurdie 482
                    mLogger.info("planRelease dependency is not in the baseline {}", alias);
6914 dpurdie 483
                    // exclude all dependent packages
484
                    // max 50 chars
485
                    rippleBuildExclude(p, p.mId, "Package build dependency not in the release", null, null, true);
486
 
487
                    // take the package out of the build
488
                    p.mBuildFile = -4;
7048 dpurdie 489
                    mLogger.info("planRelease set mBuildFile to -4 for package {}", p.mAlias );
6914 dpurdie 490
                    standardOut(mNotInBaseline, p.mAlias, mNotInBaselineFlag);
491
                    mNotInBaselineFlag = false;
492
                    break;
493
                }
494
            }
495
        }
496
 
7048 dpurdie 497
        // Detect packages with no build standard and exclude them from the build
6914 dpurdie 498
        mLogger.debug("planRelease process packages which are not reproducible");
7048 dpurdie 499
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 500
        {
501
            Package p = it.next();
502
 
503
            if (p.mBuildFile == 0)
504
            {
505
                if ( mDaemon )
506
                {
507
                    //  Daemon Mode Only
508
                    //  Not interested in the reproducibility of a pegged package or a package provided from an SDK.
509
                    //  Such packages will be deemed to be reproducible - but out side of this release
510
                    if (p.mIsPegged || p.mIsSdk)
511
                    {
512
                        continue;
513
                    }
514
                }
515
 
7048 dpurdie 516
                // Does the package have a build standard. If not then we can't reproduce it.
517
                // Escrow - Assume the package is provided
518
                // Daemon - Exclude this package, but not its consumers. If the package is available then we can use it.
6914 dpurdie 519
                if (!p.isReproducible())
520
                {
7048 dpurdie 521
                    mLogger.info("planRelease package not reproducible {}" ,p.mName);
6914 dpurdie 522
                    // max 50 chars
7048 dpurdie 523
                    rippleBuildExclude(p, p.mId, "Package has no build environment", null, null, false);
6914 dpurdie 524
 
525
                    // package is not reproducible, discard
526
                    p.mBuildFile = -1;
7048 dpurdie 527
                    mLogger.info("planRelease set mBuildFile to -1 for package {}", p.mAlias );
6914 dpurdie 528
                    standardOut(mAnyBuildPlatforms, p.mAlias, mAnyBuildPlatformsFlag);
529
                    mAnyBuildPlatformsFlag = false;
530
                }
531
            }
532
        }
533
 
7048 dpurdie 534
        //    Process packages which are not reproducible on the configured set of build machines.
6914 dpurdie 535
        //
536
        //    Test each package and determine if the package contains a buildStandard that
537
        //    can be processed by one of the machines in the build set
538
        //
539
        //    ie: Package: Win32:Production and we have a BM with a class of 'Win32'
540
        //
541
        //    Only exclude the failing package and not its dependents
542
        //    May be legitimate in the release
543
        //
7048 dpurdie 544
//TODO - verify this code. I'm not sure it can be reached. I think that the "Package has no build environment" test above is detecting all these packages
6914 dpurdie 545
        mLogger.debug("planRelease process packages which are not reproducible2");
7048 dpurdie 546
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 547
        {
548
            Package p = it.next();
549
 
550
            if (p.mBuildFile == 0)
551
            {
552
                if ( mDaemon )
553
                {
554
                    //  Daemon Mode Only
555
                    //  Not interested in the reproducibility of a pegged package or a package provided from an SDK.
556
                    //  Such packages will be deemed to be reproducible - but out side of this release
557
                    if (p.mIsPegged || p.mIsSdk)
558
                    {
559
                        continue;
560
                    }
561
                }
562
 
563
                // package has yet to be processed
564
                // assume it does not need to be reproduced for this baseline
565
                //
566
                //    For each machineClass in the buildset
567
                boolean reproduce = false;
568
 
569
                for (Iterator<String> it2 = mReleaseManager.mReleaseConfigCollection.mMachineClasses.iterator(); it2.hasNext(); )
570
                {
571
                    String machineClass = it2.next();
572
 
573
                    if ( p.canBeBuildby(machineClass))
574
                    {
575
                        reproduce = true;
7048 dpurdie 576
                        mLogger.info("planRelease package built on {} {}", machineClass, p.mAlias );
6914 dpurdie 577
                        break;
578
                    }
579
                }
580
 
581
                if ( !reproduce )
582
                {
7048 dpurdie 583
                    mLogger.info("planRelease package not reproducible on the build platforms configured for this baseline {}", p.mName);
6914 dpurdie 584
 
7048 dpurdie 585
                    // max 50 chars
586
                    rippleBuildExclude(p, p.mId, "Package not built for configured platforms", null, null, false);
6914 dpurdie 587
 
588
                    // package is not reproducible on the build platforms configured for this baseline, discard
589
                    p.mBuildFile = -2;
7048 dpurdie 590
                    mLogger.info("planRelease set mBuildFile to -2 for package {}", p.mAlias );
6914 dpurdie 591
                    standardOut(mAssocBuildPlatforms, p.mAlias, mAssocBuildPlatformsFlag);
592
                    mAssocBuildPlatformsFlag = false;
593
                }
594
            }
595
        }      
596
 
597
        if (mDaemon)
598
        {
599
            // Daemon Mode Only
600
            // Process packages which are not ripple buildable, and all packages dependent upon them
601
            mLogger.debug("planRelease process packages which are not ripple buildable");
602
            for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
603
            {
604
                BuildExclusion be = it.next();
605
 
606
                for (Iterator<Package> it1 = mPackageCollection.iterator(); it1.hasNext(); )
607
                {
608
                    Package p = it1.next();
609
 
610
                    // ensure only root cause, non test build, build exclusions are excluded
611
                    // mBuildExclusionCollection is at this point based on
612
                    // relevant (direct and indirect) excluded pv's in the database
613
                    if ( be.compare(p.mId) && be.isARootCause() && p.mTestBuildInstruction == 0 && p.mForcedRippleInstruction == 0 )
614
                    {
615
                        // package is not reproducible, discard
7048 dpurdie 616
 
6914 dpurdie 617
                        rippleBuildExclude( p, p.mId, null, it, be, true );
618
                        p.mBuildFile = -3;
7048 dpurdie 619
                        mLogger.info("planRelease set mBuildFile to -3 for package {}", p.mAlias );
6914 dpurdie 620
                        break;
621
                    }
622
                }
623
            }
624
 
625
            //  Daemon Mode Only
626
            //  Process packages which need to be ripple built
627
            mLogger.debug("planRelease process packages which need to be ripple built");
628
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
629
            {
630
                Package p = it.next();
631
 
632
                if (p.mBuildFile == 0)
633
                {
634
                    //  Not interested in a pegged package or a package provided from an SDK.
635
                    //  Such packages are not rippled
636
                    if (p.mIsPegged || p.mIsSdk)
637
                    {
638
                        continue;
639
                    }
640
 
7048 dpurdie 641
                    //    Examine this packages dependencies
642
                    //    If one of them does not exist in the 'official release' set then
643
                    //    the package needs to be built against the official release set
644
                    //    and we can't build any of its dependent packages
645
                    Iterator<Integer> it2 = p.mDependencyIDCollection.iterator();
646
                    Iterator<Package> it3 = p.mPackageDependencyCollection.iterator();
647
                    while ( it2.hasNext() && it3.hasNext() )
6914 dpurdie 648
                    {
7048 dpurdie 649
                        Integer dpvId = it2.next();
650
                        Package dependency = it3.next();
651
 
652
                        if ( !dependency.mAdvisoryRipple )
6914 dpurdie 653
                        {
7048 dpurdie 654
                            // not advisory, ie: has ripple build impact
655
                            if ( !isInRelease(dpvId) )
6914 dpurdie 656
                            {
7048 dpurdie 657
                                // the package is out of date
658
                                // exclude all dependent package versions
659
                                mLogger.info("planRelease package out of date {}", p.mName);
660
                                p.mBuildReason = BuildReason.Ripple;
661
                                rippleIndirectlyPlanned(p);
662
 
663
                                //  This package needs to be rippled
664
                                //  If this package has a rippleStop marker of 's', then we cannot
665
                                //  build this package at the moment.
666
                                //  Packages that depend on this package have been excluded
667
                                //  We need to exclude this one too
668
                                //
669
                                if (p.mRippleStop == 's' || p.mRippleStop == 'w') 
6914 dpurdie 670
                                {
7048 dpurdie 671
                                    // Package marked as a rippleStop
672
                                    // max 50 chars
673
                                    rippleBuildExclude(p, -2, "Ripple Required." + " Waiting for user", null, null, false);
674
 
675
                                    // package is unBuildable, mark reason and discard
676
                                    p.mBuildFile = -11;
6914 dpurdie 677
 
7048 dpurdie 678
                                    if (p.mRippleStop == 's' ) {
679
                                        // Need to flag to users that the package build is waiting user action
680
                                        mLogger.info("planRelease Ripple Required. Stopped by flag {}", p.mName);
681
                                        mReleaseManager.setRippleStopWait(mRtagId,p);
6914 dpurdie 682
                                    }
683
                                }
7048 dpurdie 684
 
685
                                break;
6914 dpurdie 686
                            }
687
                        }
688
                    }
689
                }
690
            }
691
 
692
            //  Daemon Mode Only
693
            //  Process packages which do not exist in the archive
694
            //  For unit test purposes, assume all packages exist in the archive if released
695
            mLogger.debug("planRelease process packages which do not exist in the archive");
7048 dpurdie 696
            if ( mReleaseManager.mUseDatabase )
6914 dpurdie 697
            {
698
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
699
                {
700
                    Package p = it.next();
701
 
702
                    if (p.mBuildFile == 0)
703
                    {
704
                        // package has yet to be processed
705
                        if (!p.mDirectlyPlanned && !p.mIndirectlyPlanned && p.mForcedRippleInstruction == 0)
706
                        {
707
                            // check package version archive existence
708
                            if (!p.existsInDpkgArchive())
709
                            {
710
                                if (! p.mIsBuildable)
711
                                {
712
                                    //  Package does not exist in dpkg_archive and it has been flagged as unbuildable
713
                                    //  This may be because is Unbuildable or Manually built
7048 dpurdie 714
                                    mLogger.info("planRelease Unbuildable package not found in archive {}", p.mName);
6914 dpurdie 715
                                    // max 50 chars
716
                                    rippleBuildExclude(p, p.mId, "Unbuildable" + " package not found in archive", null, null, true);
717
 
718
                                    // package is unBuildable, mark reason and discard
719
                                    p.mBuildFile = -10;
720
 
721
                                }
722
                                //  Not interested in a pegged package or a package provided from an SDK.
723
                                //  Such packages are not rippled
724
                                else if (p.mIsPegged || p.mIsSdk)
725
                                {
726
                                    String reason;
727
                                    reason = (p.mIsPegged) ? "Pegged" : "SDK";
728
 
729
                                    //  Pegged packages or packages provided from an SDK MUST exist in dpkg_archive
730
                                    //  They will not be built within the context of this release. It is the responsibility
731
                                    //  of another release to build them.
7048 dpurdie 732
                                    mLogger.info("planRelease {} package not found in archive {}", reason, p.mName);
6914 dpurdie 733
                                    // max 50 chars
734
                                    rippleBuildExclude(p, p.mId, reason + " package not found in archive", null, null, true);
735
 
736
                                    // package is not reproducible, mark reason and discard
737
                                    p.mBuildFile = -7;
738
 
739
                                }
740
                                else if (p.mForcedRippleInstruction == 0)
741
                                {
742
                                    //  [JATS-331] Unable to rebuild package with Advisory Ripple dependencies
743
                                    //    Examine this packages dependencies
744
                                    //    If one of them does not exist in the 'official release' set then
745
                                    //    the package cannot be rebuilt in this release.
746
                                    for (Iterator<Integer> it2 = p.mDependencyIDCollection.iterator() ; it2.hasNext() ;)
747
                                    {
748
                                        Integer dpvId = it2.next();
749
                                        if ( !isInRelease(dpvId) )
750
                                        {
751
                                            // This package cannot be rebuilt as one of its dependents is NOT in this release
752
                                            // exclude all dependent package versions
753
 
7048 dpurdie 754
                                            mLogger.info("planRelease package not found in archive. Cannot be rebuilt due to {}", p.mName);
6914 dpurdie 755
                                            // max 50 chars
756
                                            rippleBuildExclude(p, p.mId, "Package cannot be rebuilt in this release", null, null, true);
757
 
758
                                            // package is not reproducible, mark reason and discard
759
                                            p.mBuildFile = -4;
760
                                            break;
761
                                        }
762
                                    }
763
 
764
                                    //  The package has not been excluded from the build
765
                                    if (p.mBuildFile == 0)
766
                                    {
7048 dpurdie 767
                                        mLogger.info("planRelease package not found in archive {}", p.mName);
6914 dpurdie 768
                                        // DEVI 47395 the cause of this build is not WIP or ripple induced,
769
                                        // it simply does not exist in the archive (has been removed)
770
                                        // prevent source control interaction
771
                                        p.mRequiresSourceControlInteraction = false;
772
                                        p.mBuildReason = BuildReason.Restore;
773
                                        rippleIndirectlyPlanned(p);
774
                                    }
775
                                }
776
                            }
777
                        }
778
                    }
779
                }
780
            }
781
 
782
            //  Daemon Mode Only
7048 dpurdie 783
            //  Detect bad forced ripples requests and reject them
6914 dpurdie 784
            mLogger.debug("planRelease process forced ripples");
7048 dpurdie 785
            for (Iterator<Package> it = mPackageCollectionRipple.iterator(); it.hasNext(); )
6914 dpurdie 786
            {
787
                Package p = it.next();
788
 
789
                if (p.mBuildFile == 0)
790
                {
7048 dpurdie 791
                    //
792
                    //    Cannot force a ripple on an SDK based package or a Pegged Package
793
                    //        Remove the daemon instruction from the database
794
                    //        Send a warning email
795
                    //
796
                    if(p.mIsPegged || p.mIsSdk)
6914 dpurdie 797
                    {
7048 dpurdie 798
                        String reason;
799
                        reason = (p.mIsPegged) ? "Pegged" : "SDK Based";
6914 dpurdie 800
 
7048 dpurdie 801
                        mLogger.error("planRelease Daemon Instruction of {} package deleted: {}", reason, p.mName);
802
                        mReleaseManager.markDaemonInstCompleted( p.mForcedRippleInstruction );
803
                        emailRejectedDaemonInstruction("Cannot 'Ripple' a " + reason + " package",p);
6914 dpurdie 804
 
7048 dpurdie 805
                        p.mBuildFile = -8; 
6914 dpurdie 806
                    }
807
                }
808
            }
809
 
810
            //  Daemon Mode Only
811
            //  Mark Pegged and SDK packages as not to be built
812
            //  Have previously detected conflicts between pegged/sdk packages and daemon instructions
813
            //
814
            mLogger.debug("planRelease remove pegged and SDK packages from the build set");
815
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
816
            {
817
                Package p = it.next();
818
 
819
                if (p.mBuildFile == 0)
820
                {
821
                    //  Not interested in a pegged package or a package provided from an SDK.
822
                    //  Such packages are not built
823
                    if (p.mIsPegged || p.mIsSdk)
824
                    {
825
                        String reason;
826
                        reason = (p.mIsPegged) ? "Pegged" : "SDK";
827
 
7048 dpurdie 828
                        mLogger.info("planRelease {} not built in this release {}", reason, p.mName);
6914 dpurdie 829
                        p.mBuildFile = -8;
830
                    }
831
                }
832
            }
833
 
834
            //  Daemon Mode Only
835
            //  Locate Test Build Requests that cannot be satisfied - will not be built due to
836
            //  errors in dependent packages. Report the error to the user and remove the request
837
            //
7048 dpurdie 838
            for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
6914 dpurdie 839
            {
840
                Package p = it.next();
841
 
7048 dpurdie 842
                if (p.mBuildFile < 0)
6914 dpurdie 843
                {
7048 dpurdie 844
                    String reason;
845
                    switch (p.mBuildFile)
6914 dpurdie 846
                    {
7048 dpurdie 847
                    case -1:  reason = "Not reproducible"; break;
848
                    case -2:  reason = "Not reproducible on configured build platforms"; break;
849
                    case -3:  reason = "Marked as 'Do not ripple'"; break;
850
                    case -4:  reason = "Dependent on a package not in the release"; break;
851
                    case -5:  reason = "Indirectly dependent on a package not reproducible in the release"; break;
852
                    case -6:  reason = "Has a circular dependency"; break;
853
                    case -7:  reason = "Pegged or SDK package not in dpkg_archive"; break;
854
                    case -8:  reason = "Is a Pegged or SDK package"; break;
855
                    case -9:  reason = "Rejected Daemon Instruction"; break;
856
                    case -10: reason = "Unbuildable package not in dpkg_archive"; break;
857
                    case -11: reason = "Marked as 'RippleStop'"; break;
858
                    default:  reason = "Unknown reason. Code:" + p.mBuildFile; break;
6914 dpurdie 859
                    }
7048 dpurdie 860
                    mLogger.error("planRelease Test Build of an unbuildable of package deleted: {}", p.mName);
861
                    mReleaseManager.markDaemonInstCompleted( p.mTestBuildInstruction );
862
                    emailRejectedDaemonInstruction(reason,p);
6914 dpurdie 863
                }
864
            }
7048 dpurdie 865
 
6914 dpurdie 866
        }
867
        else
868
        {
869
            // escrow reporting only
870
            // Report packages that are not reproducible
871
            //
872
            //  Note: I don't believe this code can be executed
873
            //        The -3 is only set in daemon mode
874
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
875
            {
876
                Package p = it.next();
877
 
878
                if (p.mBuildFile == -3)
879
                {
880
                    standardOut(mDependent, p.mAlias, mDependentFlag);
881
                    mDependentFlag = false;
882
                }
883
            }
884
        }
885
    }
886
 
887
    /** Plan the build order.
888
     *  Assumes that a great deal of work has been done.
889
     *  This is a stand alone method to contain the work
890
     *  
891
     * @throws Exception
892
     * @throws SQLException
893
     */
7070 dpurdie 894
    private void planBuildOrder() throws Exception, SQLException 
895
    {
7052 dpurdie 896
 
7070 dpurdie 897
//TODO - Planning is not working well
7052 dpurdie 898
/**
899
 * Current status
900
 * The selection of the package to build next is deeply flawed
7070 dpurdie 901
 * Currently it will select a directly planned package over a ripple - (perhaps that is good)
902
 * 
903
 * Currently on the buildPlan of the 'selected' package is included in the BuildOrder
904
 * 
7052 dpurdie 905
 * The current algorithm is based on time - but all packages have zero build time ( in UTF )
906
 * Even if this is fixed the algorithm is broken as we will select the complete build with the shortest time
907
 * which will be the ripple of a leaf package ( perhaps that is good )
908
 * 
909
 * Also:
7070 dpurdie 910
 *      [Done] Need to include all packages that we can now build into the final build plan, not just the first one and its build tree
7052 dpurdie 911
 * 
7070 dpurdie 912
 *      [Done-ish]Need to generate a single package set - so that WIPS and others replace those in the final build set
913
 *      [Done]Remove duplicates from the complete package set
7052 dpurdie 914
 *      
915
 *      Need more test cases
916
 *      
917
 *      Need to report all build options, not just the selected one
918
 *      
919
 *      Cleanup the ANT build file - don't list all the release dependencies, just those needed to build the current package
7070 dpurdie 920
 *      
921
 *      If a WIP on a package that has circular dependencies is added, then the WIP will be excluded. This prevents the problem being fixed.
922
 *      Should not exclude a WIP of a package with a circular dependency
7052 dpurdie 923
 */
6914 dpurdie 924
 
925
        // Process remaining packages which are need to be reproduced for this baseline.
926
        //    Determine the build file for each package
927
        //    For daemon builds:
7048 dpurdie 928
        //      Determine the next package that can be built now
929
        //          Sounds simple - doesn't it
6914 dpurdie 930
        //      Set its mBuildNumber to 1, all remaining reproducible packages to 2
931
        //    For escrow builds:
932
        //      Determine the package versions that can be built in the build iteration
933
        //      Set their mBuildNumber to the build iteration
934
        //      Increment the build iteration and repeat until all package versions 
935
        //      that need to be reproduced have been assigned a build iteration        
936
 
937
        boolean allProcessed = false;
938
        int buildFile = 1;
939
 
940
        do
941
        {
7048 dpurdie 942
            //
943
            //  Create the mBuildOrder collection
944
            //      Same for both Daemon and Escrow modes
945
            //      Will have package build order and build level
6914 dpurdie 946
            boolean allDependenciesProcessed = true;
947
            do
948
            {
949
                allDependenciesProcessed = true;
950
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
951
                {
952
                    Package p = it.next();
953
 
7048 dpurdie 954
                    if ( p.mBuildFile < 0  ) 
6914 dpurdie 955
                    {
7048 dpurdie 956
                        // Daemon: Flag packages that cannot be built
6914 dpurdie 957
                        // Escrow: Flag packages with a foreign build environment as processed
958
                        p.mProcessed = true;
7048 dpurdie 959
                        mLogger.info("planRelease package not buildable {}", p.mName);            
6914 dpurdie 960
                    }
7048 dpurdie 961
                    else if ( p.mBuildFile == 0 )
6914 dpurdie 962
                    {
963
                        // package yet to be processed and
7048 dpurdie 964
                        //  Daemon mode: Could be built
6914 dpurdie 965
                        //  Escrow mode: Can be reproduced
966
                        boolean canBeBuiltNow = true;
967
                        boolean allDependenciesForThisPackageProcessed = true;
968
 
969
                        //  Scan the packages dependencies
970
                        for ( Iterator<Package> it2 = p.mPackageDependencyCollection.iterator(); it2.hasNext(); )
971
                        {
972
                            Package dependency = it2.next();
973
 
974
                            if ( !dependency.mProcessed )
975
                            {
976
                                //  If all the dependencies have been processed, then we can potentially build this package
977
                                //  If any of them have not been processed, then cannot calculate canBeBuiltNow until this 
978
                                //  dependency has been processed
979
                                allDependenciesForThisPackageProcessed = false;
980
                                allDependenciesProcessed = false;
981
                            }
7048 dpurdie 982
                            else if (  (  mDaemon && (   dependency.mBuildFile == 0 ) ) 
6914 dpurdie 983
                                    || ( !mDaemon && ( ( dependency.mBuildFile == 0 ) ||
984
                                                           ( dependency.mBuildFile == buildFile &&
985
                                                           ( !p.haveSameBuildStandards(dependency)  ) ) ) ) )
986
                            {
987
                                // Daemon mode:
7048 dpurdie 988
                                //    This processed dependency has not been assigned to a build iteration - so can't built yet
6914 dpurdie 989
                                // Escrow mode: This package cannot be built now if
990
                                //    This processed dependency has not been assigned to a build iteration or
991
                                //    This processed dependency has been assigned to this build iteration, but the 
992
                                //    build standards of the package and this dependency prevent the package being
993
                                //    built in this iteration.   
994
                                canBeBuiltNow = false;
7048 dpurdie 995
                                mLogger.info("planRelease package cannot be built in this iteration {}", p.mName);
6914 dpurdie 996
                                break;
997
                            }
998
                        }
999
 
7048 dpurdie 1000
                        //  All dependencies have been processed. May be able to build this package
1001
                        //      Add the package to the build order list
1002
                        //
6914 dpurdie 1003
                        if (allDependenciesForThisPackageProcessed)
1004
                        {
1005
                            p.mProcessed = true;
7048 dpurdie 1006
                            if ( canBeBuiltNow )
6914 dpurdie 1007
                            {
1008
                                mBuildOrder.add(p);
7048 dpurdie 1009
                                p.mBuildFile = buildFile;
1010
                                mLogger.info("planRelease set mBuildFile to {} for package {}",buildFile, p.mAlias );
6914 dpurdie 1011
                            }
1012
                        }
1013
                    }
1014
                }
1015
            } while( !allDependenciesProcessed );
7048 dpurdie 1016
 
1017
            //  Have process all the packages that we can at the moment
1018
            //      Examine all the packages in the collection to see if there are more that need to be extracted
1019
            //      These will be done at a different build-level
1020
            //  
1021
            allProcessed = true;
1022
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
1023
            {
1024
                Package p = it.next();
1025
                if ( p.mBuildFile == 0 )
1026
                {
1027
                    // more build files are required
1028
                    allProcessed = false;
1029
                    mLogger.info("planRelease more build files are required for {}", p.mName);
1030
                    break;
1031
                }
1032
            }
6914 dpurdie 1033
 
7048 dpurdie 1034
            buildFile++;
1035
            if (buildFile % 500 == 0 ) {
1036
                mLogger.error("planRelease. Too many build levels {}", buildFile);
1037
            }
1038
        } while( !allProcessed );
1039
 
1040
 
1041
        if ( mDaemon )
1042
        {
1043
 
6914 dpurdie 1044
            //
1045
            //  Daemon Mode:
1046
            //
7070 dpurdie 1047
 
1048
            //  Create a list of build candidates
1049
            //
1050
            //  Add in the WIPs, Tests and Ripple Requests so that we can process them as one collections
1051
            //  Now have a collection of packages that we would like to build right now
1052
            //  See if any of them can be excluded due to issues with creating a new package version
7048 dpurdie 1053
            ArrayList<Package> buildCandidates = new ArrayList<Package>();
7070 dpurdie 1054
            buildCandidates.addAll(mPackageCollectionWip);
1055
            buildCandidates.addAll(mPackageCollectionTest);
1056
            buildCandidates.addAll(mPackageCollectionRipple);
7048 dpurdie 1057
 
7070 dpurdie 1058
            //  Locate all packages that we can build now
1059
            //      Packages that have a build requirement and have no reason we cannot build them
1060
 
7048 dpurdie 1061
            for (Iterator<Package> it = mBuildOrder.iterator(); it.hasNext(); )
6914 dpurdie 1062
            {
7048 dpurdie 1063
                Package p = it.next();
1064
                if ( p.mProcessed && p.mBuildFile > 0 )
6914 dpurdie 1065
                {
7048 dpurdie 1066
                    if (p.mBuildReason != null)
1067
                    {
1068
                        // Have a reason to build this package
1069
                        buildCandidates.add(p);
1070
                        mLogger.info("planRelease Candidate {}",p.mAlias);
1071
                    }
1072
                }
1073
            }
1074
 
7070 dpurdie 1075
            //  Examine the build candidates and verify that a new version number can be calculated for each
1076
            //  version that we need to build.
1077
            //
1078
//TODO If we find WIP/TEST/RIPPLE with invalid nextVersion, then we could email the submitter and treat it as a fail.            
7048 dpurdie 1079
 
1080
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1081
            {
1082
                Package p = it.next();
6914 dpurdie 1083
 
7048 dpurdie 1084
                if ( p.mBuildFile >= 0 )
1085
                {
7050 dpurdie 1086
                    int pvApplied = p.applyPV(mReleaseManager);
7048 dpurdie 1087
 
1088
                    if ( pvApplied == 1 )
6914 dpurdie 1089
                    {
7048 dpurdie 1090
                        // max 50 chars
1091
                        rippleBuildExclude(p, p.mId, "Package has non standard versioning", null, null, true);
1092
                    }
1093
                    else if ( pvApplied == 2 )
1094
                    {
1095
                        // max 50 chars
1096
                        rippleBuildExclude(p, p.mId, "Package has reached ripple field limitations", null, null, true);
1097
                    }
1098
                    else if ( pvApplied == 3 )
1099
                    {
1100
                        // max 50 chars
1101
                        rippleBuildExclude(p, p.mId, "Package has invalid change type", null, null, true);
1102
                    }
1103
 
1104
                    if ( pvApplied != 0) 
1105
                    {
1106
                        // If this package is not a WIP/TEST/RIPPLE, then remove it from this collection
7051 dpurdie 1107
                        // Want to keep all WIP/TEST/RIPPLE items to simplify reporting
7048 dpurdie 1108
                        if (! p.mIsNotReleased )
6914 dpurdie 1109
                        {
7048 dpurdie 1110
                            it.remove();
6914 dpurdie 1111
                        }
7048 dpurdie 1112
                    }
1113
 
1114
                    //
1115
                    //  Ensure that the mRippleTime is known for each package
1116
                    //  Collection includes: naturalRipples, ForcedRipples, TestBuilds and NewVersions
1117
                    if ( pvApplied == 0)
1118
                    {
1119
                        if (p.mTestBuildInstruction != 0)
6914 dpurdie 1120
                        {
7048 dpurdie 1121
                            // Test Build - there is no ripple effect
1122
                            // The time impact will be the estimated build time of this one package
1123
                            p.mRippleTime = p.mBuildTime;
1124
 
6914 dpurdie 1125
                        }
7048 dpurdie 1126
                        else 
1127
                        {
1128
                            //  Calculate the time to build the package AND all of the packages that depend on it
1129
                            //  Calculate the build plan for the package
1130
                            //
7070 dpurdie 1131
                            calcBuildPlan(p, mPackageCollection, true);
7048 dpurdie 1132
                        }
6914 dpurdie 1133
                    }
1134
                }
1135
            }
7048 dpurdie 1136
 
1137
            //  Determine the first test build package
1138
            //  Assume the collection is in build instruction id order, 
1139
            //      So that the first request will be built first
1140
            //  Add all buildable test-builds to the mBuildOrder collection 
1141
            Package testBuild = ReleaseManager.NULL_PACKAGE;
1142
            mBuildOrder.clear();
6914 dpurdie 1143
 
7048 dpurdie 1144
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1145
            {
1146
 
1147
                Package p = it.next();
1148
                if ( p.mBuildFile >= 0 )
6914 dpurdie 1149
                {
7048 dpurdie 1150
                    if (p.mTestBuildInstruction != 0)
6914 dpurdie 1151
                    {
7048 dpurdie 1152
                        //  Not a Test Build
1153
                        if (testBuild == ReleaseManager.NULL_PACKAGE)
1154
                        {
7051 dpurdie 1155
                            testBuild = p;
7048 dpurdie 1156
                        }
1157
                        mBuildOrder.add(p);
6914 dpurdie 1158
                    }
1159
                }
1160
            }
7048 dpurdie 1161
 
1162
            //
7070 dpurdie 1163
            //  Determine the NON-test packages the we will build next
1164
            //  This will be the one with the lowest ripple time
7048 dpurdie 1165
            //
7070 dpurdie 1166
            Package build = ReleaseManager.NULL_PACKAGE;
1167
            ArrayList<Package> buildNext = new ArrayList<Package>();
1168
 
1169
            //  Extract candidates that are left
1170
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
6914 dpurdie 1171
            {
7070 dpurdie 1172
                Package p = it.next();
1173
                if ( p.mBuildFile >= 0  &&p.mTestBuildInstruction == 0)
1174
                {
1175
                    buildNext.add(p);
1176
                }
1177
            }
1178
 
1179
            if ( !buildNext.isEmpty() )
1180
            {
1181
                //  Sort on mRippleTime so that
1182
                //      We can get the lowest first
1183
                //      We can generate the complete plan in a nice order
1184
                //
1185
                Collections.sort(buildNext, Package.RippleTimeComparator);
1186
 
1187
                //  At the moment extract the first one - this is the fastedt
1188
                //  TODO - could build another candidate as long as it does't extend the time by (say) 10%
1189
                //         Would need to rejigger the collection - for the next step
1190
                //
1191
                build = buildNext.get(0);
1192
 
1193
                //  Determine the amount of time we would allow the 'best' plan to be extended
1194
                //      Allow for a 20% extension in time
1195
                //      Min of 10 minutes
1196
                int baseTime = build.mRippleTime;
1197
                baseTime = ( baseTime * 1200) / 1000;
1198
                if ( baseTime < 10 * 60) {
1199
                    baseTime = (10 * 60);
1200
                }
1201
                mLogger.error("Scan for package to build: {} {}", build.mRippleTime, baseTime);
1202
 
1203
                //  Find last package that does not exceed the extended ripple time
1204
                for (Iterator<Package> it = buildNext.iterator(); it.hasNext(); )
1205
                {
1206
                    Package p = it.next();
1207
                    if (p.mRippleTime > baseTime)
1208
                    {
1209
                        break;
1210
                    }
1211
                    build = p;
1212
                }
1213
 
1214
                //
1215
                //  Extend mBuildOrder with the selected non-test build package and its build plan
1216
                //  Really only for display purposes
1217
                //
1218
                Package.resetProcessed(buildNext);
7048 dpurdie 1219
                mBuildOrder.add(build);
7070 dpurdie 1220
                updateBuildList(build.mRipplePlan, buildNext);
7048 dpurdie 1221
                mBuildOrder.addAll(build.mRipplePlan);
7070 dpurdie 1222
 
1223
                //  Add in other build candidates
1224
                for (Iterator<Package> it = buildNext.iterator(); it.hasNext(); )
1225
                {
1226
                    Package p = it.next();
1227
                    if ( p.mBuildFile >= 0 )
1228
                    {
1229
                        if ( p != build && ! p.mIsProcessed)
1230
                        {
1231
                            //  Not our selected package and not already processed
1232
                            mBuildOrder.add(p);
1233
                            updateBuildList(p.mRipplePlan, buildNext);
1234
                            mBuildOrder.addAll(p.mRipplePlan);
1235
                        }
1236
                    }
1237
                }
7048 dpurdie 1238
            }
1239
 
1240
            //
1241
            //  Mark the first package in the build order as the one to be built
7051 dpurdie 1242
            //  This will give test builds priority, while indicating what will be built after that
7048 dpurdie 1243
            //
1244
 
1245
            if (!mBuildOrder.isEmpty()) {
1246
                build = mBuildOrder.get(0);
1247
                build.mBuildFile = 1;
1248
 
1249
                if ( build.mForcedRippleInstruction > 0 )
6914 dpurdie 1250
                {
7048 dpurdie 1251
                    mReleaseManager.markDaemonInstCompleted( build.mForcedRippleInstruction );
1252
                }
6914 dpurdie 1253
 
7048 dpurdie 1254
                if ( build.mTestBuildInstruction > 0 )
1255
                {
1256
                    mReleaseManager.markDaemonInstInProgress( build.mTestBuildInstruction );
1257
                }
1258
 
1259
                //  Now that we know which package we are building
1260
                //      Set the previously calculated nextVersion as the packages version number
1261
                //      Claim the version number to prevent other builds from using it. Unless doing a test build
1262
                //
1263
                if (build.mTestBuildInstruction == 0 && build.mNextVersion != null)
1264
                {
1265
                    mReleaseManager.claimVersion(build.mPid, build.mNextVersion + build.mExtension, mBaseline);
1266
                    build.mVersion = build.mNextVersion;
1267
                }
1268
            }
1269
 
1270
            //
7070 dpurdie 1271
            //  Massage the package collection
1272
            //      Replace WIP/TEST/RIPPLE so that the mPackageCollection is a collection of packages we would like in the release
1273
            //      Don't replace those that we can't build due to errors
1274
            //
1275
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1276
            {
1277
                Package p = it.next();
1278
                if ( p.mBuildFile >= 0 )
1279
                {
1280
                    Package pReleased = findPackage(p.mAlias);
1281
                    if ( pReleased != ReleaseManager.NULL_PACKAGE)
1282
                    {
1283
                        int index = mReleaseManager.findPackageLastIndex;
1284
                        mPackageCollection.set(index, p);
1285
                        p.mIsNotReleased = false;
1286
                    }
1287
                }
1288
            }
1289
 
1290
 
1291
            //
7048 dpurdie 1292
            //  To fit in with the old algorithm ( ie: could be improved )
1293
            //  Insert marks into all packages
1294
            //  Not sure exactly why - Its used in the generation of the ant build file
7070 dpurdie 1295
            //                     Want to set mNoBuildReason, mBuildFile
7048 dpurdie 1296
            //
1297
            //      Package we have selected to build: 0     , 1
7070 dpurdie 1298
            //      Package we could have built      : 0     , 2
7048 dpurdie 1299
            //      Packages we can't build          : reason, 3
1300
            //      Packages that are OK             : 3     , 3
7070 dpurdie 1301
            //      ????                             : 0     , 3
7048 dpurdie 1302
 
1303
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
1304
            {
1305
                Package p = it.next();
1306
                if (p == build ) {
1307
                    p.mNoBuildReason = 0;
1308
                    p.mBuildFile = 1;
1309
                } 
1310
                else if ( p.mBuildFile < 0 )
1311
                {
1312
                    p.mNoBuildReason = p.mBuildFile;
1313
                    p.mBuildFile = 3;
1314
                }
1315
                else if (p.mBuildReason != null)
1316
                {
7070 dpurdie 1317
                    p.mNoBuildReason = 0;
1318
                    p.mBuildFile = 2;
7048 dpurdie 1319
                }
1320
                else
1321
                {
1322
                    p.mNoBuildReason = 0;
1323
                    p.mBuildFile = 3;
1324
                }
1325
            }
7070 dpurdie 1326
 
7048 dpurdie 1327
        }
1328
 
1329
    }
1330
 
7070 dpurdie 1331
    /** Update a collection of packages such that the collection contains packages from the WIP/RIPPLE collection
1332
     *  in preference to the package in the main collection
1333
     *  
1334
     * @param packageList   - List to process and update
1335
     * @param repList - List of replacement candidates. Assumes valid packages
1336
     */
1337
    private void updateBuildList(ArrayList<Package> packageList, ArrayList<Package> repList ) {
1338
 
1339
        int baseIndex = 0;
1340
        for (Iterator<Package> it = packageList.iterator(); it.hasNext(); baseIndex++)
1341
        {
1342
            Package basePkg = it.next();
1343
 
1344
            for (Iterator<Package> repit = repList.iterator(); repit.hasNext(); )
1345
            {
1346
                Package repPkg = repit.next();
1347
                if ( basePkg.mAlias.compareTo( repPkg.mAlias ) == 0 )                    
1348
                {
1349
                    //  Replacement package has been found
1350
                    //  Only looking for non-test packages that can be built
1351
                    //  Flag that the package is now a part of the official release set
1352
                    //  Flag that the package has been processed to prevent it being included in a future plan
1353
 
1354
                    packageList.set(baseIndex, repPkg);
1355
                    repPkg.mIsNotReleased = false;
1356
                    repPkg.mIsProcessed = true;
1357
                    break;
1358
 
1359
                }
1360
            }
1361
        }
1362
    }
1363
 
7048 dpurdie 1364
    /**
1365
     * Calculate a build plan for the specified package
1366
     * Calculates : mRippleTime - time to build the package and the ripple effect
1367
     * Calculates : mBuildPlan - collection of packages in the plan that can be built at the moment
1368
     * 
1369
     * Needs to determine all packages that consume the package - and all packages that consume them
1370
     *  Note: The package may not be in the mPackageCollection ( it may be a WIP/TEST/RIPPLE )
1371
     *  
7070 dpurdie 1372
     * Note: The rippleTime of PackageA is not the sum of the rippleTimes of the packages that consume PackageA.
1373
     *  
7048 dpurdie 1374
     * Need to:
1375
     *      Only include a package once.
1376
     *      Only include packages that can/need to be built at the moment
1377
     * 
7070 dpurdie 1378
     * @param p                 - Package to process
1379
     * @param pkgCollection     - Package Collection to scan
1380
     * @param processAll        - True: Order all packages discovered
1381
 
7048 dpurdie 1382
     */
7070 dpurdie 1383
    private void calcBuildPlan(Package p, ArrayList<Package> pkgCollection, boolean processAll) {
1384
 
1385
        mLogger.error("calcBuildPlan Add {}", p.mAlias);
1386
        p.mRipplePlan = usedByPackages(p, pkgCollection);
1387
        p.mRippleTime = p.mBuildTime;
7048 dpurdie 1388
 
7070 dpurdie 1389
        //  Use a ListIterator so that we can add elements to the end of the list while processing
1390
        //  Sum the buildTimes of the packages that we add to the list
7048 dpurdie 1391
 
1392
        for (ListIterator<Package> it = p.mRipplePlan.listIterator(); it.hasNext(); )
1393
        {
1394
            Package pkg = it.next();
7070 dpurdie 1395
            mLogger.error("calc process {}", pkg.mAlias);
1396
            pkg.mRippleOrder++;
1397
            p.mRippleTime += pkg.mBuildTime;
1398
 
1399
            ArrayList<Package> usedBy = usedByPackages(pkg, pkgCollection);
7048 dpurdie 1400
            for (Iterator<Package> it1 = usedBy.iterator(); it1.hasNext(); )
1401
            {
1402
                Package uPkg = it1.next();
7070 dpurdie 1403
                uPkg.mRippleOrder = pkg.mRippleOrder + 1;
7048 dpurdie 1404
                if ( ! p.mRipplePlan.contains( uPkg ))
1405
                {
1406
                    it.add(uPkg);
7070 dpurdie 1407
                    it.previous();
1408
                    p.mRippleTime += uPkg.mBuildTime;
1409
                    mLogger.error("calc Add {}", uPkg.mAlias);
7048 dpurdie 1410
                }
1411
            }
1412
        }
1413
 
1414
        //
7070 dpurdie 1415
        //  Need to determine the rippleTime for each package in the plan
1416
        //      Have a much smaller set of packages to process
1417
        //  Don't care about the mRipplePlan item in the packages
1418
        //  Don't modify the mRippleOrder
1419
        //  
1420
 
1421
        for (ListIterator<Package> it = p.mRipplePlan.listIterator(); it.hasNext(); )
1422
        {
1423
            Package pkg = it.next();
1424
 
1425
            pkg.mRipplePlan = usedByPackages(pkg, pkgCollection);
1426
            pkg.mRippleTime = pkg.mBuildTime;
1427
 
1428
            //  Use a ListIterator so that we can add elements to the end of the list while processing
1429
            //  Sum the buildTimes of the packages that we add to the list
1430
 
1431
            for (ListIterator<Package> it0 = pkg.mRipplePlan.listIterator(); it0.hasNext(); )
1432
            {
1433
                Package pkg1 = it0.next();
1434
                pkg.mRippleTime += pkg1.mBuildTime;
1435
 
1436
                ArrayList<Package> usedBy = usedByPackages(pkg1, pkgCollection);
1437
                for (Iterator<Package> it1 = usedBy.iterator(); it1.hasNext(); )
1438
                {
1439
                    Package uPkg = it1.next();
1440
                    if ( ! pkg.mRipplePlan.contains( uPkg ))
1441
                    {
1442
                        it0.add(uPkg);
1443
                        it0.previous();
1444
                        pkg.mRippleTime += uPkg.mBuildTime;
1445
                    }
1446
                }
1447
            }
1448
 
1449
        }
1450
 
7048 dpurdie 1451
        //
7070 dpurdie 1452
        //  Sort the ripplePlan so that we build the fastest elements first
1453
        //  Only care about the ripplePlan for the main Package
1454
        //
1455
        Collections.sort(p.mRipplePlan, Package.PlanComparator);
1456
 
1457
        //  Debugging
1458
        mLogger.error("calcBuildPlan. Pkg:{} pvid:{}, Order:{} RippleT:{} BuildT:{}", p.mAlias, p.mId, p.mRippleOrder, p.mRippleTime, p.mBuildTime);
7048 dpurdie 1459
        for (ListIterator<Package> it = p.mRipplePlan.listIterator(); it.hasNext(); )
1460
        {
1461
            Package pkg = it.next();
7070 dpurdie 1462
            mLogger.error("calcBuildPlan. Plan: Pkg:{} pvid:{}, Order:{} RippleT:{} BuildT:{}", pkg.mAlias, pkg.mId, pkg.mRippleOrder, pkg.mRippleTime, pkg.mBuildTime);
7048 dpurdie 1463
        }
1464
    }
1465
 
1466
    /** 
1467
     *  Calculate a collection of packages that actively use the named package
1468
     *  A consumer package does NOT use the named package,
1469
     *      If the consumer is an SDK or is Pegged
1470
     *      If the consumer is marked as advisoryRipple
1471
     *      If the consumer cannot be built
1472
     *   
1473
     * @param pkg - Package to process
7070 dpurdie 1474
     * @param pkgCollection - collection of packages to scan
7048 dpurdie 1475
     * @return A collection of packages that actively 'use' the specified package
1476
 
1477
     */
7070 dpurdie 1478
    private ArrayList<Package> usedByPackages(Package pkg, ArrayList<Package> pkgCollection) {
7048 dpurdie 1479
 
1480
        ArrayList<Package> usedBy = new ArrayList<Package>();
1481
 
7070 dpurdie 1482
        for (Iterator<Package> it = pkgCollection.iterator(); it.hasNext(); )
7048 dpurdie 1483
        {
1484
            Package p = it.next();
1485
 
1486
            //  Is this package 'actively used' in the current build
1487
            if (p.mBuildFile >= 0)
1488
            {
1489
                for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
1490
                {
1491
                    String alias = it2.next();
7070 dpurdie 1492
                    if (  pkg.mAlias.compareTo( alias ) == 0  ) {
7048 dpurdie 1493
                        //  Have found a consumer of 'pkg'
1494
                        usedBy.add(p);
6914 dpurdie 1495
                        break;
1496
                    }
1497
                }
1498
            }
7048 dpurdie 1499
        }
1500
 
1501
        return usedBy;
6914 dpurdie 1502
    }
1503
 
1504
    /** Determine if a given PVID is a member of the current release.
1505
     *  Used to determine if a package dependency is out of date
1506
     * 
1507
     * @param dpvId
1508
     * @return true - specified pvid is a full member of the Release
1509
     */
1510
    private boolean isInRelease(Integer dpvId) {
1511
 
7048 dpurdie 1512
        boolean inRelease = false;
6914 dpurdie 1513
 
7048 dpurdie 1514
        for ( Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1515
        {
7048 dpurdie 1516
            Package p = it.next();
6914 dpurdie 1517
 
7048 dpurdie 1518
            if ( p.mId == dpvId )
6914 dpurdie 1519
            {
7048 dpurdie 1520
                inRelease = ! p.mIsNotReleased;
6914 dpurdie 1521
                break;
1522
            }
1523
        }
7048 dpurdie 1524
        return inRelease;
6914 dpurdie 1525
    }
1526
 
1527
 
1528
    /**reports what change in build exceptions happens as part of planRelease
1529
     */
1530
    public void reportChange() throws SQLException, Exception
1531
    {
1532
        int counter = 0;
1533
        for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1534
        {
1535
            BuildExclusion buildExclusion = it.next();
1536
 
1537
            if ( !buildExclusion.isProcessed() )
1538
            {
7032 dpurdie 1539
                if (buildExclusion.isImported() && ! buildExclusion.isARootCause() ) {
1540
                    // Remove from the exclusion list
1541
                    buildExclusion.includeToBuild(mReleaseManager, mBaseline);
7048 dpurdie 1542
                    mLogger.error("reportChange remove unused exclusion: {}", buildExclusion.info());
7032 dpurdie 1543
                } else {
1544
                    // Exclude and notify
1545
                    buildExclusion.excludeFromBuild(mReleaseManager, mBaseline);
1546
                    buildExclusion.email(this, mPackageCollection);
1547
                    counter++;
1548
                }
6914 dpurdie 1549
            }
1550
        }
7048 dpurdie 1551
        mLogger.error("reportChange exclusion count: {}", counter);
6914 dpurdie 1552
    }
1553
 
1554
    /**reports the build plan
1555
     */
1556
    public void reportPlan() throws SQLException, Exception
1557
    {
1558
        mReleaseManager.reportPlan(mRtagId, mBuildOrder);
1559
    }
1560
 
1561
    /**Returns the first build file from the collection
1562
     * The build file will be flagged as empty if none exists
1563
     */
1564
    public BuildFile getFirstBuildFileContent()
1565
    {
1566
        mLogger.debug("getFirstBuildFileContent");
1567
 
1568
        mBuildIndex = -1;
1569
        return getNextBuildFileContent();
1570
    }
1571
 
1572
    /**Returns next build file from the collection
1573
     * The build file will be flagged as empty if none exists
1574
     */
1575
    public BuildFile getNextBuildFileContent()
1576
    {
1577
        mLogger.debug("getNextBuildFileContent");
1578
        BuildFile retVal = null;
1579
 
1580
        try
1581
        {
1582
            mBuildIndex++;
1583
            retVal = mBuildCollection.get( mBuildIndex );
1584
        }
1585
        catch( IndexOutOfBoundsException e )
1586
        {
1587
            // Ignore exception. retVal is still null.
1588
        }
1589
 
1590
        if (retVal == null)
1591
        {
1592
            retVal = new BuildFile();
1593
        }
1594
 
7048 dpurdie 1595
        mLogger.debug("getNextBuildFileContent returned {}", retVal.state.name() );
6914 dpurdie 1596
        return retVal;
1597
    }
1598
 
1599
 
1600
    /**collects meta data associated with the baseline
1601
     * this is sufficient to send an indefinite pause email notification 
1602
     *  
1603
     * Escrow: Used once to collect information about the SBOM and associated Release 
1604
     *         mBaseline is an SBOMID 
1605
     * Daemon: Used each build cycle to refresh the information 
1606
     *          mBaseline is an RTAGID
1607
     */
1608
    public void collectMetaData() throws SQLException, Exception
1609
    {
1610
        Phase phase = new Phase("cmd");
7048 dpurdie 1611
        mLogger.debug("collectMetaData mDaemon {}", mDaemon);
6914 dpurdie 1612
 
1613
        try
1614
        {
1615
            phase.setPhase("connect");
1616
            mReleaseManager.connect();
1617
 
1618
            if (! mDaemon)
1619
            {
1620
                mSbomId = mBaseline;
1621
                phase.setPhase("queryRtagIdForSbom");
1622
                mRtagId = mReleaseManager.queryRtagIdForSbom(mBaseline);
1623
                if (mRtagId == 0)
1624
                {
7033 dpurdie 1625
                    mLogger.error("SBOM does not have a matching Release. Cannot be used as a base for an Escrow"); 
6914 dpurdie 1626
                    throw new Exception("rtagIdForSbom show stopper. SBOM does not have an associated Release");
1627
                }
1628
            }
1629
 
1630
            phase.setPhase("queryReleaseConfig");
1631
            mReleaseManager.queryReleaseConfig(mRtagId);
1632
 
1633
            if (mDaemon)
1634
            {
1635
                phase.setPhase("queryMailServer");
1636
                setMailServer(mReleaseManager.queryMailServer());
1637
                phase.setPhase("queryMailSender");
1638
                setMailSender(mReleaseManager.queryMailSender());
1639
                phase.setPhase("queryGlobalAddresses");
1640
                setMailGlobalTarget(mReleaseManager.queryGlobalAddresses());
1641
                phase.setPhase("queryProjectEmail");
1642
                mMailGlobalCollection = mReleaseManager.queryProjectEmail(mBaseline);
1643
                phase.setPhase("mMailGlobalTarget");
1644
                mMailGlobalCollection.add(0,getMailGlobalTarget());
1645
            }
1646
            phase.setPhase("queryBaselineName");
1647
            mBaselineName = mReleaseManager.queryBaselineName(mBaseline);
1648
            phase.setPhase("Done");
1649
        }
1650
        finally
1651
        {
1652
            // this block is executed regardless of what happens in the try block
1653
            // even if an exception is thrown
1654
            // ensure disconnect
1655
            mReleaseManager.disconnect();
1656
        }
1657
    }
1658
 
1659
    /**
1660
     * Find Package by package alias
7070 dpurdie 1661
     * Searches the released package collection
6914 dpurdie 1662
     * @param   alias               - alias of package to locate
1663
     * @return  Package with the matching mAlias or NULL_PACKAGE if no package has the mAlias
1664
     */
1665
    public Package findPackage(String alias)
1666
    {
1667
        mLogger.debug("findPackage");
1668
 
1669
        Package retVal = mReleaseManager.findPackage(alias, mPackageCollection);
1670
 
7048 dpurdie 1671
        mLogger.info("findPackage returned {}", retVal.mName);
6914 dpurdie 1672
        return retVal;
1673
    }
7070 dpurdie 1674
 
6914 dpurdie 1675
    /**
1676
     * Sets the mBuildFile to -5 (indirectly dependent on package versions which are not reproducible) 
7048 dpurdie 1677
     * for the package and all dependent packages that are a part of the release set.
1678
     *  
7032 dpurdie 1679
     * @param p             The package being excluded 
1680
     * @param rootPvId      The PVID of the package that is causing the exclusion. Null or -ve values are special
1681
     *                      This package is the root cause, -2: Excluded by Ripple Stop 
6914 dpurdie 1682
     *                   
7032 dpurdie 1683
     * @param rootCause     Text message. Max 50 characters imposed by RM database 
1684
     * @param list          If not null, add build exclusion to specified list, else use default(mBuildExclusionCollection) list. Allows insertions while iterating the list.
1685
     * @param be            If not null, process provided BuildExclusion element, otherwise find-existing/create a BuildExclusion element
1686
     * @param dependentToo  True: Exclude all packages that depend on the excluded package 
6914 dpurdie 1687
     */
1688
    private void rippleBuildExclude(Package p, int rootPvId, String rootCause, ListIterator<BuildExclusion> list, BuildExclusion be, boolean dependentToo )
1689
    {
1690
        mLogger.debug("rippleBuildExclude");
7048 dpurdie 1691
 
6914 dpurdie 1692
        if ( p.mBuildFile == 0 || p.mBuildFile == 1 )
1693
        {
1694
            p.mBuildFile = -5;
7048 dpurdie 1695
            mLogger.info("rippleBuildExclude set mBuildFile to -5 for package {}", p.mAlias );
6914 dpurdie 1696
 
1697
            if ( be != null )
1698
            {
7032 dpurdie 1699
                be.setProcessed();
6914 dpurdie 1700
            }
1701
            else
1702
            {
1703
                //  If no be item has been provided, then scan the complete collection looking for a matching item
1704
                //  If found, process it, else add it (unprocessed)
1705
                boolean found = false;
1706
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1707
                {
1708
                    BuildExclusion buildExclusion = it.next();
1709
 
1710
                    if ( buildExclusion.compare(p.mId, rootPvId, rootCause))
1711
                    {
7032 dpurdie 1712
                        buildExclusion.setProcessed();
6914 dpurdie 1713
                        found = true;
1714
                        break;
1715
                    }
1716
                }
1717
 
1718
                if (!found)
1719
                {
1720
                    // Entry not found in the mBuildExclusionCollection
1721
                    // Mark all occurrences for this package as processed
1722
                    // These will be superseded by a new build exclusion entry
1723
                    for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1724
                    {
1725
                        BuildExclusion buildExclusion = it.next();
1726
 
1727
                        if ( buildExclusion.compare(p.mId))
1728
                        {
7032 dpurdie 1729
                            buildExclusion.setProcessed();
6914 dpurdie 1730
                        }
1731
                    }
1732
 
1733
                    BuildExclusion buildExclusion = new BuildExclusion(p.mId, rootPvId, rootCause, p.mTestBuildInstruction);
1734
 
1735
                    //
1736
                    //  Add the new build exclusion to a list
1737
                    //    Either the default list or a user-specified list
1738
                    if ( list == null )
1739
                    {
1740
                        mBuildExclusionCollection.add(buildExclusion);
1741
                    }
1742
                    else
1743
                    {
1744
                        // must use the ListIterator interface to add to the collection whilst iterating through it
1745
                        list.add(buildExclusion);
1746
                    }
1747
                }
1748
            }
1749
 
1750
            //  Locate ALL packages that depend on this package and exclude them too
1751
            //  This process will be recursive
1752
            //    Not sure that this it is efficient 
7048 dpurdie 1753
            //  Only ripple a build exclusion through for packages that are a part of the full release set
1754
            //  NewWIPs, ForcedRipples and TestBuilds will not force consumer packages to be excluded
6914 dpurdie 1755
            //
7048 dpurdie 1756
            if ( ! p.mIsNotReleased && dependentToo)
6914 dpurdie 1757
            {
7048 dpurdie 1758
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 1759
                {
1760
                    Package pkg = it.next();
1761
 
1762
                    if ( pkg != p )
1763
                    {
1764
                        for (Iterator<Package> it2 = pkg.mPackageDependencyCollection.iterator(); it2.hasNext(); )
1765
                        {
1766
                            Package dependency = it2.next();
1767
 
1768
                            if ( dependency == p )
1769
                            {
1770
                                rippleBuildExclude( pkg, rootPvId, null, list, null, dependentToo );
1771
                                break;
1772
                            }
1773
                        }
1774
                    }
1775
                }
1776
            }
1777
        }
7048 dpurdie 1778
        mLogger.info("rippleBuildExclude set {} {}", p.mName, p.mBuildFile);
6914 dpurdie 1779
    }
1780
 
1781
    /**Simple XML string escaping
1782
     * 
1783
     * @param xml		- String to escape
1784
     * @return		- A copy of the string with XML-unfriendly characters escaped 
1785
     */
1786
    public static String escapeXml( String xml )
1787
    {
1788
        xml = xml.replaceAll("&", "&amp;");
1789
        xml = xml.replaceAll("<", "&lt;");
1790
        xml = xml.replaceAll(">", "&gt;");
1791
        xml = xml.replaceAll("\"","&quot;");
1792
        xml = xml.replaceAll("'", "&apos;");
1793
        xml = xml.replaceAll("\\$", "\\$\\$");
1794
 
1795
        return xml;
1796
    }
1797
 
1798
    /** Quote a string or a string pair
1799
     *  If two strings are provided, then they will be joined with a comma.
1800
     *   
1801
     * @param text		- First string to quote
1802
     * @param text2		- Optional, second string
1803
     * @return A string of the form 'text','text2'
1804
     */
1805
    public static String quoteString(String text, String text2)
1806
    {
1807
        String result;
1808
        result =  "\'" + text + "\'";
1809
        if (text2 != null )
1810
        {
1811
            result +=  ",\'" + text2 + "\'";  
1812
        }
1813
        return result;
1814
    }
1815
 
1816
    /** Generate build file information
1817
     * 
1818
     */
1819
    private void generateBuildFiles() 
1820
    {
1821
 
1822
        // persist the build files
1823
        boolean allProcessed = false;
1824
        int buildFile = 1;
1825
        StringBuilder rawData = new StringBuilder();
1826
        StringBuilder setUp = new StringBuilder();
1827
 
1828
        mLogger.debug("generateBuildFiles");
1829
 
1830
        if ( mDaemon )
1831
        {
1832
            // all interesting packages in daemon mode match the following filter
1833
            buildFile = 3;
1834
        }
1835
 
1836
        //-----------------------------------------------------------------------
1837
        //    Generate the build file
1838
        do
1839
        {
1840
            BuildFile buildEntry = new  BuildFile();
1841
            buildEntry.state = BuildFileState.Dummy;
1842
            XmlBuilder xml = generateBuildFileHeader();
1843
 
1844
 
1845
            //	Generate properties for each package in this build level or lower build levels
1846
            //	The properties link the packageAlias to the PackageName and PackageVersion
1847
            //
1848
            //	[DEVI 54816] In escrow mode all unreproducible packages are included 
7070 dpurdie 1849
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1850
            {
1851
                Package p = it.next();
1852
 
1853
                if ( ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) ) || ( !mDaemon && p.mBuildFile == -2 ) )
1854
                {
1855
                    xml.addProperty(p.mAlias, p.mName + " " + p.mVersion + p.mExtension);
1856
                }
1857
            }
1858
 
1859
            //	UTF Support
1860
            //	Insert additional info into the build file to provide extra checking
1861
            //
7048 dpurdie 1862
            if ( ! mReleaseManager.mUseDatabase )
6914 dpurdie 1863
            {
1864
                // UTF Support
1865
                // Insert per-package planning information
1866
                //
7070 dpurdie 1867
                xml.addComment("mPackageCollection");
1868
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1869
                {
1870
                    Package p = it.next();
1871
                    generatePackageInfo(xml, p);
1872
                }
1873
 
7070 dpurdie 1874
                xml.addComment("mPackageCollectionWip");
1875
                for (Iterator<Package> it = mPackageCollectionWip.iterator(); it.hasNext(); )
1876
                {
1877
                    Package p = it.next();
1878
                    if (p.mIsNotReleased )
1879
                        generatePackageInfo(xml, p);
1880
                }
1881
 
1882
                xml.addComment("mPackageCollectionTest");
1883
                for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
1884
                {
1885
                    Package p = it.next();
1886
                    if (p.mIsNotReleased )
1887
                        generatePackageInfo(xml, p);
1888
                }
1889
 
1890
                xml.addComment("mPackageCollectionTestRipple");
1891
                for (Iterator<Package> it = mPackageCollectionRipple.iterator(); it.hasNext(); )
1892
                {
1893
                    Package p = it.next();
1894
                    if (p.mIsNotReleased )
1895
                        generatePackageInfo(xml, p);
1896
                }
1897
 
6914 dpurdie 1898
                // UTF Support
1899
                // Insert build exclusion information
1900
                xml.addComment("mBuildExclusionCollection");
1901
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1902
                {
1903
                    BuildExclusion buildExclusion = it.next();
1904
                    if (!buildExclusion.isProcessed())
1905
                    {
1906
                        xml.addComment(buildExclusion.info());
1907
                    }
1908
                }
1909
 
1910
                // UTF Support
1911
                // Insert build Plan
1912
                if (mDaemon)
1913
                {
1914
                    xml.addComment("mBuildOrder");
1915
                    int order = 0;
1916
                    for (Iterator<Package> it = mBuildOrder.iterator(); it.hasNext(); )
1917
                    {
1918
                        Package p = it.next();
1919
                        String comment =
1920
                                "pvid="+ p.mId +
7048 dpurdie 1921
                                " order=" + (++order) +
7070 dpurdie 1922
                                " Rorder=" + (p.mRippleOrder) +
1923
                                " time=" + p.mRippleTime +
6914 dpurdie 1924
                                " name=\"" + p.mAlias + "\"";
1925
                        xml.addComment(comment);
1926
                    }
1927
                }
1928
            }
1929
 
1930
            //  Generate Taskdef information
1931
            generateTaskdef(xml);
1932
 
1933
            //
1934
            //  Insert known Machine Information
1935
            //  Escrow usage: 
1936
            //      Map machType to machClass
1937
            //  Also serves as a snapshot of the required build configuration
1938
            //  ie: machine types and buildfilters
1939
            //
1940
            if (!mDaemon)
1941
            {
1942
                generateMachineInfo(xml, null);
1943
            }
1944
 
1945
            //
1946
            //	Generate target rules for each package to be built within the current build file
1947
            //
1948
            boolean daemonHasTarget = false;
1949
 
7048 dpurdie 1950
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 1951
            {
1952
                Package p = it.next();
1953
 
1954
                if ( p.mBuildFile > 0 && p.mBuildFile <= buildFile )
1955
                {
1956
                    generateTarget(xml, buildEntry, p, buildFile);
1957
 
1958
                    if ( p.mBuildFile == 1 )
1959
                    {
1960
                        daemonHasTarget = true;
1961
 
1962
                        // Retain information about the target package
1963
                        buildEntry.mPkgId = p.mPid;
1964
                        buildEntry.mPvId = p.mId;
1965
                    }
1966
                }
1967
 
1968
                //	Generate escrow extraction commands
1969
                //	Only done on the first pass though the packages
1970
                //
1971
                if ( !mDaemon && buildFile == 1 )
1972
                {
1973
                    setUp.append("jats jats_vcsrelease -extractfiles"
1974
                                + " \"-label=" + p.mVcsTag + "\""
1975
                                + " \"-view=" + p.mAlias + "\""
1976
                                + " -root=. -noprefix"
1977
                                + mlf );
1978
                }
1979
 
1980
                //	Generate escrow raw CSV data
1981
                //	Note: I don't think this data is used at all
1982
 
1983
                if ( !mDaemon && ( p.mBuildFile == buildFile))
1984
                {
1985
                    StringAppender machines = new StringAppender(",");
1986
                    for (Iterator<BuildStandard> it1 = p.mBuildStandardCollection.iterator(); it1.hasNext();)
1987
                    {
1988
                        BuildStandard bs = it1.next();
1989
                        machines.append(bs.mMachClass);
1990
                    }
1991
 
1992
                    rawData.append(p.mAlias + "," +
1993
                                    buildFile + "," +
1994
                                    machines +
1995
                                    mlf);
1996
                }
1997
            }
1998
 
1999
            if ( mDaemon && !daemonHasTarget )
2000
            {
2001
                // must have AbtTestPath, AbtSetUp, AbtTearDown, and AbtPublish targets
2002
                XmlBuilder target = xml.addNewElement("target");
2003
                target.addAttribute("name", "AbtTestPath");
2004
 
2005
                target = xml.addNewElement("target");
2006
                target.addAttribute("name", "AbtSetUp");
2007
 
2008
                target = xml.addNewElement("target");
2009
                target.addAttribute("name", "AbtTearDown");
2010
 
2011
                target = xml.addNewElement("target");
2012
                target.addAttribute("name", "AbtPublish");
2013
            }
2014
 
2015
            generateDefaultTarget( xml, buildFile);
2016
 
2017
            //	Convert the Xml structure into text and save it in the build file
2018
            //	Add this build file to the mBuildCollection
2019
            buildEntry.content = mXmlHeader + xml.toString();
2020
            mBuildCollection.add(buildEntry);
2021
 
2022
            // are more build files required
2023
            allProcessed = true;
2024
 
2025
            if (!mDaemon)
2026
            {
2027
                // this is escrow mode centric
7048 dpurdie 2028
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2029
                {
2030
                    Package p = it.next();
2031
 
2032
                    if ( p.mBuildFile > buildFile )
2033
                    {
2034
                        // more build files are required
2035
                        allProcessed = false;
7048 dpurdie 2036
                        mLogger.info("planRelease reiterating package has no build requirement {} {} {}",p.mName, p.mBuildFile,  buildFile);
6914 dpurdie 2037
                        break;
2038
                    }
2039
                } 
2040
 
2041
                buildFile++;
2042
            }
2043
 
2044
        } while( !allProcessed );
2045
 
2046
        //	Save additional escrow data
2047
        if ( !mDaemon )
2048
        {
2049
            mEscrowSetup = setUp.toString();
2050
            mEscrowRawData = rawData.toString();
2051
        }
2052
    }
2053
 
2054
    /**returns a build file header for the mBaseline
2055
     */
2056
    private XmlBuilder generateBuildFileHeader()
2057
    {
2058
        mLogger.debug("generateBuildFileHeader");
2059
        XmlBuilder element = new XmlBuilder("project");
2060
 
2061
        element.addAttribute("name", "mass");
2062
        element.addAttribute("default", "full");
2063
        element.addAttribute("basedir", ".");
2064
 
2065
        if ( mDaemon )
2066
        {
2067
            element.addProperty("abt_mail_server", getMailServer());
2068
            element.addProperty("abt_mail_sender", getMailSender()); 
2069
            element.addProperty("abt_rtag_id", mBaseline);
2070
            element.addProperty("abt_daemon", mReleaseManager.currentTimeMillis());
2071
            element.makePropertyTag("abt_packagetarball", true);
2072
            element.makePropertyTag("abt_usetestarchive", !ReleaseManager.getUseMutex());
2073
 
7048 dpurdie 2074
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2075
            {
2076
                Package p = it.next();
2077
 
2078
                if ( p.mBuildFile == 1 )
2079
                {
2080
                    element.addProperty("abt_package_name", p.mName);
2081
                    element.addProperty("abt_package_version", p.mVersion + p.mExtension);
2082
                    element.addProperty("abt_package_extension", p.mExtension);
2083
                    element.addProperty("abt_package_location", getBuildLocation(p));
2084
                    element.addProperty("abt_package_ownerlist", p.emailInfoNonAntTask(this));
2085
                    element.addProperty("abt_package_build_info", buildInfoText(p));
2086
 
2087
                    // depends in the form 'cs','25.1.0000.cr';'Dinkumware_STL','1.0.0.cots'
2088
                    StringAppender depends = new StringAppender(";");
2089
 
2090
                    for (Iterator<Package> it3 = p.mPackageDependencyCollection.iterator(); it3.hasNext(); )
2091
                    {
2092
                        Package depend = it3.next();
2093
                        depends.append( quoteString(depend.mName, depend.mVersion + depend.mExtension) );
2094
                    }
2095
 
2096
                    element.addProperty("abt_package_depends", depends.toString());
2097
                    element.addProperty("abt_is_ripple", p.mDirectlyPlanned ? "0" : "1");
2098
                    element.addProperty("abt_build_reason", p.mBuildReason.toString());
2099
                    element.addProperty("abt_package_version_id", p.mId);
2100
                    element.addProperty("abt_does_not_require_source_control_interaction", ! p.mRequiresSourceControlInteraction ? "true" : "false" );
2101
                    element.addProperty("abt_test_build_instruction", p.mTestBuildInstruction);
2102
                }
2103
            }
2104
        }
2105
        else
2106
        {
2107
            //    Escrow Mode
2108
            element.addProperty("abt_rtag_id", mRtagId);
2109
            element.addProperty("abt_sbom_id", mSbomId);
2110
        }
2111
 
2112
        element.addProperty("abt_release", escapeXml(mBaselineName));
2113
        element.addProperty("abt_buildtool_version", mReleaseManager.getMajorVersionNumber() );
2114
 
2115
        element.addNewElement("condition")
2116
        .addAttribute("property", "abt_family")
2117
        .addAttribute("value", "windows")
2118
        .addNewElement("os")
2119
        .addAttribute("family", "windows");
2120
        element.addProperty("abt_family", "unix");
2121
 
2122
        return element;
2123
    }
2124
 
2125
    /** Add task def XML items taskdef for the abt ant task
2126
     * @param xml 	- xml item to extend
2127
     */
2128
    private void generateTaskdef(XmlBuilder xml)
2129
    {
2130
        mLogger.debug("generateTaskdef");
2131
        xml.addNewElement("taskdef")
2132
        .addAttribute("name", "abt")
2133
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABT");
2134
 
2135
        xml.addNewElement("taskdef")
2136
        .addAttribute("name", "abtdata")
2137
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABTData");
2138
    }
2139
 
2140
    /** returns the command abtdata items
2141
     *  <br>Common machine information
2142
     *  <br>Common email address
2143
     *  
2144
     *  
2145
     *  @param	xml - Xml element to extend   
2146
     *  @param    p - Package (May be null)
2147
     */
2148
    private void generateMachineInfo(XmlBuilder xml, Package p)
2149
    {
2150
        XmlBuilder element = xml.addNewElement("abtdata");
2151
        element.addAttribute("id", "global-abt-data");
2152
 
2153
        //
2154
        //  Iterate over all the machines and create a nice entry
2155
        //
2156
        for (Iterator<ReleaseConfig> it = mReleaseManager.mReleaseConfigCollection.mReleaseConfig.iterator(); it.hasNext(); )
2157
        {
2158
            ReleaseConfig rc = it.next();
2159
            element.addElement(rc.getMachineEntry());
2160
        }
2161
 
2162
        //
2163
        //  Now the email information
2164
        //
2165
        if ( p != null)
2166
        {
2167
            p.emailInfo(this, element);
2168
        }
2169
    }
2170
 
2171
    /** Generate package information
2172
     *  Only when running unit tests
2173
     *  
2174
     * @param xml	- An xml element to append data to
2175
     * @param p	- Package to process
2176
     */
2177
    private void generatePackageInfo (XmlBuilder xml, Package p)
2178
    {
7051 dpurdie 2179
        String joiner = "";
2180
 
6914 dpurdie 2181
        String comment =
2182
                "pvid="+ p.mId + 
2183
                " name=\"" + p.mAlias + "\""+
2184
                " reason=" + p.mNoBuildReason +" "+ 
2185
                " buildFile=" + p.mBuildFile + " "+
2186
                " directlyPlanned=" + p.mDirectlyPlanned + " "+
7051 dpurdie 2187
                " indirectlyPlanned=" + p.mIndirectlyPlanned + " depends=[" ;
2188
 
2189
        for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
2190
        {
2191
            String alias = it2.next();
2192
            comment += joiner + alias;
2193
            joiner = ",";
2194
        }
2195
 
2196
        comment += "]";
6914 dpurdie 2197
 
2198
        xml.addComment(comment);            
2199
    }
2200
 
2201
    /**returns an ant target for the passed Package
2202
     * in daemon mode:
2203
     *  packages are categorized with one of three mBuildFile values:
2204
     *   1 the package to be built by this buildfile
2205
     *   2 the packages with a future build requirement
2206
     *   3 the packages with no build requirement
2207
     *  the returned target depends on this categorization and will have
2208
     *   1 full abt info
2209
     *   2 full dependency info to determine future build ordering but no abt info (will not build this package)
2210
     *   3 only a name attribute (will not build this package)
2211
     * in escrow mode:
2212
     *  if the passed Package's mBuildFile is different (less than) the passed build file,
2213
     *  the returned target have only a name attribute (will not build this package)
2214
     *   
2215
     * @param xml - Xml element to extend
2216
     * @param buildEntry - Record build type (dummy/generic/not generic)
2217
     * @param p - Package to process
2218
     * @param buildFile - buildfile level being processed
2219
     */
2220
    private void generateTarget(XmlBuilder xml, BuildFile buildEntry, Package p, int buildFile)
2221
    {
2222
        mLogger.debug("generateTarget");
2223
 
2224
        //---------------------------------------------------------------------
2225
        //  Generate the AbtData - common machine and email information
2226
        //  Only used by the daemon builds
2227
        //
2228
        if ( mDaemon && p.mBuildFile == 1 )
2229
        {
2230
            generateMachineInfo(xml, p );
2231
        }
2232
 
2233
        //-------------------------------------------------------------------------
2234
        //  Generate the <target name=... /> construct
2235
        //  There are two types
2236
        //      1) Simple dummy place holder. Just has the PackageName.PackageExt
2237
        //      2) Full target. Has all information to build the package including
2238
        //              AbtSetUp, AbtTearDown and AbtPublish targets
2239
        //
2240
 
2241
        if ( !mDaemon && ( p.mBuildFile < buildFile ) )
2242
        {
2243
            XmlBuilder target = xml.addNewElement("target");
2244
            target.addAttribute("name", p.mAlias);
2245
        }
2246
        else
2247
        {
2248
            if (!mDaemon) 
2249
            {
2250
                //  Escrow Only:
2251
                //  Generate the 'wrapper' target
2252
                //  This is used to ensure that the required dependencies have been built - I think
2253
                //
2254
                StringAppender dependList = new StringAppender(",");
2255
                if ( !p.mPackageDependencyCollection.isEmpty() )
2256
                {
2257
                    for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2258
                    {
2259
                        Package dependency = it.next();
2260
                        if ( !mDaemon && dependency.mBuildFile == -2 )
2261
                        {
2262
                            // ignore targets which build in foreign environments in escrow mode
2263
                            continue;
2264
                        }
2265
                        dependList.append(dependency.mAlias);
2266
                    }
2267
                }
2268
 
2269
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2270
                target.addAttribute("name", p.mAlias + ".wrap");
2271
 
2272
                if (dependList.length() > 0)
2273
                {
2274
                    target.addAttribute("depends", dependList.toString() );
2275
                }
2276
 
2277
                if ( !mDaemon )
2278
                {
2279
                    boolean hasDependenciesBuiltInThisIteration = false;
2280
                    if ( ( !p.mPackageDependencyCollection.isEmpty()) )
2281
                    {
2282
                        for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2283
                        {
2284
                            Package dependency = it.next();
2285
 
2286
                            if ( dependency.mBuildFile == buildFile )
2287
                            {
2288
                                hasDependenciesBuiltInThisIteration = true;
2289
                                break;
2290
                            }
2291
                        }
2292
                    }
2293
 
2294
                    if ( hasDependenciesBuiltInThisIteration )
2295
                    {
2296
                        XmlBuilder condition = target.addNewElement("condition");
2297
                        condition.addAttribute("property",  p.mAlias + ".build");
2298
 
2299
                        XmlBuilder and = condition.addNewElement("and");
2300
 
2301
                        for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2302
                        {
2303
                            Package dependency = it.next();
2304
 
2305
                            if ( dependency.mBuildFile == buildFile )
2306
                            {
2307
                                XmlBuilder or = and.addNewElement("or");
2308
 
2309
                                XmlBuilder equal1 = or.addNewElement("equals");
2310
                                equal1.addAttribute("arg1", "${" + dependency.mAlias + ".res}");
2311
                                equal1.addAttribute("arg2", "0");
2312
 
2313
                                XmlBuilder equal2 = or.addNewElement("equals");
2314
                                equal2.addAttribute("arg1", "${" + dependency.mAlias + ".res}");
2315
                                equal2.addAttribute("arg2", "257");
2316
                            }
2317
                        }
2318
                    }
2319
                    else
2320
                    {
2321
                        target.addProperty(p.mAlias + ".build", "");
2322
                    }
2323
                }
2324
            }
2325
 
2326
 
2327
            //
2328
            //  Generate the 'body' of the target package
2329
            //  Escrow Mode: Always
2330
            //  Daemon Mode: Only for the one target we are building
2331
            //                  Simplifies the XML
2332
            //                  Reduces noise in the logs
2333
            //              Don't add target dependencies. 
2334
            //                  We are only building one target and the 
2335
            //                  dependency management has been done way before now.
2336
            //                  All it does is makes the logs noisy.
2337
            //
2338
            if ( ( mDaemon && p.mBuildFile == 1 ) || !mDaemon )
2339
            {
2340
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2341
                target.addAttribute("name", p.mAlias);
2342
 
2343
                if ( !mDaemon )
2344
                {
2345
                    target.addAttribute("depends",  p.mAlias + ".wrap");
2346
                    target.addAttribute("if",p.mAlias + ".build");
2347
                }
2348
 
2349
                if ( mDaemon && p.mBuildFile == 1 )
2350
                {
2351
                    target.addProperty(p.mAlias + "pkg_id",p.mPid);
2352
                    target.addProperty(p.mAlias + "pv_id",p.mId);
2353
                }
2354
 
2355
                target.addProperty(p.mAlias + "packagename",p.mName);        		
2356
                target.addProperty(p.mAlias + "packageversion",p.mVersion);
2357
                target.addProperty(p.mAlias + "packageextension",p.mExtension);
2358
                target.addProperty(p.mAlias + "packagevcstag",p.mVcsTag);
2359
 
2360
                target.makePropertyTag(p.mAlias + "directchange", p.mDirectlyPlanned); 
2361
                target.makePropertyTag(p.mAlias + "doesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2362
 
2363
                buildEntry.state = BuildFile.BuildFileState.NonGeneric;
2364
                if ( p.isGeneric() )
2365
                {
2366
                    buildEntry.state = BuildFile.BuildFileState.Generic;
2367
                    target.makePropertyTag(p.mAlias + "generic", true); 
2368
                }
2369
 
2370
                target.addProperty(p.mAlias + "loc", getBuildLocation(p));
2371
                target.makePropertyTag(p.mAlias + "unittests", p.mHasAutomatedUnitTests && mDaemon);
2372
 
2373
                //    Add our own task and associated information
2374
                //
2375
                XmlBuilder abt = target.addNewElement("abt").isExpanded();
2376
 
2377
                for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2378
                {
2379
                    Package dependency = it.next();
2380
                    XmlBuilder depend = abt.addNewElement("depend");
2381
                    depend.addAttribute("package_alias", "${" + dependency.mAlias + "}");
2382
                }
2383
 
2384
                buildInfo(abt,p);
2385
 
2386
                if ( mDaemon && p.mBuildFile == 1 )
2387
                {
2388
                    //    AbtTestPath
2389
                    target = xml.addNewElement("target").isExpanded();
2390
                    target.addAttribute("name", "AbtTestPath");
2391
                    target.addProperty("AbtTestPathpackagevcstag", p.mVcsTag);
2392
                    target.addProperty("AbtTestPathpackagename", p.mName);
2393
                    abt = target.addNewElement("abt").isExpanded();
2394
                    buildInfo(abt, p);
2395
 
2396
 
2397
                    //    AbtSetUp
2398
                    target = xml.addNewElement("target").isExpanded();
2399
                    target.addAttribute("name", "AbtSetUp");
2400
                    target.addProperty("AbtSetUppackagevcstag", p.mVcsTag);
2401
                    target.addProperty("AbtSetUppackagename", p.mName);
2402
 
2403
                    abt = target.addNewElement("abt").isExpanded();
2404
                    buildInfo(abt, p);
2405
 
2406
                    //    AbtTearDown
2407
                    target = xml.addNewElement("target").isExpanded();
2408
                    target.addAttribute("name", "AbtTearDown");
2409
                    target.addProperty("AbtTearDownpackagevcstag", p.mVcsTag);
2410
                    target.addProperty("AbtTearDownpackagename", p.mName);
2411
                    target.addProperty("AbtTearDownpackageversion", p.mVersion);
2412
                    target.addProperty("AbtTearDownpackageextension", p.mExtension);
2413
                    target.makePropertyTag(p.mAlias + "generic", p.isGeneric());
2414
 
2415
                    abt = target.addNewElement("abt").isExpanded();
2416
                    buildInfo(abt, p);
2417
 
2418
 
2419
                    //  AbtPublish
2420
                    target = xml.addNewElement("target").isExpanded();
2421
                    target.addAttribute("name", "AbtPublish");
2422
 
2423
                    target.addProperty("AbtPublishpackagevcstag", p.mVcsTag);
2424
                    target.addProperty("AbtPublishpackagename", p.mName);
2425
                    target.addProperty("AbtPublishpackageversion", p.mVersion);
2426
                    target.addProperty("AbtPublishpackageextension", p.mExtension);
2427
                    target.makePropertyTag("AbtPublishdirectchange", p.mDirectlyPlanned);
2428
                    target.makePropertyTag("AbtPublishdoesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2429
                    target.makePropertyTag("AbtPublishgeneric", p.isGeneric());
2430
                    target.addProperty("AbtPublishloc", getBuildLocation(p));
2431
 
2432
                    abt = target.addNewElement("abt").isExpanded();
2433
                    buildInfo(abt, p);
2434
 
2435
                }
2436
            }
2437
        }
2438
    }
2439
 
2440
    /** Extends the xml object. Adds ant default target for the current build iteration
2441
     * @param xml - The XmlBuilder Object to extend
2442
     * @param buildFile - The current build file level. This differs for Daemon and Escrow mode. In Daemon mode it will not be a '1' 
2443
     */
2444
    private void generateDefaultTarget(XmlBuilder xml, int buildFile)
2445
    {
2446
        mLogger.debug("generateDefaultTarget");
2447
 
2448
        XmlBuilder target = xml.addNewElement("target").isExpanded();
2449
        target.addAttribute("name", "fullstart");
2450
 
2451
        if (buildFile == 1)
2452
        {
2453
            antEcho(target, "${line.separator}" + mAnyBuildPlatforms + "${line.separator}${line.separator}");
7048 dpurdie 2454
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2455
            {
2456
                Package p = it.next();
2457
 
2458
                if ( p.mBuildFile == -1 )
2459
                {
2460
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2461
                }
2462
            }
2463
 
2464
            antEcho(target, "${line.separator}" + mAssocBuildPlatforms + "${line.separator}${line.separator}");
7048 dpurdie 2465
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2466
            {
2467
                Package p = it.next();
2468
 
2469
                if ( p.mBuildFile == -2 )
2470
                {
2471
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2472
                }
2473
            }
2474
 
2475
            antEcho(target, "${line.separator}" + mNotInBaseline + "${line.separator}${line.separator}");
7048 dpurdie 2476
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2477
            {
2478
                Package p = it.next();
2479
 
2480
                if ( p.mBuildFile == -4 )
2481
                {
2482
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2483
                }
2484
            }
2485
 
2486
            antEcho(target, "${line.separator}" + mDependent + "${line.separator}${line.separator}");
7048 dpurdie 2487
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2488
            {
2489
                Package p = it.next();
2490
 
2491
                if ( p.mBuildFile == -5 )
2492
                {
2493
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2494
                }
2495
            }
2496
        }
2497
 
2498
        if ( !mDaemon )
2499
        {
2500
            antEcho(target, "${line.separator}Build Started:${line.separator}${line.separator}");
2501
        }
2502
 
2503
        //
2504
        //	Create a comma separated list of all the required targets
2505
        //      Escrow : All packages
2506
        //      Daemon : Just the package being built
2507
        //
2508
        StringAppender dependList = new StringAppender(",");
2509
        dependList.append("fullstart");
7048 dpurdie 2510
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2511
        {
2512
            Package p = it.next();
2513
 
2514
            if ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) )
2515
            {
2516
                if ((mDaemon && p.mBuildFile == 1) || !mDaemon)
2517
                {
2518
                    dependList.append(p.mAlias);                    
2519
                }
2520
            }
2521
        }
2522
 
2523
        target = xml.addNewElement("target").isExpanded();
2524
        target.addAttribute("name", "full");
2525
        target.addAttribute("depends", dependList.toString());
2526
 
2527
        if ( !mDaemon )
2528
        {
2529
            antEcho(target, "${line.separator}Build Finished${line.separator}");
2530
        }
2531
    }
2532
 
2533
    /** Internal helper function to create an ant 'echo statement
2534
     *  Many of the parameters are fixed
2535
     */
2536
    private void antEcho( XmlBuilder xml, String message)
2537
    {
2538
        XmlBuilder msg = xml.addNewElement("echo");
2539
        msg.addAttribute("message", message);
2540
        msg.addAttribute("file", "publish.log");
2541
        msg.addAttribute("append", "true");
2542
    }
2543
 
2544
    /**sets the mIndirectlyPlanned true for the package and all dependent packages
2545
     */
2546
    private void rippleIndirectlyPlanned(Package p)
2547
    {
2548
        mLogger.debug("rippleIndirectlyPlanned");
2549
        if ( !p.mIndirectlyPlanned && p.mBuildFile == 0 )
2550
        {
2551
            p.mIndirectlyPlanned = true;
2552
 
7048 dpurdie 2553
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2554
            {
2555
                Package pkg = it.next();
2556
 
2557
                if ( pkg != p )
2558
                {
2559
                    for (Iterator<Package> it2 = pkg.mPackageDependencyCollection.iterator(); it2.hasNext(); )
2560
                    {
2561
                        Package dependency = it2.next();
2562
 
2563
                        if ( dependency == p )
2564
                        {
2565
                            rippleIndirectlyPlanned( pkg );
2566
                            break;
2567
                        }
2568
                    }
2569
                }
2570
            }
2571
        }
7048 dpurdie 2572
        mLogger.info("rippleIndirectlyPlanned set {} {}", p.mName, p.mIndirectlyPlanned);    
6914 dpurdie 2573
    }
2574
 
2575
    /**accessor method
2576
     */
2577
    public String getEscrowSetUp()
2578
    {
2579
        mLogger.debug("getEscrowSetUp");
2580
        String retVal = mEscrowSetup;
2581
 
7048 dpurdie 2582
        mLogger.debug("getEscrowSetUp returned {}", retVal);
6914 dpurdie 2583
        return retVal;
2584
    }
2585
 
2586
    /**accessor method
2587
     */
2588
    public String getRawData()
2589
    {
2590
        mLogger.debug("getRawData");
2591
        String retVal = mEscrowRawData;
2592
 
7048 dpurdie 2593
        mLogger.debug("getRawData returned {}", retVal);
6914 dpurdie 2594
        return retVal;
2595
    }
2596
 
2597
    /**Get the build loc (location)
2598
     * This is package specific and will depend on the build mode (Escrow/Daemon)
2599
     * 
2600
     * @param	p - Package being built
2601
     * @return A string that describes the build location
2602
     */
2603
    private String getBuildLocation(Package p)
2604
    {
2605
        mLogger.debug("locationProperty");
2606
        String location = "";
2607
 
2608
        if (mDaemon)
2609
        {
2610
            // Daemon: Start in root of view/workspace
2611
            location += mBaseline;
2612
        }
2613
        else
2614
        {
2615
            // Escrow: mAlias used with jats -extractfiles -view
2616
            location += p.mAlias;
2617
        }
2618
 
2619
        //
2620
        //  Always use '/' as a path separator - even if user has specified '\'
2621
        //  Ant can handle it.
2622
        //
2623
        location = location.replace('\\', '/');
2624
        return location;
2625
    }
2626
 
2627
    /**Adds package build into as XML elements 
2628
     * @param	  xml 	- Xml element to extend
2629
     * @param   p       - Package to process
2630
     */
2631
    private void buildInfo(XmlBuilder xml, Package p)
2632
    {
2633
        mLogger.debug("buildInfo");
2634
 
2635
        //
2636
        // Create the xml build information
2637
        // <platform gbe_machtype="linux_i386" type="jats" arg="all"/>
2638
        //
2639
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext();)
2640
        {
2641
            BuildStandard bs = it.next();
2642
            bs.getBuildStandardXml(xml);
2643
        }
2644
    }
2645
 
2646
    /**returns the buildInfo as a single line of text
2647
     * Used for reporting purposes only
2648
     * @param   p       - Package to process
2649
     * 
2650
     */
2651
    public String buildInfoText(Package p)
2652
    {
2653
        mLogger.debug("buildInfoText");
2654
 
2655
        StringAppender result = new StringAppender (";");
2656
 
2657
        //
2658
        //  Create platform:standards
2659
        //      
2660
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext(); )
2661
        {
2662
            BuildStandard bs = it.next();
2663
 
2664
            if ( bs.isActive() )
2665
            {
2666
                String info = bs.getBuildStandardText();
2667
                result.append(info);
2668
            }
2669
        }
2670
 
7048 dpurdie 2671
        mLogger.info("buildInfoText returned {}", result);
6914 dpurdie 2672
        return result.toString();
2673
    }
2674
 
2675
    /**prints to standard out in escrow mode only
2676
     * <br>Prints a title and information. The title is only printed once.
2677
     * 
2678
     * @param header - The message title to display, if printMessage is true
2679
     * @param text - A package name. Really just the 2nd line of the message
2680
     * @param printHeader -  Controls the printing of the message argument
2681
     */
2682
    private void standardOut(final String header, final String text, boolean printHeader)
2683
    {
2684
        mLogger.debug("standardOut");
2685
        if (!mDaemon)
2686
        {
2687
            if ( printHeader )
2688
            {
2689
                System.out.println(header);
2690
            }
2691
 
2692
            System.out.println(text);
2693
        }
2694
    }
2695
 
2696
 
2697
    /**
2698
     *  Email users about a rejected daemon instruction
2699
     *  @param  reason  - Reason for the rejection
2700
     *  @param  pkg     - Package to be affected by the instruction
2701
     *  
2702
     */
2703
    public void emailRejectedDaemonInstruction(String reason, Package p)
2704
    {
2705
        mLogger.debug("emailRejectedDaemonInstruction");
2706
 
2707
        //  Email Subject
2708
        String subject = "BUILD FAILURE of Daemon Instruction on package " + p.mAlias;
2709
 
2710
        // Email Body
2711
        String mailBody = "The build system reject the the Daemon Instruction";
2712
        mailBody += "<br>Reason: " + reason; 
2713
 
2714
        mailBody += "<p>Release: " + mBaselineName 
2715
                +  "<br>Package: " + p.mAlias 
2716
                +  "<br>Rm Ref: " + CreateUrls.generateRmUrl(getRtagId(), p.mId); 
2717
 
2718
        mailBody += "<p><hr>";
2719
 
2720
        String target = p.emailInfoNonAntTask(this);
2721
 
7048 dpurdie 2722
        mLogger.error("emailRejectedDaemonInstruction Server: {}", getMailServer());
2723
        mLogger.error("emailRejectedDaemonInstruction Sender: {}", getMailSender());
2724
        mLogger.error("emailRejectedDaemonInstruction Target: {}", target);
6914 dpurdie 2725
 
2726
        try
2727
        {
2728
            //    
7048 dpurdie 2729
            Smtpsend.send(getMailServer(),  // mailServer
2730
                    getMailSender(),        // source
2731
                    target,                 // target
2732
                    getMailSender(),        // cc
2733
                    null,                   // bcc
2734
                    subject,                // subject
2735
                    mailBody,               // body
2736
                    null                    // attachment
6914 dpurdie 2737
                    );
2738
        } catch (Exception e)
2739
        {
7048 dpurdie 2740
            mLogger.warn("Email Failure: emailRejectedDaemonInstruction:{}", e.getMessage());
6914 dpurdie 2741
        }
2742
    }
2743
 
2744
    /**
2745
     * @return the mMailServer
2746
     */
2747
    public String getMailServer() {
2748
        return mMailServer;
2749
    }
2750
 
2751
    /**
2752
     * @param mMailServer the mMailServer to set
2753
     */
2754
    public void setMailServer(String mMailServer) {
2755
        this.mMailServer = mMailServer;
2756
    }
2757
 
2758
    /**
2759
     * @return the mMailSender
2760
     */
2761
    public String getMailSender() {
2762
        return mMailSender;
2763
    }
2764
 
2765
    /**
2766
     * @param mMailSender the mMailSender to set
2767
     */
2768
    public void setMailSender(String mMailSender) {
2769
        this.mMailSender = mMailSender;
2770
    }
2771
 
2772
    /**
2773
     * @return the mMailGlobalTarget
2774
     */
2775
    public String getMailGlobalTarget() {
2776
        return mMailGlobalTarget;
2777
    }
2778
 
2779
    /**
2780
     * @param mMailGlobalTarget the mMailGlobalTarget to set
2781
     */
2782
    public void setMailGlobalTarget(String mMailGlobalTarget) {
2783
        this.mMailGlobalTarget = mMailGlobalTarget;
2784
    }
2785
 
2786
}