Subversion Repositories DevTools

Rev

Rev 7070 | 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
7071 dpurdie 446
                rippleBuildExclude(p, p.mId, "Package has circular dependency", null, null, true, false);
6914 dpurdie 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
7071 dpurdie 485
                    rippleBuildExclude(p, p.mId, "Package build dependency not in the release", null, null, true, true);
6914 dpurdie 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
7071 dpurdie 523
                    rippleBuildExclude(p, p.mId, "Package has no build environment", null, null, false, true);
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
        //
544
        mLogger.debug("planRelease process packages which are not reproducible2");
7048 dpurdie 545
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 546
        {
547
            Package p = it.next();
548
 
549
            if (p.mBuildFile == 0)
550
            {
551
                if ( mDaemon )
552
                {
553
                    //  Daemon Mode Only
554
                    //  Not interested in the reproducibility of a pegged package or a package provided from an SDK.
555
                    //  Such packages will be deemed to be reproducible - but out side of this release
556
                    if (p.mIsPegged || p.mIsSdk)
557
                    {
558
                        continue;
559
                    }
560
                }
561
 
562
                // package has yet to be processed
563
                // assume it does not need to be reproduced for this baseline
564
                //
565
                //    For each machineClass in the buildset
566
                boolean reproduce = false;
567
 
568
                for (Iterator<String> it2 = mReleaseManager.mReleaseConfigCollection.mMachineClasses.iterator(); it2.hasNext(); )
569
                {
570
                    String machineClass = it2.next();
571
 
572
                    if ( p.canBeBuildby(machineClass))
573
                    {
574
                        reproduce = true;
7048 dpurdie 575
                        mLogger.info("planRelease package built on {} {}", machineClass, p.mAlias );
6914 dpurdie 576
                        break;
577
                    }
578
                }
579
 
580
                if ( !reproduce )
581
                {
7048 dpurdie 582
                    mLogger.info("planRelease package not reproducible on the build platforms configured for this baseline {}", p.mName);
6914 dpurdie 583
 
7048 dpurdie 584
                    // max 50 chars
7071 dpurdie 585
                    rippleBuildExclude(p, p.mId, "Package not built for configured platforms", null, null, false, true);
6914 dpurdie 586
 
587
                    // package is not reproducible on the build platforms configured for this baseline, discard
588
                    p.mBuildFile = -2;
7048 dpurdie 589
                    mLogger.info("planRelease set mBuildFile to -2 for package {}", p.mAlias );
6914 dpurdie 590
                    standardOut(mAssocBuildPlatforms, p.mAlias, mAssocBuildPlatformsFlag);
591
                    mAssocBuildPlatformsFlag = false;
592
                }
593
            }
594
        }      
595
 
596
        if (mDaemon)
597
        {
598
            // Daemon Mode Only
599
            // Process packages which are not ripple buildable, and all packages dependent upon them
7071 dpurdie 600
            //      I would have thought that all consumer packages had already been excluded ??
6914 dpurdie 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
 
7071 dpurdie 606
                for (Iterator<Package> it1 = mPackageCollectionAll.iterator(); it1.hasNext(); )
6914 dpurdie 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
 
7071 dpurdie 617
                        rippleBuildExclude( p, p.mId, null, it, be, true, true );
6914 dpurdie 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
7071 dpurdie 673
                                    rippleBuildExclude(p, -2, "Ripple Required." + " Waiting for user", null, null, false, true);
7048 dpurdie 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
7071 dpurdie 716
                                    rippleBuildExclude(p, p.mId, "Unbuildable" + " package not found in archive", null, null, true, true);
6914 dpurdie 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
7071 dpurdie 734
                                    rippleBuildExclude(p, p.mId, reason + " package not found in archive", null, null, true, true);
6914 dpurdie 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
7071 dpurdie 756
                                            rippleBuildExclude(p, p.mId, "Package cannot be rebuilt in this release", null, null, true, true);
6914 dpurdie 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
 *      
7071 dpurdie 915
 *      [Being Done] Need more test cases
7052 dpurdie 916
 *      
7071 dpurdie 917
 *      [Done, in the UTF] Need to report all build options, not just the selected one
918
 *                         Data to RM may need some more info
7052 dpurdie 919
 *      
920
 *      Cleanup the ANT build file - don't list all the release dependencies, just those needed to build the current package
7071 dpurdie 921
 *      Chances are - all we need is the new package version number
7070 dpurdie 922
 *      
7071 dpurdie 923
 *      [Fixed] If a WIP on a package that has circular dependencies is added, then the WIP will be excluded. This prevents the problem being fixed.
924
 *              Should not exclude a WIP of a package with a circular dependency
7052 dpurdie 925
 */
6914 dpurdie 926
 
927
        // Process remaining packages which are need to be reproduced for this baseline.
928
        //    Determine the build file for each package
929
        //    For daemon builds:
7048 dpurdie 930
        //      Determine the next package that can be built now
931
        //          Sounds simple - doesn't it
6914 dpurdie 932
        //      Set its mBuildNumber to 1, all remaining reproducible packages to 2
933
        //    For escrow builds:
934
        //      Determine the package versions that can be built in the build iteration
935
        //      Set their mBuildNumber to the build iteration
936
        //      Increment the build iteration and repeat until all package versions 
937
        //      that need to be reproduced have been assigned a build iteration        
938
 
939
        boolean allProcessed = false;
940
        int buildFile = 1;
941
 
942
        do
943
        {
7048 dpurdie 944
            //
945
            //  Create the mBuildOrder collection
946
            //      Same for both Daemon and Escrow modes
947
            //      Will have package build order and build level
6914 dpurdie 948
            boolean allDependenciesProcessed = true;
949
            do
950
            {
951
                allDependenciesProcessed = true;
952
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
953
                {
954
                    Package p = it.next();
955
 
7048 dpurdie 956
                    if ( p.mBuildFile < 0  ) 
6914 dpurdie 957
                    {
7048 dpurdie 958
                        // Daemon: Flag packages that cannot be built
6914 dpurdie 959
                        // Escrow: Flag packages with a foreign build environment as processed
960
                        p.mProcessed = true;
7048 dpurdie 961
                        mLogger.info("planRelease package not buildable {}", p.mName);            
6914 dpurdie 962
                    }
7048 dpurdie 963
                    else if ( p.mBuildFile == 0 )
6914 dpurdie 964
                    {
965
                        // package yet to be processed and
7048 dpurdie 966
                        //  Daemon mode: Could be built
6914 dpurdie 967
                        //  Escrow mode: Can be reproduced
968
                        boolean canBeBuiltNow = true;
969
                        boolean allDependenciesForThisPackageProcessed = true;
970
 
971
                        //  Scan the packages dependencies
972
                        for ( Iterator<Package> it2 = p.mPackageDependencyCollection.iterator(); it2.hasNext(); )
973
                        {
974
                            Package dependency = it2.next();
975
 
976
                            if ( !dependency.mProcessed )
977
                            {
978
                                //  If all the dependencies have been processed, then we can potentially build this package
979
                                //  If any of them have not been processed, then cannot calculate canBeBuiltNow until this 
980
                                //  dependency has been processed
981
                                allDependenciesForThisPackageProcessed = false;
982
                                allDependenciesProcessed = false;
983
                            }
7048 dpurdie 984
                            else if (  (  mDaemon && (   dependency.mBuildFile == 0 ) ) 
6914 dpurdie 985
                                    || ( !mDaemon && ( ( dependency.mBuildFile == 0 ) ||
986
                                                           ( dependency.mBuildFile == buildFile &&
987
                                                           ( !p.haveSameBuildStandards(dependency)  ) ) ) ) )
988
                            {
989
                                // Daemon mode:
7048 dpurdie 990
                                //    This processed dependency has not been assigned to a build iteration - so can't built yet
6914 dpurdie 991
                                // Escrow mode: This package cannot be built now if
992
                                //    This processed dependency has not been assigned to a build iteration or
993
                                //    This processed dependency has been assigned to this build iteration, but the 
994
                                //    build standards of the package and this dependency prevent the package being
995
                                //    built in this iteration.   
996
                                canBeBuiltNow = false;
7048 dpurdie 997
                                mLogger.info("planRelease package cannot be built in this iteration {}", p.mName);
6914 dpurdie 998
                                break;
999
                            }
1000
                        }
1001
 
7048 dpurdie 1002
                        //  All dependencies have been processed. May be able to build this package
1003
                        //      Add the package to the build order list
1004
                        //
6914 dpurdie 1005
                        if (allDependenciesForThisPackageProcessed)
1006
                        {
1007
                            p.mProcessed = true;
7048 dpurdie 1008
                            if ( canBeBuiltNow )
6914 dpurdie 1009
                            {
1010
                                mBuildOrder.add(p);
7048 dpurdie 1011
                                p.mBuildFile = buildFile;
1012
                                mLogger.info("planRelease set mBuildFile to {} for package {}",buildFile, p.mAlias );
6914 dpurdie 1013
                            }
1014
                        }
1015
                    }
1016
                }
1017
            } while( !allDependenciesProcessed );
7048 dpurdie 1018
 
1019
            //  Have process all the packages that we can at the moment
1020
            //      Examine all the packages in the collection to see if there are more that need to be extracted
1021
            //      These will be done at a different build-level
1022
            //  
1023
            allProcessed = true;
1024
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
1025
            {
1026
                Package p = it.next();
1027
                if ( p.mBuildFile == 0 )
1028
                {
1029
                    // more build files are required
1030
                    allProcessed = false;
1031
                    mLogger.info("planRelease more build files are required for {}", p.mName);
1032
                    break;
1033
                }
1034
            }
6914 dpurdie 1035
 
7048 dpurdie 1036
            buildFile++;
1037
            if (buildFile % 500 == 0 ) {
1038
                mLogger.error("planRelease. Too many build levels {}", buildFile);
1039
            }
1040
        } while( !allProcessed );
1041
 
1042
 
1043
        if ( mDaemon )
1044
        {
1045
 
6914 dpurdie 1046
            //
1047
            //  Daemon Mode:
1048
            //
7070 dpurdie 1049
 
1050
            //  Create a list of build candidates
1051
            //
1052
            //  Add in the WIPs, Tests and Ripple Requests so that we can process them as one collections
1053
            //  Now have a collection of packages that we would like to build right now
1054
            //  See if any of them can be excluded due to issues with creating a new package version
7048 dpurdie 1055
            ArrayList<Package> buildCandidates = new ArrayList<Package>();
7070 dpurdie 1056
            buildCandidates.addAll(mPackageCollectionWip);
1057
            buildCandidates.addAll(mPackageCollectionTest);
1058
            buildCandidates.addAll(mPackageCollectionRipple);
7048 dpurdie 1059
 
7070 dpurdie 1060
            //  Locate all packages that we can build now
1061
            //      Packages that have a build requirement and have no reason we cannot build them
1062
 
7048 dpurdie 1063
            for (Iterator<Package> it = mBuildOrder.iterator(); it.hasNext(); )
6914 dpurdie 1064
            {
7048 dpurdie 1065
                Package p = it.next();
1066
                if ( p.mProcessed && p.mBuildFile > 0 )
6914 dpurdie 1067
                {
7048 dpurdie 1068
                    if (p.mBuildReason != null)
1069
                    {
1070
                        // Have a reason to build this package
1071
                        buildCandidates.add(p);
1072
                        mLogger.info("planRelease Candidate {}",p.mAlias);
1073
                    }
1074
                }
1075
            }
1076
 
7070 dpurdie 1077
            //  Examine the build candidates and verify that a new version number can be calculated for each
1078
            //  version that we need to build.
1079
            //
7071 dpurdie 1080
            //  If we can't generate a new version number, then this is considered to be a build failure
1081
            //  The package will be excluded and the user will be emailed
1082
            //
7048 dpurdie 1083
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1084
            {
1085
                Package p = it.next();
6914 dpurdie 1086
 
7048 dpurdie 1087
                if ( p.mBuildFile >= 0 )
1088
                {
7050 dpurdie 1089
                    int pvApplied = p.applyPV(mReleaseManager);
7048 dpurdie 1090
 
1091
                    if ( pvApplied == 1 )
6914 dpurdie 1092
                    {
7048 dpurdie 1093
                        // max 50 chars
7071 dpurdie 1094
                        rippleBuildExclude(p, p.mId, "Package has non standard versioning", null, null, true, true);
7048 dpurdie 1095
                    }
1096
                    else if ( pvApplied == 2 )
1097
                    {
1098
                        // max 50 chars
7071 dpurdie 1099
                        rippleBuildExclude(p, p.mId, "Package has reached ripple field limitations", null, null, true, true);
7048 dpurdie 1100
                    }
1101
                    else if ( pvApplied == 3 )
1102
                    {
1103
                        // max 50 chars
7071 dpurdie 1104
                        rippleBuildExclude(p, p.mId, "Package has invalid change type", null, null, true, true);
7048 dpurdie 1105
                    }
1106
 
1107
                    if ( pvApplied != 0) 
1108
                    {
1109
                        // If this package is not a WIP/TEST/RIPPLE, then remove it from this collection
7051 dpurdie 1110
                        // Want to keep all WIP/TEST/RIPPLE items to simplify reporting
7048 dpurdie 1111
                        if (! p.mIsNotReleased )
6914 dpurdie 1112
                        {
7048 dpurdie 1113
                            it.remove();
6914 dpurdie 1114
                        }
7048 dpurdie 1115
                    }
1116
 
1117
                    //
1118
                    //  Ensure that the mRippleTime is known for each package
1119
                    //  Collection includes: naturalRipples, ForcedRipples, TestBuilds and NewVersions
1120
                    if ( pvApplied == 0)
1121
                    {
1122
                        if (p.mTestBuildInstruction != 0)
6914 dpurdie 1123
                        {
7048 dpurdie 1124
                            // Test Build - there is no ripple effect
1125
                            // The time impact will be the estimated build time of this one package
1126
                            p.mRippleTime = p.mBuildTime;
1127
 
6914 dpurdie 1128
                        }
7048 dpurdie 1129
                        else 
1130
                        {
1131
                            //  Calculate the time to build the package AND all of the packages that depend on it
1132
                            //  Calculate the build plan for the package
1133
                            //
7071 dpurdie 1134
                            calcBuildPlan(p, mPackageCollection);
7048 dpurdie 1135
                        }
6914 dpurdie 1136
                    }
1137
                }
1138
            }
7048 dpurdie 1139
 
1140
            //  Determine the first test build package
1141
            //  Assume the collection is in build instruction id order, 
1142
            //      So that the first request will be built first
1143
            //  Add all buildable test-builds to the mBuildOrder collection 
1144
            Package testBuild = ReleaseManager.NULL_PACKAGE;
1145
            mBuildOrder.clear();
6914 dpurdie 1146
 
7048 dpurdie 1147
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1148
            {
1149
 
1150
                Package p = it.next();
1151
                if ( p.mBuildFile >= 0 )
6914 dpurdie 1152
                {
7048 dpurdie 1153
                    if (p.mTestBuildInstruction != 0)
6914 dpurdie 1154
                    {
7048 dpurdie 1155
                        //  Not a Test Build
1156
                        if (testBuild == ReleaseManager.NULL_PACKAGE)
1157
                        {
7051 dpurdie 1158
                            testBuild = p;
7048 dpurdie 1159
                        }
1160
                        mBuildOrder.add(p);
6914 dpurdie 1161
                    }
1162
                }
1163
            }
7048 dpurdie 1164
 
1165
            //
7070 dpurdie 1166
            //  Determine the NON-test packages the we will build next
1167
            //  This will be the one with the lowest ripple time
7048 dpurdie 1168
            //
7070 dpurdie 1169
            Package build = ReleaseManager.NULL_PACKAGE;
1170
            ArrayList<Package> buildNext = new ArrayList<Package>();
1171
 
1172
            //  Extract candidates that are left
1173
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
6914 dpurdie 1174
            {
7070 dpurdie 1175
                Package p = it.next();
1176
                if ( p.mBuildFile >= 0  &&p.mTestBuildInstruction == 0)
1177
                {
1178
                    buildNext.add(p);
1179
                }
1180
            }
1181
 
1182
            if ( !buildNext.isEmpty() )
1183
            {
1184
                //  Sort on mRippleTime so that
1185
                //      We can get the lowest first
1186
                //      We can generate the complete plan in a nice order
1187
                //
1188
                Collections.sort(buildNext, Package.RippleTimeComparator);
1189
 
7071 dpurdie 1190
                //  At the moment extract the first one - this is the fastest
1191
                //  Allowing for a 20% extension.
7070 dpurdie 1192
                //
7071 dpurdie 1193
                //  TODO - what if two build sets don't overlap. Do we build the longer one first ?
1194
                //  TODO - what if two build sets do overlay. Can we merge them somehow
1195
                //
7070 dpurdie 1196
                build = buildNext.get(0);
1197
 
1198
                //  Determine the amount of time we would allow the 'best' plan to be extended
1199
                //      Allow for a 20% extension in time
7071 dpurdie 1200
                //      Minimum of 10 minutes
7070 dpurdie 1201
                int baseTime = build.mRippleTime;
1202
                baseTime = ( baseTime * 1200) / 1000;
1203
                if ( baseTime < 10 * 60) {
1204
                    baseTime = (10 * 60);
1205
                }
1206
                mLogger.error("Scan for package to build: {} {}", build.mRippleTime, baseTime);
1207
 
1208
                //  Find last package that does not exceed the extended ripple time
1209
                for (Iterator<Package> it = buildNext.iterator(); it.hasNext(); )
1210
                {
1211
                    Package p = it.next();
1212
                    if (p.mRippleTime > baseTime)
1213
                    {
1214
                        break;
1215
                    }
1216
                    build = p;
1217
                }
1218
 
1219
                //
1220
                //  Extend mBuildOrder with the selected non-test build package and its build plan
1221
                //  Really only for display purposes
1222
                //
1223
                Package.resetProcessed(buildNext);
7048 dpurdie 1224
                mBuildOrder.add(build);
7070 dpurdie 1225
                updateBuildList(build.mRipplePlan, buildNext);
7048 dpurdie 1226
                mBuildOrder.addAll(build.mRipplePlan);
7070 dpurdie 1227
 
1228
                //  Add in other build candidates
1229
                for (Iterator<Package> it = buildNext.iterator(); it.hasNext(); )
1230
                {
1231
                    Package p = it.next();
1232
                    if ( p.mBuildFile >= 0 )
1233
                    {
1234
                        if ( p != build && ! p.mIsProcessed)
1235
                        {
1236
                            //  Not our selected package and not already processed
1237
                            mBuildOrder.add(p);
1238
                            updateBuildList(p.mRipplePlan, buildNext);
1239
                            mBuildOrder.addAll(p.mRipplePlan);
1240
                        }
1241
                    }
1242
                }
7048 dpurdie 1243
            }
1244
 
1245
            //
1246
            //  Mark the first package in the build order as the one to be built
7051 dpurdie 1247
            //  This will give test builds priority, while indicating what will be built after that
7048 dpurdie 1248
            //
1249
 
1250
            if (!mBuildOrder.isEmpty()) {
1251
                build = mBuildOrder.get(0);
1252
                build.mBuildFile = 1;
1253
 
1254
                if ( build.mForcedRippleInstruction > 0 )
6914 dpurdie 1255
                {
7048 dpurdie 1256
                    mReleaseManager.markDaemonInstCompleted( build.mForcedRippleInstruction );
1257
                }
6914 dpurdie 1258
 
7048 dpurdie 1259
                if ( build.mTestBuildInstruction > 0 )
1260
                {
1261
                    mReleaseManager.markDaemonInstInProgress( build.mTestBuildInstruction );
1262
                }
1263
 
1264
                //  Now that we know which package we are building
1265
                //      Set the previously calculated nextVersion as the packages version number
7071 dpurdie 1266
                //      Claim the version number to prevent other builds from using it. Even if doing a test build
7048 dpurdie 1267
                //
7071 dpurdie 1268
                if (build.mNextVersion != null)
7048 dpurdie 1269
                {
1270
                    mReleaseManager.claimVersion(build.mPid, build.mNextVersion + build.mExtension, mBaseline);
1271
                    build.mVersion = build.mNextVersion;
1272
                }
1273
            }
1274
 
1275
            //
7070 dpurdie 1276
            //  Massage the package collection
1277
            //      Replace WIP/TEST/RIPPLE so that the mPackageCollection is a collection of packages we would like in the release
1278
            //      Don't replace those that we can't build due to errors
1279
            //
1280
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1281
            {
1282
                Package p = it.next();
1283
                if ( p.mBuildFile >= 0 )
1284
                {
1285
                    Package pReleased = findPackage(p.mAlias);
1286
                    if ( pReleased != ReleaseManager.NULL_PACKAGE)
1287
                    {
1288
                        int index = mReleaseManager.findPackageLastIndex;
1289
                        mPackageCollection.set(index, p);
1290
                        p.mIsNotReleased = false;
1291
                    }
1292
                }
1293
            }
1294
 
1295
 
1296
            //
7048 dpurdie 1297
            //  To fit in with the old algorithm ( ie: could be improved )
1298
            //  Insert marks into all packages
1299
            //  Not sure exactly why - Its used in the generation of the ant build file
7070 dpurdie 1300
            //                     Want to set mNoBuildReason, mBuildFile
7048 dpurdie 1301
            //
1302
            //      Package we have selected to build: 0     , 1
7070 dpurdie 1303
            //      Package we could have built      : 0     , 2
7048 dpurdie 1304
            //      Packages we can't build          : reason, 3
1305
            //      Packages that are OK             : 3     , 3
7070 dpurdie 1306
            //      ????                             : 0     , 3
7048 dpurdie 1307
 
1308
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
1309
            {
1310
                Package p = it.next();
1311
                if (p == build ) {
1312
                    p.mNoBuildReason = 0;
1313
                    p.mBuildFile = 1;
1314
                } 
1315
                else if ( p.mBuildFile < 0 )
1316
                {
1317
                    p.mNoBuildReason = p.mBuildFile;
1318
                    p.mBuildFile = 3;
1319
                }
1320
                else if (p.mBuildReason != null)
1321
                {
7070 dpurdie 1322
                    p.mNoBuildReason = 0;
1323
                    p.mBuildFile = 2;
7048 dpurdie 1324
                }
1325
                else
1326
                {
1327
                    p.mNoBuildReason = 0;
1328
                    p.mBuildFile = 3;
1329
                }
1330
            }
7070 dpurdie 1331
 
7048 dpurdie 1332
        }
1333
 
1334
    }
1335
 
7070 dpurdie 1336
    /** Update a collection of packages such that the collection contains packages from the WIP/RIPPLE collection
1337
     *  in preference to the package in the main collection
1338
     *  
1339
     * @param packageList   - List to process and update
1340
     * @param repList - List of replacement candidates. Assumes valid packages
1341
     */
1342
    private void updateBuildList(ArrayList<Package> packageList, ArrayList<Package> repList ) {
1343
 
1344
        int baseIndex = 0;
1345
        for (Iterator<Package> it = packageList.iterator(); it.hasNext(); baseIndex++)
1346
        {
1347
            Package basePkg = it.next();
1348
 
1349
            for (Iterator<Package> repit = repList.iterator(); repit.hasNext(); )
1350
            {
1351
                Package repPkg = repit.next();
1352
                if ( basePkg.mAlias.compareTo( repPkg.mAlias ) == 0 )                    
1353
                {
1354
                    //  Replacement package has been found
1355
                    //  Only looking for non-test packages that can be built
1356
                    //  Flag that the package is now a part of the official release set
1357
                    //  Flag that the package has been processed to prevent it being included in a future plan
1358
 
1359
                    packageList.set(baseIndex, repPkg);
1360
                    repPkg.mIsNotReleased = false;
1361
                    repPkg.mIsProcessed = true;
1362
                    break;
1363
 
1364
                }
1365
            }
1366
        }
1367
    }
1368
 
7048 dpurdie 1369
    /**
1370
     * Calculate a build plan for the specified package
1371
     * Calculates : mRippleTime - time to build the package and the ripple effect
1372
     * Calculates : mBuildPlan - collection of packages in the plan that can be built at the moment
1373
     * 
1374
     * Needs to determine all packages that consume the package - and all packages that consume them
1375
     *  Note: The package may not be in the mPackageCollection ( it may be a WIP/TEST/RIPPLE )
1376
     *  
7070 dpurdie 1377
     * Note: The rippleTime of PackageA is not the sum of the rippleTimes of the packages that consume PackageA.
1378
     *  
7048 dpurdie 1379
     * Need to:
1380
     *      Only include a package once.
1381
     *      Only include packages that can/need to be built at the moment
1382
     * 
7070 dpurdie 1383
     * @param p                 - Package to process
1384
     * @param pkgCollection     - Package Collection to scan
1385
 
7048 dpurdie 1386
     */
7071 dpurdie 1387
    private void calcBuildPlan(Package p, ArrayList<Package> pkgCollection) {
7070 dpurdie 1388
 
7071 dpurdie 1389
 
1390
        p.mRipplePlan = new ArrayList<Package>(); 
7070 dpurdie 1391
        p.mRippleTime = p.mBuildTime;
7071 dpurdie 1392
 
1393
        //  Need to add elements to the end of the list while processing
7070 dpurdie 1394
        //  Sum the buildTimes of the packages that we add to the list
7071 dpurdie 1395
        ArrayList<Package> toProcess = usedByPackages(p, pkgCollection, 1);
1396
        while ( ! toProcess.isEmpty())
7048 dpurdie 1397
        {
7071 dpurdie 1398
            Package pkg = toProcess.remove(0);
1399
            if ( ! p.mRipplePlan.contains( pkg ))
7048 dpurdie 1400
            {
7071 dpurdie 1401
                p.mRipplePlan.add(pkg);
1402
                p.mRippleTime += pkg.mBuildTime;
7048 dpurdie 1403
            }
7071 dpurdie 1404
 
1405
            ArrayList<Package> usedBy = usedByPackages(pkg, pkgCollection, pkg.mRippleOrder + 1);
1406
            toProcess.addAll(usedBy);
7048 dpurdie 1407
        }
1408
 
1409
        //
7070 dpurdie 1410
        //  Need to determine the rippleTime for each package in the plan
7071 dpurdie 1411
        //      Have a much smaller set of packages to process (need only scan those in p.mRipplePlan)
1412
        //  Similar to the above code, but 
1413
        //      Don't care about the mRipplePlan item in the packages
1414
        //      Don't modify the mRippleOrder
1415
        //
7070 dpurdie 1416
        for (ListIterator<Package> it = p.mRipplePlan.listIterator(); it.hasNext(); )
1417
        {
7071 dpurdie 1418
            Package p1 = it.next();
7070 dpurdie 1419
 
7071 dpurdie 1420
            int rippleTime = 0;
1421
            ArrayList<Package> ripplePlan = new ArrayList<Package>();
1422
            ArrayList<Package> toProcess1 = new ArrayList<Package>();
7070 dpurdie 1423
 
7071 dpurdie 1424
            toProcess1.add(p1);
1425
            while ( ! toProcess1.isEmpty())
7070 dpurdie 1426
            {
7071 dpurdie 1427
                Package pkg = toProcess1.remove(0);
1428
                if ( ! ripplePlan.contains( pkg ))
7070 dpurdie 1429
                {
7071 dpurdie 1430
                    ripplePlan.add(pkg);
1431
                    rippleTime += pkg.mBuildTime;
7070 dpurdie 1432
                }
7071 dpurdie 1433
 
1434
                ArrayList<Package> usedBy = usedByPackages(pkg, p.mRipplePlan, -1);
1435
                toProcess1.addAll(usedBy);
7070 dpurdie 1436
            }
7071 dpurdie 1437
 
1438
            p1.mRippleTime = rippleTime;
7070 dpurdie 1439
        }
1440
 
7071 dpurdie 1441
 
7048 dpurdie 1442
        //
7070 dpurdie 1443
        //  Sort the ripplePlan so that we build the fastest elements first
1444
        //  Only care about the ripplePlan for the main Package
1445
        //
1446
        Collections.sort(p.mRipplePlan, Package.PlanComparator);
1447
 
1448
        //  Debugging
1449
        mLogger.error("calcBuildPlan. Pkg:{} pvid:{}, Order:{} RippleT:{} BuildT:{}", p.mAlias, p.mId, p.mRippleOrder, p.mRippleTime, p.mBuildTime);
7048 dpurdie 1450
        for (ListIterator<Package> it = p.mRipplePlan.listIterator(); it.hasNext(); )
1451
        {
1452
            Package pkg = it.next();
7070 dpurdie 1453
            mLogger.error("calcBuildPlan. Plan: Pkg:{} pvid:{}, Order:{} RippleT:{} BuildT:{}", pkg.mAlias, pkg.mId, pkg.mRippleOrder, pkg.mRippleTime, pkg.mBuildTime);
7048 dpurdie 1454
        }
1455
    }
1456
 
1457
    /** 
1458
     *  Calculate a collection of packages that actively use the named package
1459
     *  A consumer package does NOT use the named package,
1460
     *      If the consumer is an SDK or is Pegged
1461
     *      If the consumer is marked as advisoryRipple
1462
     *      If the consumer cannot be built
1463
     *   
1464
     * @param pkg - Package to process
7070 dpurdie 1465
     * @param pkgCollection - collection of packages to scan
7071 dpurdie 1466
     * @param rippleOrder - Set the ripple oder, if >= 0
7048 dpurdie 1467
     * @return A collection of packages that actively 'use' the specified package
1468
 
1469
     */
7071 dpurdie 1470
    private ArrayList<Package> usedByPackages(Package pkg, ArrayList<Package> pkgCollection, int rippleOrder) {
7048 dpurdie 1471
 
1472
        ArrayList<Package> usedBy = new ArrayList<Package>();
1473
 
7070 dpurdie 1474
        for (Iterator<Package> it = pkgCollection.iterator(); it.hasNext(); )
7048 dpurdie 1475
        {
1476
            Package p = it.next();
1477
 
1478
            //  Is this package 'actively used' in the current build
1479
            if (p.mBuildFile >= 0)
1480
            {
1481
                for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
1482
                {
1483
                    String alias = it2.next();
7070 dpurdie 1484
                    if (  pkg.mAlias.compareTo( alias ) == 0  ) {
7048 dpurdie 1485
                        //  Have found a consumer of 'pkg'
1486
                        usedBy.add(p);
7071 dpurdie 1487
                        if (rippleOrder >= 0)
1488
                            p.mRippleOrder = rippleOrder;
6914 dpurdie 1489
                        break;
1490
                    }
1491
                }
1492
            }
7048 dpurdie 1493
        }
1494
 
1495
        return usedBy;
6914 dpurdie 1496
    }
1497
 
1498
    /** Determine if a given PVID is a member of the current release.
1499
     *  Used to determine if a package dependency is out of date
1500
     * 
1501
     * @param dpvId
1502
     * @return true - specified pvid is a full member of the Release
1503
     */
1504
    private boolean isInRelease(Integer dpvId) {
1505
 
7048 dpurdie 1506
        boolean inRelease = false;
6914 dpurdie 1507
 
7048 dpurdie 1508
        for ( Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1509
        {
7048 dpurdie 1510
            Package p = it.next();
6914 dpurdie 1511
 
7048 dpurdie 1512
            if ( p.mId == dpvId )
6914 dpurdie 1513
            {
7048 dpurdie 1514
                inRelease = ! p.mIsNotReleased;
6914 dpurdie 1515
                break;
1516
            }
1517
        }
7048 dpurdie 1518
        return inRelease;
6914 dpurdie 1519
    }
1520
 
1521
 
1522
    /**reports what change in build exceptions happens as part of planRelease
1523
     */
1524
    public void reportChange() throws SQLException, Exception
1525
    {
1526
        int counter = 0;
1527
        for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1528
        {
1529
            BuildExclusion buildExclusion = it.next();
1530
 
1531
            if ( !buildExclusion.isProcessed() )
1532
            {
7032 dpurdie 1533
                if (buildExclusion.isImported() && ! buildExclusion.isARootCause() ) {
1534
                    // Remove from the exclusion list
1535
                    buildExclusion.includeToBuild(mReleaseManager, mBaseline);
7048 dpurdie 1536
                    mLogger.error("reportChange remove unused exclusion: {}", buildExclusion.info());
7032 dpurdie 1537
                } else {
1538
                    // Exclude and notify
1539
                    buildExclusion.excludeFromBuild(mReleaseManager, mBaseline);
7071 dpurdie 1540
                    buildExclusion.email(this, mPackageCollectionAll);
7032 dpurdie 1541
                    counter++;
1542
                }
6914 dpurdie 1543
            }
1544
        }
7048 dpurdie 1545
        mLogger.error("reportChange exclusion count: {}", counter);
6914 dpurdie 1546
    }
1547
 
1548
    /**reports the build plan
1549
     */
1550
    public void reportPlan() throws SQLException, Exception
1551
    {
1552
        mReleaseManager.reportPlan(mRtagId, mBuildOrder);
1553
    }
1554
 
1555
    /**Returns the first build file from the collection
1556
     * The build file will be flagged as empty if none exists
1557
     */
1558
    public BuildFile getFirstBuildFileContent()
1559
    {
1560
        mLogger.debug("getFirstBuildFileContent");
1561
 
1562
        mBuildIndex = -1;
1563
        return getNextBuildFileContent();
1564
    }
1565
 
1566
    /**Returns next build file from the collection
1567
     * The build file will be flagged as empty if none exists
1568
     */
1569
    public BuildFile getNextBuildFileContent()
1570
    {
1571
        mLogger.debug("getNextBuildFileContent");
1572
        BuildFile retVal = null;
1573
 
1574
        try
1575
        {
1576
            mBuildIndex++;
1577
            retVal = mBuildCollection.get( mBuildIndex );
1578
        }
1579
        catch( IndexOutOfBoundsException e )
1580
        {
1581
            // Ignore exception. retVal is still null.
1582
        }
1583
 
1584
        if (retVal == null)
1585
        {
1586
            retVal = new BuildFile();
1587
        }
1588
 
7048 dpurdie 1589
        mLogger.debug("getNextBuildFileContent returned {}", retVal.state.name() );
6914 dpurdie 1590
        return retVal;
1591
    }
1592
 
1593
 
1594
    /**collects meta data associated with the baseline
1595
     * this is sufficient to send an indefinite pause email notification 
1596
     *  
1597
     * Escrow: Used once to collect information about the SBOM and associated Release 
1598
     *         mBaseline is an SBOMID 
1599
     * Daemon: Used each build cycle to refresh the information 
1600
     *          mBaseline is an RTAGID
1601
     */
1602
    public void collectMetaData() throws SQLException, Exception
1603
    {
1604
        Phase phase = new Phase("cmd");
7048 dpurdie 1605
        mLogger.debug("collectMetaData mDaemon {}", mDaemon);
6914 dpurdie 1606
 
1607
        try
1608
        {
1609
            phase.setPhase("connect");
1610
            mReleaseManager.connect();
1611
 
1612
            if (! mDaemon)
1613
            {
1614
                mSbomId = mBaseline;
1615
                phase.setPhase("queryRtagIdForSbom");
1616
                mRtagId = mReleaseManager.queryRtagIdForSbom(mBaseline);
1617
                if (mRtagId == 0)
1618
                {
7033 dpurdie 1619
                    mLogger.error("SBOM does not have a matching Release. Cannot be used as a base for an Escrow"); 
6914 dpurdie 1620
                    throw new Exception("rtagIdForSbom show stopper. SBOM does not have an associated Release");
1621
                }
1622
            }
1623
 
1624
            phase.setPhase("queryReleaseConfig");
1625
            mReleaseManager.queryReleaseConfig(mRtagId);
1626
 
1627
            if (mDaemon)
1628
            {
1629
                phase.setPhase("queryMailServer");
1630
                setMailServer(mReleaseManager.queryMailServer());
1631
                phase.setPhase("queryMailSender");
1632
                setMailSender(mReleaseManager.queryMailSender());
1633
                phase.setPhase("queryGlobalAddresses");
1634
                setMailGlobalTarget(mReleaseManager.queryGlobalAddresses());
1635
                phase.setPhase("queryProjectEmail");
1636
                mMailGlobalCollection = mReleaseManager.queryProjectEmail(mBaseline);
1637
                phase.setPhase("mMailGlobalTarget");
1638
                mMailGlobalCollection.add(0,getMailGlobalTarget());
1639
            }
1640
            phase.setPhase("queryBaselineName");
1641
            mBaselineName = mReleaseManager.queryBaselineName(mBaseline);
1642
            phase.setPhase("Done");
1643
        }
1644
        finally
1645
        {
1646
            // this block is executed regardless of what happens in the try block
1647
            // even if an exception is thrown
1648
            // ensure disconnect
1649
            mReleaseManager.disconnect();
1650
        }
1651
    }
1652
 
1653
    /**
1654
     * Find Package by package alias
7070 dpurdie 1655
     * Searches the released package collection
6914 dpurdie 1656
     * @param   alias               - alias of package to locate
1657
     * @return  Package with the matching mAlias or NULL_PACKAGE if no package has the mAlias
1658
     */
1659
    public Package findPackage(String alias)
1660
    {
1661
        mLogger.debug("findPackage");
1662
 
1663
        Package retVal = mReleaseManager.findPackage(alias, mPackageCollection);
1664
 
7048 dpurdie 1665
        mLogger.info("findPackage returned {}", retVal.mName);
6914 dpurdie 1666
        return retVal;
1667
    }
7070 dpurdie 1668
 
6914 dpurdie 1669
    /**
1670
     * Sets the mBuildFile to -5 (indirectly dependent on package versions which are not reproducible) 
7048 dpurdie 1671
     * for the package and all dependent packages that are a part of the release set.
1672
     *  
7032 dpurdie 1673
     * @param p             The package being excluded 
1674
     * @param rootPvId      The PVID of the package that is causing the exclusion. Null or -ve values are special
1675
     *                      This package is the root cause, -2: Excluded by Ripple Stop 
1676
     * @param rootCause     Text message. Max 50 characters imposed by RM database 
1677
     * @param list          If not null, add build exclusion to specified list, else use default(mBuildExclusionCollection) list. Allows insertions while iterating the list.
1678
     * @param be            If not null, process provided BuildExclusion element, otherwise find-existing/create a BuildExclusion element
1679
     * @param dependentToo  True: Exclude all packages that depend on the excluded package 
7071 dpurdie 1680
     * @param depWipsToo    False: Don't exclude WIP packages that depend on the excluded package
6914 dpurdie 1681
     */
7071 dpurdie 1682
    private void rippleBuildExclude(Package p, int rootPvId, String rootCause, ListIterator<BuildExclusion> list, BuildExclusion be, boolean dependentToo, boolean depWipsToo )
6914 dpurdie 1683
    {
1684
        mLogger.debug("rippleBuildExclude");
7048 dpurdie 1685
 
6914 dpurdie 1686
        if ( p.mBuildFile == 0 || p.mBuildFile == 1 )
1687
        {
1688
            p.mBuildFile = -5;
7048 dpurdie 1689
            mLogger.info("rippleBuildExclude set mBuildFile to -5 for package {}", p.mAlias );
6914 dpurdie 1690
 
1691
            if ( be != null )
1692
            {
7032 dpurdie 1693
                be.setProcessed();
6914 dpurdie 1694
            }
1695
            else
1696
            {
1697
                //  If no be item has been provided, then scan the complete collection looking for a matching item
1698
                //  If found, process it, else add it (unprocessed)
1699
                boolean found = false;
1700
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1701
                {
1702
                    BuildExclusion buildExclusion = it.next();
1703
 
1704
                    if ( buildExclusion.compare(p.mId, rootPvId, rootCause))
1705
                    {
7032 dpurdie 1706
                        buildExclusion.setProcessed();
6914 dpurdie 1707
                        found = true;
1708
                        break;
1709
                    }
1710
                }
1711
 
1712
                if (!found)
1713
                {
1714
                    // Entry not found in the mBuildExclusionCollection
1715
                    // Mark all occurrences for this package as processed
1716
                    // These will be superseded by a new build exclusion entry
1717
                    for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1718
                    {
1719
                        BuildExclusion buildExclusion = it.next();
1720
 
1721
                        if ( buildExclusion.compare(p.mId))
1722
                        {
7032 dpurdie 1723
                            buildExclusion.setProcessed();
6914 dpurdie 1724
                        }
1725
                    }
1726
 
1727
                    BuildExclusion buildExclusion = new BuildExclusion(p.mId, rootPvId, rootCause, p.mTestBuildInstruction);
1728
 
1729
                    //
1730
                    //  Add the new build exclusion to a list
1731
                    //    Either the default list or a user-specified list
1732
                    if ( list == null )
1733
                    {
1734
                        mBuildExclusionCollection.add(buildExclusion);
1735
                    }
1736
                    else
1737
                    {
1738
                        // must use the ListIterator interface to add to the collection whilst iterating through it
1739
                        list.add(buildExclusion);
1740
                    }
1741
                }
1742
            }
1743
 
1744
            //  Locate ALL packages that depend on this package and exclude them too
1745
            //  This process will be recursive
1746
            //    Not sure that this it is efficient 
7048 dpurdie 1747
            //  Only ripple a build exclusion through for packages that are a part of the full release set
1748
            //  NewWIPs, ForcedRipples and TestBuilds will not force consumer packages to be excluded
6914 dpurdie 1749
            //
7048 dpurdie 1750
            if ( ! p.mIsNotReleased && dependentToo)
6914 dpurdie 1751
            {
7048 dpurdie 1752
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 1753
                {
1754
                    Package pkg = it.next();
7071 dpurdie 1755
 
1756
                    //  Skip myself
1757
                    if (pkg == p)
1758
                        continue;
6914 dpurdie 1759
 
7071 dpurdie 1760
                    //  Ignore dependent WIPS if required
1761
                    if (!depWipsToo && pkg.mDirectlyPlanned)
1762
                        continue;
1763
 
1764
                    for (Iterator<Package> it2 = pkg.mPackageDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 1765
                    {
7071 dpurdie 1766
                        Package dependency = it2.next();
1767
 
1768
                        if ( dependency == p )
6914 dpurdie 1769
                        {
7071 dpurdie 1770
                            rippleBuildExclude( pkg, rootPvId, null, list, null, dependentToo, depWipsToo );
1771
                            break;
6914 dpurdie 1772
                        }
1773
                    }
7071 dpurdie 1774
 
6914 dpurdie 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
    {
7071 dpurdie 2179
        StringBuilder comment = new StringBuilder();
2180
        StringBuilder deps = new StringBuilder();
2181
 
7051 dpurdie 2182
        String joiner = "";
2183
        for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
2184
        {
2185
            String alias = it2.next();
7071 dpurdie 2186
            deps.append(joiner).append(alias); 
7051 dpurdie 2187
            joiner = ",";
2188
        }
2189
 
7071 dpurdie 2190
        comment.append("pvid=").append(p.mId);
2191
        comment.append(" name=").append('"').append(p.mAlias).append('"');
2192
        comment.append(" reason=").append(p.mNoBuildReason);
2193
        comment.append(" buildFile=").append(p.mBuildFile);
2194
        comment.append(" directlyPlanned=").append(p.mDirectlyPlanned);
2195
        comment.append(" indirectlyPlanned=").append(p.mIndirectlyPlanned);
2196
        comment.append(" depends=[").append(deps).append("]");
6914 dpurdie 2197
 
7071 dpurdie 2198
        xml.addComment(comment.toString());            
6914 dpurdie 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
}