Subversion Repositories DevTools

Rev

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

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