Subversion Repositories DevTools

Rev

Rev 7201 | Rev 7282 | 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);
7231 dpurdie 995
 
996
                        //  Insert a marker package to indicate a 'newPlan'
997
                        PlannedPackage pp = new PlannedPackage( new Package() );
998
                        pp.mBuildLevel = -1;
999
                        mBuildOrder.add(pp);                     
1000
 
7082 dpurdie 1001
                        mBuildOrder.addAll(fullPlan.planCollection);
1002
 
1003
                    } else {
1004
                        //  Use the full plan
7176 dpurdie 1005
                        mLogger.warn("Use full plan");
7082 dpurdie 1006
                        mBuildOrder.addAll(fullPlan.planCollection);
1007
                    }
1008
                } else if (!basicPlan.planCollection.isEmpty() ) {
1009
                    // Use the basic plan
7176 dpurdie 1010
                    mLogger.warn("Use basic plan");
7082 dpurdie 1011
                    mBuildOrder.addAll(basicPlan.planCollection);
1012
 
1013
                } else if ( !fullPlan.planCollection.isEmpty() ) {
1014
                    // Use the full plan
7176 dpurdie 1015
                    mLogger.warn("Use full plan");
7082 dpurdie 1016
                    mBuildOrder.addAll(fullPlan.planCollection);
1017
 
1018
                } else {
1019
                    // Do not have a plan
1020
                    // May have tests requests
7176 dpurdie 1021
                    mLogger.warn("Use NO plan");
7082 dpurdie 1022
                }
1023
 
1024
                //
7099 dpurdie 1025
                //  Now have a build order
1026
                //  Allocate new version numbers
1027
                //      Examine packages with a buidLevel of zero
1028
                //  If we fail all of them then we can't build anything
1029
                //
7176 dpurdie 1030
                mLogger.warn("Determine new version numbers");
7082 dpurdie 1031
                Package build = ReleaseManager.NULL_PACKAGE;
7099 dpurdie 1032
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1033
                {
1034
                    PlannedPackage pkg = it.next();
1035
                    if (pkg.mBuildLevel != 0)
1036
                    {
1037
                        continue;
1038
                    }
1039
 
1040
                    //
1041
                    //  Attempt to allocate a new version number
1042
                    //  If we can't generate a new version number, then this is considered to be a build failure
1043
                    //  The package will be excluded and the user will be emailed
1044
                    //
1045
                    Package p = pkg.mPkg;
1046
 
1047
                    int pvApplied = p.applyPV(mReleaseManager);
1048
 
1049
                    if ( pvApplied == 0)
1050
                    {
1051
                        build = p;
1052
                        break;
1053
                    }
1054
                    else if ( pvApplied == 1 )
1055
                    {
1056
                        // max 50 chars
1057
                        rippleBuildExclude(p, p.mId, "Package has non standard versioning", -12);
1058
                    }
1059
                    else if ( pvApplied == 2 )
1060
                    {
1061
                        // max 50 chars
1062
                        rippleBuildExclude(p, p.mId, "Package has reached ripple field limitations", -12);
1063
                    }
1064
                    else if ( pvApplied == 3 )
1065
                    {
1066
                        // max 50 chars
1067
                        rippleBuildExclude(p, p.mId, "Package has invalid change type", -12);
1068
                    }
1069
                    else
1070
                    {
1071
                        // max 50 chars
1072
                        // Bad programming - should not get here
1073
                        rippleBuildExclude(p, p.mId, "Unable to calculate next version", -12);
1074
                    }
1075
                }
1076
 
1077
 
1078
                //  Now have an mBuildOrder
1079
                //  Mark the selected package in the build order as the one to be built
1080
                //  May need to process its it a bit more
1081
                //  
7107 dpurdie 1082
                if ( build != ReleaseManager.NULL_PACKAGE)
1083
                {
7082 dpurdie 1084
                    build.mBuildFile = 1;
1085
 
1086
                    if ( build.mForcedRippleInstruction > 0 )
1087
                    {
1088
                        mReleaseManager.markDaemonInstCompleted( build.mForcedRippleInstruction );
1089
                    }
1090
 
1091
                    if ( build.mTestBuildInstruction > 0 )
1092
                    {
1093
                        mReleaseManager.markDaemonInstInProgress( build.mTestBuildInstruction );
1094
                    }
1095
 
1096
                    //  Now that we know which package we are building
1097
                    //      Set the previously calculated nextVersion as the packages version number
1098
                    //      Claim the version number to prevent other builds from using it. Even if doing a test build
1099
                    //
7118 dpurdie 1100
                    mLogger.debug("Update mVersion: {}", build);
7082 dpurdie 1101
                    if (build.mNextVersion != null)
1102
                    {
1103
                        mReleaseManager.claimVersion(build.mPid, build.mNextVersion + build.mExtension, mBaseline);
1104
                        build.mVersion = build.mNextVersion;
7176 dpurdie 1105
                        mLogger.warn("Update mVersion: {} to {}", build, build.mVersion);
7082 dpurdie 1106
                    }
1107
 
7107 dpurdie 1108
                    //
1109
                    //  Ensure that the package we are about to build is present in the mPackageCollection as its
1110
                    //  this list that is used to generate the build.xml file - that may be a bad way to do it , but ...
1111
                    //
1112
                    //  Note: Can't really modify others as they will be used as dependencies
1113
                    //
7186 dpurdie 1114
                    mPackageCollection.upsert(build);
1115
                    build.mIsNotReleased = false;
7082 dpurdie 1116
                }
7107 dpurdie 1117
 
7082 dpurdie 1118
                //
1119
                //  Report packages that are indirectly excluded
7145 dpurdie 1120
                //  ie: They will not be built because one, or more, of their dependents is not buildable
7082 dpurdie 1121
                //
7163 dpurdie 1122
                mLogger.warn("planBuildOrder process packages which are not ripple buildable");
7082 dpurdie 1123
 
7129 dpurdie 1124
                Package.resetCircularDependency (mPackageCollection);
7176 dpurdie 1125
                for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
1126
                {
1127
                    BuildExclusion be = it.next();
1128
 
1129
                    //  Only process direct exclusions
1130
                    //      mBuildExclusionCollection is at this point based on relevant (direct and indirect) 
1131
                    //      excluded pv's in the database
1132
                    //
1133
                    if ( be.isARootCause() )
1134
                    {
7082 dpurdie 1135
 
7176 dpurdie 1136
                        for (Iterator<Package> it1 = mPackageCollectionAll.iterator(); it1.hasNext(); )
1137
                        {
1138
                            Package p = it1.next();
7082 dpurdie 1139
 
7176 dpurdie 1140
                            // TODO - Do we need && p.mTestBuildInstruction == 0 && p.mForcedRippleInstruction == 0
7082 dpurdie 1141
 
7176 dpurdie 1142
                            if ( be.compare(p.mId)  )
1143
                            {
1144
                                // package is not reproducible, discard it and its consumers
1145
                                //
1146
                                mLogger.warn("Excluded Package {}, {}", p, be );                                     
1147
 
1148
                                ArrayList<Package> toExclude = new ArrayList<Package>();
7186 dpurdie 1149
                                toExclude.addAll(usedByAnyPackages(p, mPackageCollection ));
7176 dpurdie 1150
 
1151
                                //  Process packages that we need to exclude indirectly
1152
                                //
1153
                                while ( ! toExclude.isEmpty())
1154
                                {
1155
                                    Package pkg = toExclude.remove(0);
1156
 
1157
                                    // If this package has not been excluded (for whatever reason), than add it
1158
                                    boolean found = false;
1159
                                    for (Iterator<BuildExclusion> it2 = mBuildExclusionCollection.iterator(); it2.hasNext(); )
1160
                                    {
1161
                                        BuildExclusion buildExclusion = it2.next();
1162
                                        if (buildExclusion.compare(pkg.mId) )
1163
                                        {
1164
                                            found = true;
1165
                                            if  ( buildExclusion.isImported() )
1166
                                            {
1167
                                                // An exclusion for this package already exists
1168
                                                // If it was 'imported' from the database then 
1169
                                                // mark it as processed so that it will be persisted
1170
                                                //
1171
                                                // Otherwise it will be a new one
1172
                                                //
1173
                                                buildExclusion.setProcessed();
1174
                                            }
1175
                                            break;
1176
                                        }
1177
                                    }
1178
 
1179
                                    if (!found)
1180
                                    {
1181
                                        BuildExclusion buildExclusion = new BuildExclusion(pkg.mId, p.mId, null, p.mTestBuildInstruction);
1182
                                        it.add(buildExclusion);
1183
                                        mLogger.warn("Indirectly Excluded Package {}", pkg.mAlias);
1184
                                        pkg.mBuildFile = -5; 
1185
                                    }
1186
 
1187
                                    // Determine all packages that use this excluded package
1188
                                    // THAT WE HAVE NOT ALREADY PROCESSED - circular dependencies are a killer
7186 dpurdie 1189
                                    ArrayList<Package> usedBy = usedByAnyPackages(pkg, mPackageCollection );
7176 dpurdie 1190
                                    for (Iterator<Package> it2 = usedBy.iterator(); it2.hasNext(); )
1191
                                    {
1192
                                        Package uPkg = it2.next();
1193
                                        if (!uPkg.mCheckedCircularDependency)
1194
                                        {
1195
                                            toExclude.add(uPkg);
1196
                                            uPkg.mCheckedCircularDependency = true;
1197
                                        }
1198
                                    }
1199
 
1200
                                }
1201
                            }
1202
                        }
1203
                    }
1204
                }
7099 dpurdie 1205
 
1206
                 //
7163 dpurdie 1207
                 // Handle daemon Instructions that cannot be satisfied
1208
                 // Need to be rejected to prevent continuous planning
1209
                 //
1210
                 mLogger.warn("Handle unsatisfied Daemon Instructions");
1211
                 reportUnsatisfiedDaemonInstructions();
1212
 
1213
                 //
7099 dpurdie 1214
                 //  Examine the build order and 'delete' entries with a -ve mBuildFile
1215
                 //  These will be the product of pvApply errors and the packages that depend on them
7147 dpurdie 1216
                 //
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
                     }
1226
                 }
7147 dpurdie 1227
 
7231 dpurdie 1228
                 //
1229
                 // If the first entry is a 'new Plan' marker, then remove it
1230
                 //     It will be the result of applyPvs that failed
1231
                 if ( !mBuildOrder.isEmpty() )
7147 dpurdie 1232
                 {
7231 dpurdie 1233
                     PlannedPackage pkg = mBuildOrder.get(0);
1234
                     if (pkg.mBuildLevel < 0)
1235
                         mBuildOrder.remove(0);
7147 dpurdie 1236
                 }
7082 dpurdie 1237
 
1238
                //
1239
                //  To fit in with the old algorithm ( ie: could be improved )
1240
                //  Insert marks into all packages
1241
                //  Not sure exactly why - Its used in the generation of the ant build file
1242
                //                     Want to set mNoBuildReason, mBuildFile
1243
                //
1244
                //      Package we have selected to build: 0     , 1
1245
                //      Package we could have built      : 0     , 2
1246
                //      Packages we can't build          : reason, 3
1247
                //      Packages that are OK             : 3     , 3
1248
                //      ????                             : 0     , 3
1249
 
1250
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
1251
                {
1252
                    Package p = it.next();
1253
                    if (p == build ) {
1254
                        p.mNoBuildReason = 0;
1255
                        p.mBuildFile = 1;
1256
                    } 
1257
                    else if ( p.mBuildFile < 0 )
1258
                    {
1259
                        p.mNoBuildReason = p.mBuildFile;
1260
                        p.mBuildFile = 3;
1261
                    }
1262
                    else if (p.mBuildReason != null)
1263
                    {
1264
                        p.mNoBuildReason = 0;
1265
                        p.mBuildFile = 2;
1266
                    }
1267
                    else
1268
                    {
1269
                        p.mNoBuildReason = 0;
1270
                        p.mBuildFile = 3;
1271
                    }
1272
                }
1273
 
1274
            }
1275
            else
1276
            {
1277
                //  Escrow
1278
                //  The basic plan is the escrow build order
1279
                mBuildOrder = basicPlan.planCollection;
7133 dpurdie 1280
 
1281
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1282
                {
1283
                    PlannedPackage p = it.next();
1284
                    p.mPkg.mNoBuildReason = p.mPkg.mBuildFile;
1285
                    p.mPkg.mBuildFile = p.mBuildLevel + 1;
1286
                }
7082 dpurdie 1287
            }
1288
 
7118 dpurdie 1289
            mLogger.warn("Final Plan");
7082 dpurdie 1290
            for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1291
            {
1292
                PlannedPackage p = it.next();
7118 dpurdie 1293
                mLogger.warn("Plan: {} {} {}", p.mBuildLevel, p.mPkg.mAlias, p.mPkg.mId);
7082 dpurdie 1294
            }
1295
 
1296
 
1297
        }
1298
 
7201 dpurdie 1299
        /**
1300
         * Post process the basic plan to replace packages with WIPs and RIPPLES
1301
         * Done so that the displayed plan correctly indicates the time that these will be processed
1302
         * 
1303
         * @param basicPlan
1304
         */
1305
    private void addWipsAndRipples(PlanResults basicPlan) {
1306
        for (Iterator<PlannedPackage> it = basicPlan.planCollection.iterator(); it.hasNext(); )
1307
        {
1308
            PlannedPackage pkg = it.next();
1309
            Package p = mPackageCollectionWip.contains(pkg.mPkg.mAlias);
1310
            if (p == null ) {
1311
                p = mPackageCollectionRipple.contains(pkg.mPkg.mAlias); 
1312
            }
1313
 
1314
            //  Have a WIP/RIPPLE will be processed in the basic plan
1315
            //  If its eligible to be built then replace the package entry in the plan
1316
 
1317
            if (p != null && p.mBuildFile >= 0 ) {
1318
                mLogger.warn("WIP/RIPPLE consumed into basic plan: {}", p);
1319
                pkg.mPkg = p;
1320
            }
1321
        }    
1322
 
1323
    }
1324
 
7082 dpurdie 1325
    /** Internal class to contain intermediate results
1326
     */
1327
    class PlanResults {
1328
        int planTime = 0;
1329
        ArrayList<PlannedPackage> planCollection = new ArrayList<PlannedPackage>(); 
1330
    }
1331
 
1332
    /**
1333
     * Process a collection of packages and generate a collection of package plans
1334
     * A package plan is a collection of packages that can be built
1335
     *      The first item in the list is a package that can be built right now
1336
     *      Other items in the list will be packages that can be built now or will need to be built as the result
1337
     *      of a ripple
1338
     *      
1339
     * The method will be called multiple times so that we can evaluate different plans
1340
     * The underling packages will have data and flags that will need to be rested before a calculation      
1341
     *
1342
     * @param name - Name of the plan
1343
     * @param packageCollection - Base collection of packages to plan
1344
     * @param mode - true: Include 'Ripples'
1345
     * 
1346
     * @return
1347
     */
7186 dpurdie 1348
    private PlanResults planCollection(String name, PackageCollection packageCollection, boolean mode)
7082 dpurdie 1349
    {
7118 dpurdie 1350
        Phase phase = new Phase("Plan-" + name); 
7082 dpurdie 1351
        ArrayList<PlannedPackage> ripplePlan = new ArrayList<PlannedPackage>();
1352
        PlanResults results = new PlanResults();
1353
 
1354
        //  Reset flags used in the calculations
1355
        Package.resetProcessed(packageCollection);
6914 dpurdie 1356
 
7163 dpurdie 1357
 
7082 dpurdie 1358
        //  Exclude all packages that cannot be built and all packages that depend on them
1359
        //      First find packages to be directly excluded
1360
        ArrayList<Package>exclude = new ArrayList<Package>();
7099 dpurdie 1361
        phase.setPhase("Exclude Unbuildable");
7082 dpurdie 1362
        for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1363
        {
7082 dpurdie 1364
            Package p = it.next();
1365
            if ( p.mBuildFile == -8 ) {
1366
 
1367
                //  Mark SDK or Pegged so that we don't build them, but can build their dependents
1368
                p.mProcessed = true;
1369
                p.mIsProcessed = true;
7176 dpurdie 1370
                mLogger.warn("SDK/Peg Exclude: {}", p);
7082 dpurdie 1371
 
1372
            } else if (p.mBuildFile < 0 ) {
1373
                exclude.add(p);
7176 dpurdie 1374
                mLogger.warn("Direct Exclude: {}", p);
7082 dpurdie 1375
 
1376
            }
6914 dpurdie 1377
        }
1378
 
7082 dpurdie 1379
        //  Exclude packages that have failed to be built
1380
        //      These are recorded in mBuildExclusionCollection
7099 dpurdie 1381
        phase.setPhase("Exclude Build Failures");
7082 dpurdie 1382
        for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
1383
        {
1384
            BuildExclusion be = it.next();
7176 dpurdie 1385
            mLogger.warn("BE: {}", be);
7099 dpurdie 1386
            if ( !be.isAIndirectError() )
7082 dpurdie 1387
            {
1388
                for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1389
                {
1390
                    Package p = it1.next();
1391
                    if (p.mBuildFile >= 0 && p.mId == be.mId) {
1392
                        p.mBuildFile  = -3;
7176 dpurdie 1393
                        mLogger.warn("AddExclude {}",p);
7082 dpurdie 1394
                        exclude.add(p);
1395
                        break;
1396
                    }
1397
                }
1398
            }
1399
        }
1400
 
1401
 
1402
        //  Process the list of packages to be excluded
1403
        //  Add to the list packages that depend on the excluded package that have not already been excluded
7099 dpurdie 1404
        phase.setPhase("ExcludeAllUsed");
7082 dpurdie 1405
        while( !exclude.isEmpty() )
1406
        {
1407
            Package p = exclude.remove(0);
7118 dpurdie 1408
            mLogger.info("planCollection package not buildable {}. {},{}", p, p.mProcessed, p.mIsProcessed);
7082 dpurdie 1409
 
7118 dpurdie 1410
            p.mProcessed = true;                        // Used to indicate pkg has had its dependencies scanned
1411
            p.mIsProcessed = true;                      // Used to indicate pkg has been added to list to process 
1412
 
7163 dpurdie 1413
 
7082 dpurdie 1414
            for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1415
            {
1416
                Package pkg = it1.next();
1417
                if (pkg.mProcessed) {
1418
                    continue;
1419
                }
1420
 
7163 dpurdie 1421
                for (Iterator<PkgDependency> it = pkg.mDependencyCollection.iterator(); it.hasNext(); )
7082 dpurdie 1422
                {
7163 dpurdie 1423
                    PkgDependency depEntry = it.next();
1424
                    if ( p.mAlias.compareTo( depEntry.alias ) == 0 ) {
7118 dpurdie 1425
                        if (!pkg.mIsProcessed) {
1426
                            pkg.mIsProcessed = true;
7114 dpurdie 1427
                            exclude.add(pkg);
1428
                        }
7082 dpurdie 1429
                    }
1430
                }
1431
            }
1432
        }
1433
 
7133 dpurdie 1434
        // Have a collection packages that we can build right now
1435
        // Create the ripplePlan
6914 dpurdie 1436
 
7133 dpurdie 1437
        phase.setPhase("Calc Build Order");
1438
        if (mDaemon)
6914 dpurdie 1439
        {
7133 dpurdie 1440
            ArrayList<PlannedPackage> toBuild = new ArrayList<PlannedPackage>();
1441
 
7082 dpurdie 1442
            //
7133 dpurdie 1443
            //  Daemon Mode
7163 dpurdie 1444
            //  Generate the ripplePlan - collection of packages that we need to build in the current ripple
7137 dpurdie 1445
            //
7133 dpurdie 1446
            //  Determine if we have a reason to build anything in this collection of buildable packages
7201 dpurdie 1447
            //      Reset mProcessed - it will be used to detect that we have processed a package
7082 dpurdie 1448
 
1449
            for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
1450
            {
1451
                Package p = it.next();
7133 dpurdie 1452
                if (!p.mIsProcessed) {
1453
                    PlannedPackage pPkg = new PlannedPackage(p); 
1454
 
1455
                    results.planCollection.add(pPkg);
7201 dpurdie 1456
                    pPkg.mProcessed = false;
7133 dpurdie 1457
 
1458
                    if (p.mBuildReason != null) {
1459
                        if (mode || ( !mode && p.mBuildReason != BuildReason.Ripple )) {
1460
                            toBuild.add(pPkg);
1461
                        }
6914 dpurdie 1462
                    }
1463
                }
1464
            }
7082 dpurdie 1465
 
1466
            //  Need (would like to) build stuff
1467
            //  Determine the packages that we need to build and the time that it will take
1468
            //
1469
            if ( !toBuild.isEmpty() )
6914 dpurdie 1470
            {
7099 dpurdie 1471
                //  Locate the packages that we need to build
1472
                //  The build order cannot be correctly determined at this time
1473
                //      Need to add elements to the end of the list while processing
1474
                //      Sum the buildTimes of the packages that we add to the list
7082 dpurdie 1475
                while ( ! toBuild.isEmpty())
6914 dpurdie 1476
                {
7082 dpurdie 1477
                    PlannedPackage pkg = toBuild.remove(0);
1478
 
7201 dpurdie 1479
                    if ( ! pkg.mProcessed )
6914 dpurdie 1480
                    {
7082 dpurdie 1481
                        ripplePlan.add(pkg);
1482
                        results.planTime += pkg.mPkg.mBuildTime;
7201 dpurdie 1483
                        pkg.mProcessed = true;
7099 dpurdie 1484
 
7163 dpurdie 1485
                        // How do we handle duplicates ?
7099 dpurdie 1486
                        ArrayList<PlannedPackage> usedBy = usedByPackages(pkg, results.planCollection);
1487
                        toBuild.addAll(usedBy);
6914 dpurdie 1488
                    }
1489
                }
7133 dpurdie 1490
            }
1491
        }
1492
        else
1493
        {
1494
            //  Escrow
1495
            //      Add all (not excluded) packages directly to the ripplePlan
1496
            for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
1497
            {
1498
                Package p = it.next();
1499
                if (!p.mIsProcessed) {
1500
                    ripplePlan.add(new PlannedPackage(p));
1501
                }
1502
            }  
1503
        }
1504
 
1505
        //
1506
        //  Now we have a collection of packages to build (and only the packages to build)
1507
        //  Need to determine the order in which it can be done and assign build levels
1508
        //  Basically:
1509
        //      Scan the collection looking for any package whose dependencies do not exist in the collection
1510
        //      or they have been allocated a build level.
1511
        //
1512
        //      Need to do this in waves so that we can correctly determine the build level.
1513
        //
7231 dpurdie 1514
        //
1515
        //  Need two metrics out of this process
1516
        //      buildGroup - all packages in a given group depend entirely on packages in lower numbers groups
1517
        //      buildLevel - This is a function of the number of parallel builds that can be performed
1518
        //                   and 
1519
 
1520
 
1521
        //
7133 dpurdie 1522
        for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1523
        {
1524
            PlannedPackage p = it.next();
7201 dpurdie 1525
            p.mProcessed = true;
7133 dpurdie 1526
            p.mBuildLevel = 0;
1527
        }
1528
 
1529
        int buildLevel = 0;
1530
        boolean more = true;
1531
        do  {
1532
            ArrayList<PlannedPackage> thisLevel = new ArrayList<PlannedPackage>();
1533
            for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1534
            {
1535
                PlannedPackage p = it.next();
7201 dpurdie 1536
                if ( p.mProcessed )
7099 dpurdie 1537
                {
7133 dpurdie 1538
                    boolean found = false;
7163 dpurdie 1539
                    for (Iterator<PkgDependency> it2 = p.mPkg.mDependencyCollection.iterator(); !found && it2.hasNext(); )
7099 dpurdie 1540
                    {
7163 dpurdie 1541
                        PkgDependency depEntry = it2.next();
7133 dpurdie 1542
                        for (Iterator<PlannedPackage> it3 = ripplePlan.iterator(); !found && it3.hasNext(); )
7099 dpurdie 1543
                        {
7133 dpurdie 1544
                            PlannedPackage pkg = it3.next();
7163 dpurdie 1545
                            if (pkg.mPkg.mAlias.compareTo( depEntry.alias ) == 0)
7099 dpurdie 1546
                            {
7201 dpurdie 1547
                                found = pkg.mProcessed ;
7133 dpurdie 1548
                                break;
7099 dpurdie 1549
                            }
1550
                        }
1551
                    }
1552
 
7133 dpurdie 1553
                    if (!found)
7099 dpurdie 1554
                    {
7133 dpurdie 1555
                        //  None of this packages dependencies can be found in the collection of packages to build
1556
                        //  Thus we can build it - at the current level
1557
                        p.mBuildLevel = buildLevel;
1558
                        thisLevel.add(p);
7099 dpurdie 1559
                    }
7082 dpurdie 1560
                }
1561
            }
1562
 
7133 dpurdie 1563
            //  Mark all the packages at this level as have been processed
7231 dpurdie 1564
            //  Cannot do this while we are determining the packages in the level
7133 dpurdie 1565
            for (Iterator<PlannedPackage> it = thisLevel.iterator(); it.hasNext(); )
1566
            {
1567
                PlannedPackage p = it.next();
7201 dpurdie 1568
                p.mProcessed = false;
7133 dpurdie 1569
            }
1570
 
7137 dpurdie 1571
            //
1572
            //  If any packages needed to be build at this level, then there might be a higher level
1573
            //  If no packages needed to be build at this level, then there is nothing to do.
7133 dpurdie 1574
            more = !thisLevel.isEmpty(); 
1575
            buildLevel++;
1576
 
1577
        } while (more);
1578
 
1579
        //  Sort the packages by buildOrder and buildTime
1580
        phase.setPhase("Sort Plan");
1581
        Collections.sort(ripplePlan, PlannedPackage.BuildOrderComparitor);
1582
 
7137 dpurdie 1583
        //  Optionally - Display the calculated plan
1584
        //      It will fill the log, but ...
7133 dpurdie 1585
        if (mLogger.isInfoEnabled() )
1586
        {
1587
            phase.setPhase("Display Build Order");
1588
            mLogger.info("Plan Build {} Time: {}", name, results.planTime);
1589
            for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1590
            {
1591
                PlannedPackage p = it.next();
1592
                mLogger.info("Plan: {} {} t:{}", p.mBuildLevel, p.mPkg.mAlias, p.mPkg.mBuildTime);
1593
            }
7082 dpurdie 1594
        }
7133 dpurdie 1595
 
1596
        results.planCollection = ripplePlan;
7137 dpurdie 1597
 
7099 dpurdie 1598
        phase.setPhase("EndPlanCollection");
7082 dpurdie 1599
        return results;
1600
    }
6914 dpurdie 1601
 
7082 dpurdie 1602
    /** Generate a plan based on a modified set of packages
1603
     * 
1604
     * @param name      - Name of the plan
1605
     * @param basicPlan - basicPlan
1606
     * @param mode      - True: Include natural ripples and WIPS/RIPPLES that would have been done
1607
     *                          as a part of the basic plan
1608
     * @return
1609
     */
1610
    private PlanResults postRipplePlan(String name, PlanResults basicPlan, boolean mode) {
6914 dpurdie 1611
 
7186 dpurdie 1612
        PackageCollection fullPlanCollection = new PackageCollection(mPackageCollection);
7082 dpurdie 1613
        ArrayList<Package> buildCandidates = new ArrayList<Package>();
7186 dpurdie 1614
        buildCandidates.addAll(mPackageCollectionWip.mCollection);
1615
        buildCandidates.addAll(mPackageCollectionRipple.mCollection);
7082 dpurdie 1616
 
1617
        if ( !buildCandidates.isEmpty() )
1618
        {
1619
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1620
            {
1621
                Package p = it.next();
1622
                if (p.mBuildFile >= 0)
6914 dpurdie 1623
                {
7201 dpurdie 1624
                    boolean include = true;
7082 dpurdie 1625
                    if (!mode)
6914 dpurdie 1626
                    {
7088 dpurdie 1627
                        //  Exclude packages that would have been processed in the basicPlan
1628
                        for (Iterator<PlannedPackage> it1 = basicPlan.planCollection.iterator(); it1.hasNext(); )
1629
                        {
1630
                            PlannedPackage pkg = it1.next();
1631
                            if (pkg.mPkg == p)
1632
                            {
7176 dpurdie 1633
                                mLogger.warn("Test Plan without {}", p);
7201 dpurdie 1634
                                include = false;
7163 dpurdie 1635
                                break;
7088 dpurdie 1636
                            }
1637
                        }
6914 dpurdie 1638
                    }
7082 dpurdie 1639
 
7201 dpurdie 1640
                    if( include )
7082 dpurdie 1641
                    {
7201 dpurdie 1642
                        mLogger.warn("Test Plan with {}", p);
1643
                        fullPlanCollection.upsert(p);
1644
 
1645
                        Package.resetCircularDependency (fullPlanCollection);
1646
                        if ( p.hasCircularDependency( fullPlanCollection ) )
1647
                        {
1648
                            mLogger.info("planRelease circular dependency detected {}", p);
1649
 
1650
                            //  Force this package to be marked as having a circular dependency - even if its been excluded
1651
                            p.mBuildFile = 0;
1652
 
1653
                            // Exclude the package
1654
                            // max 50 chars
1655
                            rippleBuildExclude(p, p.mId, "Package has circular dependency", -6);
1656
                        }
7082 dpurdie 1657
                    }
6914 dpurdie 1658
                }
1659
            }
7082 dpurdie 1660
 
1661
        }
1662
        return planCollection(name, fullPlanCollection, mode);
1663
    }
1664
 
1665
    /** 
1666
     *  Calculate a collection of packages that actively use the named package
1667
     *  A consumer package does NOT use the named package,
7231 dpurdie 1668
     *      If the package is marked as advisoryRipple
7082 dpurdie 1669
     *      If the consumer is an SDK or is Pegged
1670
     *      If the consumer cannot be built
7231 dpurdie 1671
     *      
1672
     *  Used when planning which packages need to be built
7082 dpurdie 1673
     *   
1674
     * @param pkg - Package to process
1675
     * @param planCollection - collection of packages to scan
1676
     *
1677
     * @return A collection of packages that actively 'use' the specified package
1678
 
1679
     */
7099 dpurdie 1680
    private ArrayList<PlannedPackage> usedByPackages(PlannedPackage pkg, ArrayList<PlannedPackage> planCollection) {
7082 dpurdie 1681
        ArrayList<PlannedPackage> usedBy = new ArrayList<PlannedPackage>();
1682
 
7231 dpurdie 1683
        //  If 'this' package is marked as advisory, then don't ripple its consumers
1684
        if ( !pkg.mPkg.mAdvisoryRipple )
7082 dpurdie 1685
        {
1686
 
7231 dpurdie 1687
            for (Iterator<PlannedPackage> it = planCollection.iterator(); it.hasNext(); )
6914 dpurdie 1688
            {
7231 dpurdie 1689
                PlannedPackage p = it.next();
1690
 
1691
                //  If the (potential) consumer is an SDK or is Pegged, then we don't ripple its consumer
1692
                if  (!(p.mPkg.mIsSdk || p.mPkg.mIsPegged))
6914 dpurdie 1693
                {
7231 dpurdie 1694
                    //  Is this package 'actively used' in the current build
1695
                    if (p.mPkg.mBuildFile >= 0)
1696
                    {
1697
                        for (Iterator<PkgDependency> it2 = p.mPkg.mDependencyCollection.iterator(); it2.hasNext(); )
1698
                        {
1699
                            PkgDependency depEntry = it2.next();
1700
                            if (  pkg.mPkg.mAlias.compareTo( depEntry.alias ) == 0  ) {
1701
                                //  Have found a consumer of 'pkg'
1702
 
1703
                                usedBy.add(p);
1704
                                break;
1705
                            }
1706
                        }
6914 dpurdie 1707
                    }
1708
                }
7082 dpurdie 1709
            }
1710
        }
1711
 
1712
        return usedBy;
1713
    }
1714
 
1715
    /** 
1716
     *  Calculate a collection of packages that use the named package
7231 dpurdie 1717
     *  
1718
     *  Used when determining which packages to exclude from a build
7082 dpurdie 1719
     *   
1720
     * @param pkg - Package to process
7186 dpurdie 1721
     * @param packageCollection - collection of packages to scan
7082 dpurdie 1722
     *
1723
     * @return A collection of packages that actively 'use' the specified package
6914 dpurdie 1724
 
7082 dpurdie 1725
     */
7186 dpurdie 1726
    private ArrayList<Package> usedByAnyPackages(Package pkg, PackageCollection packageCollection) {
7082 dpurdie 1727
 
1728
        ArrayList<Package> usedBy = new ArrayList<Package>();
1729
 
7186 dpurdie 1730
        for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
7082 dpurdie 1731
        {
1732
            Package p = it.next();
1733
 
7163 dpurdie 1734
            for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
7082 dpurdie 1735
            {
7163 dpurdie 1736
                PkgDependency depEntry = it2.next();
1737
                if (  pkg.mAlias.compareTo( depEntry.alias ) == 0  ) {
7082 dpurdie 1738
                    usedBy.add(p);
1739
                    break;
1740
                }
6914 dpurdie 1741
            }
7082 dpurdie 1742
        }
1743
 
1744
        return usedBy;
6914 dpurdie 1745
    }
7163 dpurdie 1746
 
1747
    /**
1748
     *  Locate Daemon Instructions ( TEST and RIPPLE ) Requests that cannot be satisfied - will not be built due to
1749
     *  errors in dependent packages. Report the error to the user and remove the request
1750
     *  
1751
     *  These need o be rejected now as the the Master logic will plan a build a build if there is a daemon instruction
1752
     *  present. If an instruction cannot be processed and is not removed, then the daemon will continuously 'plan'
1753
     */
1754
    private void reportUnsatisfiedDaemonInstructions() throws SQLException, Exception {
7186 dpurdie 1755
        PackageCollection toProcess = new PackageCollection();
7163 dpurdie 1756
        toProcess.addAll(mPackageCollectionTest);
1757
        toProcess.addAll(mPackageCollectionRipple);
1758
 
1759
        for (Iterator<Package> it = toProcess.iterator(); it.hasNext(); )
1760
        {
1761
            Package p = it.next();
1762
 
1763
            //
1764
            //  If the package is in the 'plan, then its not excluded
1765
            //
1766
            boolean isPlanned = false;
7186 dpurdie 1767
//TODO Should mBuildOrder be  aPackageCollection            
7163 dpurdie 1768
            for (Iterator<PlannedPackage> it1 = mBuildOrder.listIterator(); it1.hasNext(); )
1769
            {
1770
                PlannedPackage pkg = it1.next();
1771
                if (pkg.mPkg == p)
1772
                {
1773
                    isPlanned = true;
1774
                    break;
1775
                }
1776
            }
1777
 
1778
            if (! isPlanned) 
1779
            {
1780
 
1781
                // If this package has been excluded, then we can't build it
1782
                //
1783
                boolean excluded = false;
1784
                for (ListIterator<BuildExclusion> it1 = mBuildExclusionCollection.listIterator(); it1.hasNext(); )
1785
                {
1786
                    BuildExclusion be = it1.next();
1787
                    if (be.compare(p.mId))
1788
                    {
1789
                        excluded = true;
1790
                        if (p.mBuildFile >= 0)
1791
                            p.mBuildFile = -5;
1792
                        break;
1793
                    }
1794
                }
1795
 
1796
 
1797
                if (excluded)
1798
                {
1799
                    String reason;
1800
                    switch (p.mBuildFile)
1801
                    {
1802
                    case -1:  reason = "Not reproducible"; break;
1803
                    case -2:  reason = "Not reproducible on configured build platforms"; break;
1804
                    case -3:  reason = "Marked as 'Do not ripple'"; break;
1805
                    case -4:  reason = "Dependent on a package not in the release"; break;
1806
                    case -5:  reason = "Indirectly dependent on a package not reproducible in the release"; break;
1807
                    case -6:  reason = "Has a circular dependency"; break;
1808
                    case -7:  reason = "Pegged or SDK package not in dpkg_archive"; break;
1809
                    case -8:  reason = "Is a Pegged or SDK package"; break;
1810
                    case -9:  reason = "Rejected Daemon Instruction"; break;
1811
                    case -10: reason = "Unbuildable package not in dpkg_archive"; break;
1812
                    case -11: reason = "Marked as 'RippleStop'"; break;
1813
                    case -12: reason = "Cannot generate next version number"; break;
1814
                    default:  reason = "Unknown reason. Code:" + p.mBuildFile; break;
1815
                    }
1816
                    mLogger.warn("planRelease Test Build of an unbuildable of package deleted: {}", p);
1817
 
1818
                    int daemonInstruction = p.mTestBuildInstruction > 0  ? p.mTestBuildInstruction : p.mForcedRippleInstruction; 
1819
                    if ( daemonInstruction <= 0)
1820
                    {
7176 dpurdie 1821
                        mLogger.warn("Daemon Instruction number not found for {}", p);
7163 dpurdie 1822
                    }
1823
 
1824
                    mReleaseManager.markDaemonInstCompleted( daemonInstruction );
1825
                    emailRejectedDaemonInstruction(reason,p);
1826
                }
1827
            }
1828
        }
1829
 
1830
    }
6914 dpurdie 1831
 
1832
    /** Determine if a given PVID is a member of the current release.
1833
     *  Used to determine if a package dependency is out of date
1834
     * 
1835
     * @param dpvId
1836
     * @return true - specified pvid is a full member of the Release
1837
     */
1838
    private boolean isInRelease(Integer dpvId) {
1839
 
7186 dpurdie 1840
        boolean inRelease = ( mPackageCollection.contains(dpvId) != null);
7082 dpurdie 1841
        return inRelease;
6914 dpurdie 1842
    }
1843
 
1844
 
7082 dpurdie 1845
    /** Reports what change in build exceptions happens as part of planRelease
1846
     * 
1847
     *  There are three types of exceptions
1848
     *      PlanError - These may be removed, if the error was not seen in the last plan
1849
     *      BuildErrors - These we persist
1850
     *      IndirectErrors - Packages that depend on a Plan or Build errors
6914 dpurdie 1851
     */
1852
    public void reportChange() throws SQLException, Exception
1853
    {
1854
        int counter = 0;
1855
        for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1856
        {
1857
            BuildExclusion buildExclusion = it.next();
1858
 
7082 dpurdie 1859
            //  Skip 'Processed' entries
7141 dpurdie 1860
            //      These will be the result of a PlanError that we have seen again
7082 dpurdie 1861
            //
7141 dpurdie 1862
            if ( buildExclusion.isProcessed() ) {
1863
                continue;
1864
            }
1865
 
1866
            //  BuildErrors     - Persist ( do nothing) These are handled elsewhere
1867
            //  PackageErrors   - Add new (ie: was not imported)
1868
            //  IndirectErrors  - Add/Remove as detected
7082 dpurdie 1869
            //  
7141 dpurdie 1870
            if (buildExclusion.isABuildError()) {
1871
                continue;
1872
 
1873
            } else if (buildExclusion.isAPackageError()) {
1874
                if (buildExclusion.isImported()) {
1875
                    continue;
7032 dpurdie 1876
                }
6914 dpurdie 1877
            }
7141 dpurdie 1878
 
1879
            if (buildExclusion.isImported()) {
1880
                // Remove from the exclusion list
7176 dpurdie 1881
                mLogger.warn("reportChange remove unused exclusion: {}", buildExclusion );
7141 dpurdie 1882
                buildExclusion.includeToBuild(mReleaseManager, mBaseline);
1883
 
1884
            } else {
1885
                // Exclude and notify
7176 dpurdie 1886
                mLogger.warn("reportChange add new exclusion: {}", buildExclusion );
7141 dpurdie 1887
                buildExclusion.excludeFromBuild(mReleaseManager, mBaseline);
7186 dpurdie 1888
                buildExclusion.email(this, mPackageCollection);
7141 dpurdie 1889
                counter++;
1890
            }
6914 dpurdie 1891
        }
7176 dpurdie 1892
        mLogger.warn("reportChange exclusion count: {}", counter);
6914 dpurdie 1893
    }
1894
 
1895
    /**reports the build plan
1896
     */
1897
    public void reportPlan() throws SQLException, Exception
1898
    {
1899
        mReleaseManager.reportPlan(mRtagId, mBuildOrder);
1900
    }
1901
 
1902
    /**Returns the first build file from the collection
1903
     * The build file will be flagged as empty if none exists
1904
     */
1905
    public BuildFile getFirstBuildFileContent()
1906
    {
1907
        mLogger.debug("getFirstBuildFileContent");
1908
 
1909
        mBuildIndex = -1;
1910
        return getNextBuildFileContent();
1911
    }
1912
 
1913
    /**Returns next build file from the collection
1914
     * The build file will be flagged as empty if none exists
1915
     */
1916
    public BuildFile getNextBuildFileContent()
1917
    {
1918
        mLogger.debug("getNextBuildFileContent");
1919
        BuildFile retVal = null;
1920
 
1921
        try
1922
        {
1923
            mBuildIndex++;
1924
            retVal = mBuildCollection.get( mBuildIndex );
1925
        }
1926
        catch( IndexOutOfBoundsException e )
1927
        {
1928
            // Ignore exception. retVal is still null.
1929
        }
1930
 
1931
        if (retVal == null)
1932
        {
1933
            retVal = new BuildFile();
1934
        }
1935
 
7044 dpurdie 1936
        mLogger.debug("getNextBuildFileContent returned {}", retVal.state.name() );
6914 dpurdie 1937
        return retVal;
1938
    }
1939
 
1940
 
1941
    /**collects meta data associated with the baseline
1942
     * this is sufficient to send an indefinite pause email notification 
1943
     *  
1944
     * Escrow: Used once to collect information about the SBOM and associated Release 
1945
     *         mBaseline is an SBOMID 
1946
     * Daemon: Used each build cycle to refresh the information 
1947
     *          mBaseline is an RTAGID
1948
     */
1949
    public void collectMetaData() throws SQLException, Exception
1950
    {
1951
        Phase phase = new Phase("cmd");
7044 dpurdie 1952
        mLogger.debug("collectMetaData mDaemon {}", mDaemon);
6914 dpurdie 1953
 
1954
        try
1955
        {
1956
            phase.setPhase("connect");
1957
            mReleaseManager.connect();
1958
 
1959
            if (! mDaemon)
1960
            {
1961
                mSbomId = mBaseline;
1962
                phase.setPhase("queryRtagIdForSbom");
1963
                mRtagId = mReleaseManager.queryRtagIdForSbom(mBaseline);
1964
                if (mRtagId == 0)
1965
                {
7033 dpurdie 1966
                    mLogger.error("SBOM does not have a matching Release. Cannot be used as a base for an Escrow"); 
6914 dpurdie 1967
                    throw new Exception("rtagIdForSbom show stopper. SBOM does not have an associated Release");
1968
                }
1969
            }
1970
 
1971
            phase.setPhase("queryReleaseConfig");
1972
            mReleaseManager.queryReleaseConfig(mRtagId);
1973
 
1974
            if (mDaemon)
1975
            {
1976
                phase.setPhase("queryMailServer");
1977
                setMailServer(mReleaseManager.queryMailServer());
1978
                phase.setPhase("queryMailSender");
1979
                setMailSender(mReleaseManager.queryMailSender());
1980
                phase.setPhase("queryGlobalAddresses");
1981
                setMailGlobalTarget(mReleaseManager.queryGlobalAddresses());
1982
                phase.setPhase("queryProjectEmail");
1983
                mMailGlobalCollection = mReleaseManager.queryProjectEmail(mBaseline);
1984
                phase.setPhase("mMailGlobalTarget");
1985
                mMailGlobalCollection.add(0,getMailGlobalTarget());
7169 dpurdie 1986
                phase.setPhase("mPlanControl");
1987
                mReleaseManager.queryPlanControl(mBaseline, mPlanControl);
6914 dpurdie 1988
            }
1989
            phase.setPhase("queryBaselineName");
1990
            mBaselineName = mReleaseManager.queryBaselineName(mBaseline);
1991
            phase.setPhase("Done");
1992
        }
1993
        finally
1994
        {
1995
            // this block is executed regardless of what happens in the try block
1996
            // even if an exception is thrown
1997
            // ensure disconnect
1998
            mReleaseManager.disconnect();
1999
        }
2000
    }
2001
 
2002
    /**
7082 dpurdie 2003
     * Sets the mBuildFile to the specified value for the package
2004
     * Does not handle dependent packages - this will be done later  
2005
     *  
7032 dpurdie 2006
     * @param p             The package being excluded 
2007
     * @param rootPvId      The PVID of the package that is causing the exclusion. Null or -ve values are special
2008
     *                      This package is the root cause, -2: Excluded by Ripple Stop 
2009
     * @param rootCause     Text message. Max 50 characters imposed by RM database 
7082 dpurdie 2010
     * @param reason        New value for mBuildFile
6914 dpurdie 2011
     */
7082 dpurdie 2012
    private void rippleBuildExclude(Package p, int rootPvId, String rootCause, int reason )
6914 dpurdie 2013
    {
2014
        mLogger.debug("rippleBuildExclude");
7082 dpurdie 2015
 
7099 dpurdie 2016
        if ( p.mBuildFile >= 0 )
6914 dpurdie 2017
        {
7088 dpurdie 2018
            p.mBuildFile = reason;
7099 dpurdie 2019
            mLogger.info("rippleBuildExclude set mBuildFile to {} for package {}", reason, p.mAlias );
7088 dpurdie 2020
 
2021
            //  Scan the complete collection looking for a matching item
2022
            //  If found then assume that this error is a a PlanError that is still present
2023
            //      Mark it as Processed to indicate that its still present
2024
            //  If found, process it, else add it (unprocessed)
2025
            boolean found = false;
2026
            for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
2027
            {
2028
                BuildExclusion buildExclusion = it.next();
6914 dpurdie 2029
 
7082 dpurdie 2030
                if ( buildExclusion.compare(p.mId, rootPvId, rootCause))
2031
                {
2032
                    buildExclusion.setProcessed();
2033
                    found = true;
2034
                    break;
2035
                }
6914 dpurdie 2036
            }
7082 dpurdie 2037
 
2038
            if (!found)
6914 dpurdie 2039
            {
7082 dpurdie 2040
                // Entry not found in the mBuildExclusionCollection. Its a new error
2041
                // 
2042
                // Mark all occurrences for this package as processed
2043
                // These will be superseded by a new build exclusion entry
6914 dpurdie 2044
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
2045
                {
2046
                    BuildExclusion buildExclusion = it.next();
2047
 
7082 dpurdie 2048
                    if ( buildExclusion.compare(p.mId))
6914 dpurdie 2049
                    {
7032 dpurdie 2050
                        buildExclusion.setProcessed();
6914 dpurdie 2051
                    }
2052
                }
2053
 
7082 dpurdie 2054
                //  Add the new build exclusion to a list
2055
                BuildExclusion buildExclusion = new BuildExclusion(p.mId, rootPvId, rootCause, p.mTestBuildInstruction);
2056
                mBuildExclusionCollection.add(buildExclusion);
6914 dpurdie 2057
            }
7082 dpurdie 2058
        }
6914 dpurdie 2059
 
7088 dpurdie 2060
        mLogger.info("rippleBuildExclude set {} {}", p.mAlias, p.mBuildFile);
6914 dpurdie 2061
    }
2062
 
2063
    /**Simple XML string escaping
2064
     * 
2065
     * @param xml		- String to escape
2066
     * @return		- A copy of the string with XML-unfriendly characters escaped 
2067
     */
2068
    public static String escapeXml( String xml )
2069
    {
2070
        xml = xml.replaceAll("&", "&amp;");
2071
        xml = xml.replaceAll("<", "&lt;");
2072
        xml = xml.replaceAll(">", "&gt;");
2073
        xml = xml.replaceAll("\"","&quot;");
2074
        xml = xml.replaceAll("'", "&apos;");
2075
        xml = xml.replaceAll("\\$", "\\$\\$");
2076
 
2077
        return xml;
2078
    }
2079
 
2080
    /** Quote a string or a string pair
2081
     *  If two strings are provided, then they will be joined with a comma.
2082
     *   
2083
     * @param text		- First string to quote
2084
     * @param text2		- Optional, second string
2085
     * @return A string of the form 'text','text2'
2086
     */
2087
    public static String quoteString(String text, String text2)
2088
    {
2089
        String result;
2090
        result =  "\'" + text + "\'";
2091
        if (text2 != null )
2092
        {
2093
            result +=  ",\'" + text2 + "\'";  
2094
        }
2095
        return result;
2096
    }
2097
 
2098
    /** Generate build file information
2099
     * 
2100
     */
2101
    private void generateBuildFiles() 
2102
    {
2103
 
2104
        // persist the build files
2105
        boolean allProcessed = false;
2106
        int buildFile = 1;
2107
        StringBuilder rawData = new StringBuilder();
2108
        StringBuilder setUp = new StringBuilder();
2109
 
2110
        mLogger.debug("generateBuildFiles");
2111
 
2112
        if ( mDaemon )
2113
        {
2114
            // all interesting packages in daemon mode match the following filter
2115
            buildFile = 3;
2116
        }
2117
 
2118
        //-----------------------------------------------------------------------
2119
        //    Generate the build file
2120
        do
2121
        {
2122
            BuildFile buildEntry = new  BuildFile();
2123
            buildEntry.state = BuildFileState.Dummy;
2124
            XmlBuilder xml = generateBuildFileHeader();
2125
 
2126
 
2127
            //	Generate properties for each package in this build level or lower build levels
2128
            //	The properties link the packageAlias to the PackageName and PackageVersion
2129
            //
2130
            //	[DEVI 54816] In escrow mode all unreproducible packages are included 
2131
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
2132
            {
2133
                Package p = it.next();
2134
 
2135
                if ( ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) ) || ( !mDaemon && p.mBuildFile == -2 ) )
2136
                {
2137
                    xml.addProperty(p.mAlias, p.mName + " " + p.mVersion + p.mExtension);
2138
                }
2139
            }
2140
 
2141
            //	UTF Support
2142
            //	Insert additional info into the build file to provide extra checking
2143
            //
7046 dpurdie 2144
            if ( ! mReleaseManager.mUseDatabase )
6914 dpurdie 2145
            {
2146
                // UTF Support
2147
                // Insert per-package planning information
2148
                //
2149
                xml.addComment("mPackageCollection");
2150
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
2151
                {
2152
                    Package p = it.next();
2153
                    generatePackageInfo(xml, p);
2154
                }
2155
 
7082 dpurdie 2156
                xml.addComment("mPackageCollectionWip");
2157
                for (Iterator<Package> it = mPackageCollectionWip.iterator(); it.hasNext(); )
2158
                {
2159
                    Package p = it.next();
2160
                    if (p.mIsNotReleased )
2161
                        generatePackageInfo(xml, p);
2162
                }
2163
 
2164
                xml.addComment("mPackageCollectionTest");
2165
                for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
2166
                {
2167
                    Package p = it.next();
2168
                    if (p.mIsNotReleased )
2169
                        generatePackageInfo(xml, p);
2170
                }
2171
 
2172
                xml.addComment("mPackageCollectionTestRipple");
2173
                for (Iterator<Package> it = mPackageCollectionRipple.iterator(); it.hasNext(); )
2174
                {
2175
                    Package p = it.next();
2176
                    if (p.mIsNotReleased )
2177
                        generatePackageInfo(xml, p);
2178
                }
2179
 
6914 dpurdie 2180
                // UTF Support
2181
                // Insert build exclusion information
2182
                xml.addComment("mBuildExclusionCollection");
2183
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
2184
                {
2185
                    BuildExclusion buildExclusion = it.next();
7164 dpurdie 2186
                    xml.addComment(buildExclusion.toString());
6914 dpurdie 2187
                }
7082 dpurdie 2188
            }
2189
 
7137 dpurdie 2190
            // UTF Support (Also while trialing the changes)
7082 dpurdie 2191
            // Insert build Plan
2192
            if (mDaemon)
2193
            {
2194
                xml.addComment("mBuildOrder");
2195
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
6914 dpurdie 2196
                {
7082 dpurdie 2197
                    PlannedPackage p = it.next();
2198
                    String comment =
2199
                            "pvid="+ p.mPkg.mId +
2200
                            " order=" + p.mBuildLevel +
2201
                            " time=" + p.mPkg.mBuildTime +
2202
                            " name=\"" + p.mPkg.mAlias + "\"";
2203
                    xml.addComment(comment);
6914 dpurdie 2204
                }
2205
            }
2206
 
2207
            //  Generate Taskdef information
2208
            generateTaskdef(xml);
2209
 
2210
            //
2211
            //  Insert known Machine Information
2212
            //  Escrow usage: 
2213
            //      Map machType to machClass
2214
            //  Also serves as a snapshot of the required build configuration
2215
            //  ie: machine types and buildfilters
2216
            //
2217
            if (!mDaemon)
2218
            {
2219
                generateMachineInfo(xml, null);
2220
            }
2221
 
2222
            //
2223
            //	Generate target rules for each package to be built within the current build file
2224
            //
2225
            boolean daemonHasTarget = false;
2226
 
7082 dpurdie 2227
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2228
            {
2229
                Package p = it.next();
2230
 
2231
                if ( p.mBuildFile > 0 && p.mBuildFile <= buildFile )
2232
                {
2233
                    generateTarget(xml, buildEntry, p, buildFile);
2234
 
2235
                    if ( p.mBuildFile == 1 )
2236
                    {
2237
                        daemonHasTarget = true;
2238
 
2239
                        // Retain information about the target package
2240
                        buildEntry.mPkgId = p.mPid;
2241
                        buildEntry.mPvId = p.mId;
2242
                    }
2243
                }
2244
 
2245
                //	Generate escrow extraction commands
2246
                //	Only done on the first pass though the packages
2247
                //
2248
                if ( !mDaemon && buildFile == 1 )
2249
                {
2250
                    setUp.append("jats jats_vcsrelease -extractfiles"
2251
                                + " \"-label=" + p.mVcsTag + "\""
2252
                                + " \"-view=" + p.mAlias + "\""
2253
                                + " -root=. -noprefix"
2254
                                + mlf );
2255
                }
2256
 
2257
                //	Generate escrow raw CSV data
2258
                //	Note: I don't think this data is used at all
2259
 
2260
                if ( !mDaemon && ( p.mBuildFile == buildFile))
2261
                {
2262
                    StringAppender machines = new StringAppender(",");
2263
                    for (Iterator<BuildStandard> it1 = p.mBuildStandardCollection.iterator(); it1.hasNext();)
2264
                    {
2265
                        BuildStandard bs = it1.next();
2266
                        machines.append(bs.mMachClass);
2267
                    }
2268
 
2269
                    rawData.append(p.mAlias + "," +
2270
                                    buildFile + "," +
2271
                                    machines +
2272
                                    mlf);
2273
                }
2274
            }
2275
 
2276
            if ( mDaemon && !daemonHasTarget )
2277
            {
2278
                // must have AbtTestPath, AbtSetUp, AbtTearDown, and AbtPublish targets
2279
                XmlBuilder target = xml.addNewElement("target");
2280
                target.addAttribute("name", "AbtTestPath");
2281
 
2282
                target = xml.addNewElement("target");
2283
                target.addAttribute("name", "AbtSetUp");
2284
 
2285
                target = xml.addNewElement("target");
2286
                target.addAttribute("name", "AbtTearDown");
2287
 
2288
                target = xml.addNewElement("target");
2289
                target.addAttribute("name", "AbtPublish");
2290
            }
2291
 
2292
            generateDefaultTarget( xml, buildFile);
2293
 
2294
            //	Convert the Xml structure into text and save it in the build file
2295
            //	Add this build file to the mBuildCollection
2296
            buildEntry.content = mXmlHeader + xml.toString();
2297
            mBuildCollection.add(buildEntry);
2298
 
2299
            // are more build files required
2300
            allProcessed = true;
2301
 
2302
            if (!mDaemon)
2303
            {
2304
                // this is escrow mode centric
7082 dpurdie 2305
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2306
                {
2307
                    Package p = it.next();
2308
 
2309
                    if ( p.mBuildFile > buildFile )
2310
                    {
2311
                        // more build files are required
2312
                        allProcessed = false;
7044 dpurdie 2313
                        mLogger.info("planRelease reiterating package has no build requirement {} {} {}",p.mName, p.mBuildFile,  buildFile);
6914 dpurdie 2314
                        break;
2315
                    }
2316
                } 
2317
 
2318
                buildFile++;
2319
            }
2320
 
2321
        } while( !allProcessed );
2322
 
2323
        //	Save additional escrow data
2324
        if ( !mDaemon )
2325
        {
2326
            mEscrowSetup = setUp.toString();
2327
            mEscrowRawData = rawData.toString();
2328
        }
2329
    }
2330
 
2331
    /**returns a build file header for the mBaseline
2332
     */
2333
    private XmlBuilder generateBuildFileHeader()
2334
    {
2335
        mLogger.debug("generateBuildFileHeader");
2336
        XmlBuilder element = new XmlBuilder("project");
2337
 
2338
        element.addAttribute("name", "mass");
2339
        element.addAttribute("default", "full");
2340
        element.addAttribute("basedir", ".");
2341
 
2342
        if ( mDaemon )
2343
        {
2344
            element.addProperty("abt_mail_server", getMailServer());
2345
            element.addProperty("abt_mail_sender", getMailSender()); 
2346
            element.addProperty("abt_rtag_id", mBaseline);
2347
            element.addProperty("abt_daemon", mReleaseManager.currentTimeMillis());
2348
            element.makePropertyTag("abt_packagetarball", true);
2349
            element.makePropertyTag("abt_usetestarchive", !ReleaseManager.getUseMutex());
2350
 
7082 dpurdie 2351
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2352
            {
2353
                Package p = it.next();
2354
 
2355
                if ( p.mBuildFile == 1 )
2356
                {
2357
                    element.addProperty("abt_package_name", p.mName);
2358
                    element.addProperty("abt_package_version", p.mVersion + p.mExtension);
2359
                    element.addProperty("abt_package_extension", p.mExtension);
2360
                    element.addProperty("abt_package_location", getBuildLocation(p));
2361
                    element.addProperty("abt_package_ownerlist", p.emailInfoNonAntTask(this));
2362
                    element.addProperty("abt_package_build_info", buildInfoText(p));
2363
 
2364
                    // depends in the form 'cs','25.1.0000.cr';'Dinkumware_STL','1.0.0.cots'
2365
                    StringAppender depends = new StringAppender(";");
2366
 
7163 dpurdie 2367
                    for (Iterator<PkgDependency> it3 = p.mDependencyCollection.iterator(); it3.hasNext(); )
6914 dpurdie 2368
                    {
7163 dpurdie 2369
                        PkgDependency depEntry = it3.next();
2370
                        depends.append( quoteString(depEntry.pkg.mName, depEntry.pkg.mVersion + depEntry.pkg.mExtension) );
6914 dpurdie 2371
                    }
2372
 
2373
                    element.addProperty("abt_package_depends", depends.toString());
2374
                    element.addProperty("abt_is_ripple", p.mDirectlyPlanned ? "0" : "1");
2375
                    element.addProperty("abt_build_reason", p.mBuildReason.toString());
2376
                    element.addProperty("abt_package_version_id", p.mId);
2377
                    element.addProperty("abt_does_not_require_source_control_interaction", ! p.mRequiresSourceControlInteraction ? "true" : "false" );
2378
                    element.addProperty("abt_test_build_instruction", p.mTestBuildInstruction);
7155 dpurdie 2379
                    element.addProperty("abt_vcs_tag", p.mVcsTag);
6914 dpurdie 2380
                }
2381
            }
2382
        }
2383
        else
2384
        {
2385
            //    Escrow Mode
2386
            element.addProperty("abt_rtag_id", mRtagId);
2387
            element.addProperty("abt_sbom_id", mSbomId);
2388
        }
2389
 
2390
        element.addProperty("abt_release", escapeXml(mBaselineName));
2391
        element.addProperty("abt_buildtool_version", mReleaseManager.getMajorVersionNumber() );
2392
 
2393
        element.addNewElement("condition")
2394
        .addAttribute("property", "abt_family")
2395
        .addAttribute("value", "windows")
2396
        .addNewElement("os")
2397
        .addAttribute("family", "windows");
2398
        element.addProperty("abt_family", "unix");
2399
 
2400
        return element;
2401
    }
2402
 
2403
    /** Add task def XML items taskdef for the abt ant task
2404
     * @param xml 	- xml item to extend
2405
     */
2406
    private void generateTaskdef(XmlBuilder xml)
2407
    {
2408
        mLogger.debug("generateTaskdef");
2409
        xml.addNewElement("taskdef")
2410
        .addAttribute("name", "abt")
2411
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABT");
2412
 
2413
        xml.addNewElement("taskdef")
2414
        .addAttribute("name", "abtdata")
2415
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABTData");
2416
    }
2417
 
2418
    /** returns the command abtdata items
2419
     *  <br>Common machine information
2420
     *  <br>Common email address
2421
     *  
2422
     *  
2423
     *  @param	xml - Xml element to extend   
2424
     *  @param    p - Package (May be null)
2425
     */
2426
    private void generateMachineInfo(XmlBuilder xml, Package p)
2427
    {
2428
        XmlBuilder element = xml.addNewElement("abtdata");
2429
        element.addAttribute("id", "global-abt-data");
2430
 
2431
        //
2432
        //  Iterate over all the machines and create a nice entry
2433
        //
2434
        for (Iterator<ReleaseConfig> it = mReleaseManager.mReleaseConfigCollection.mReleaseConfig.iterator(); it.hasNext(); )
2435
        {
2436
            ReleaseConfig rc = it.next();
2437
            element.addElement(rc.getMachineEntry());
2438
        }
2439
 
2440
        //
2441
        //  Now the email information
2442
        //
2443
        if ( p != null)
2444
        {
2445
            p.emailInfo(this, element);
2446
        }
2447
    }
2448
 
2449
    /** Generate package information
2450
     *  Only when running unit tests
2451
     *  
2452
     * @param xml	- An xml element to append data to
2453
     * @param p	- Package to process
2454
     */
2455
    private void generatePackageInfo (XmlBuilder xml, Package p)
2456
    {
7082 dpurdie 2457
        StringBuilder comment = new StringBuilder();
2458
        StringBuilder deps = new StringBuilder();
2459
 
2460
        String joiner = "";
7163 dpurdie 2461
        for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
7082 dpurdie 2462
        {
7163 dpurdie 2463
            PkgDependency depEntry = it2.next();
2464
            deps.append(joiner).append(depEntry.alias); 
7082 dpurdie 2465
            joiner = ",";
2466
        }
2467
 
2468
        comment.append("pvid=").append(p.mId);
2469
        comment.append(" name=").append('"').append(p.mAlias).append('"');
2470
        comment.append(" reason=").append(p.mNoBuildReason);
2471
        comment.append(" buildFile=").append(p.mBuildFile);
2472
        comment.append(" directlyPlanned=").append(p.mDirectlyPlanned);
2473
        comment.append(" indirectlyPlanned=").append(p.mIndirectlyPlanned);
2474
        comment.append(" depends=[").append(deps).append("]");
6914 dpurdie 2475
 
7082 dpurdie 2476
        xml.addComment(comment.toString());            
6914 dpurdie 2477
    }
2478
 
2479
    /**returns an ant target for the passed Package
2480
     * in daemon mode:
2481
     *  packages are categorized with one of three mBuildFile values:
2482
     *   1 the package to be built by this buildfile
2483
     *   2 the packages with a future build requirement
2484
     *   3 the packages with no build requirement
2485
     *  the returned target depends on this categorization and will have
2486
     *   1 full abt info
2487
     *   2 full dependency info to determine future build ordering but no abt info (will not build this package)
2488
     *   3 only a name attribute (will not build this package)
2489
     * in escrow mode:
2490
     *  if the passed Package's mBuildFile is different (less than) the passed build file,
2491
     *  the returned target have only a name attribute (will not build this package)
2492
     *   
2493
     * @param xml - Xml element to extend
2494
     * @param buildEntry - Record build type (dummy/generic/not generic)
2495
     * @param p - Package to process
2496
     * @param buildFile - buildfile level being processed
2497
     */
2498
    private void generateTarget(XmlBuilder xml, BuildFile buildEntry, Package p, int buildFile)
2499
    {
2500
        mLogger.debug("generateTarget");
2501
 
2502
        //---------------------------------------------------------------------
2503
        //  Generate the AbtData - common machine and email information
2504
        //  Only used by the daemon builds
2505
        //
2506
        if ( mDaemon && p.mBuildFile == 1 )
2507
        {
2508
            generateMachineInfo(xml, p );
2509
        }
2510
 
2511
        //-------------------------------------------------------------------------
2512
        //  Generate the <target name=... /> construct
2513
        //  There are two types
2514
        //      1) Simple dummy place holder. Just has the PackageName.PackageExt
2515
        //      2) Full target. Has all information to build the package including
2516
        //              AbtSetUp, AbtTearDown and AbtPublish targets
2517
        //
2518
 
2519
        if ( !mDaemon && ( p.mBuildFile < buildFile ) )
2520
        {
2521
            XmlBuilder target = xml.addNewElement("target");
2522
            target.addAttribute("name", p.mAlias);
2523
        }
2524
        else
2525
        {
2526
            if (!mDaemon) 
2527
            {
2528
                //  Escrow Only:
2529
                //  Generate the 'wrapper' target
2530
                //  This is used to ensure that the required dependencies have been built - I think
2531
                //
2532
                StringAppender dependList = new StringAppender(",");
7163 dpurdie 2533
                if ( !p.mDependencyCollection.isEmpty() )
6914 dpurdie 2534
                {
7163 dpurdie 2535
                    for (Iterator<PkgDependency> it = p.mDependencyCollection.iterator(); it.hasNext(); )
6914 dpurdie 2536
                    {
7163 dpurdie 2537
                        PkgDependency depEntry = it.next();
2538
                        if ( !mDaemon && depEntry.pkg.mBuildFile == -2 )
6914 dpurdie 2539
                        {
2540
                            // ignore targets which build in foreign environments in escrow mode
2541
                            continue;
2542
                        }
7163 dpurdie 2543
                        dependList.append(depEntry.pkg.mAlias);
6914 dpurdie 2544
                    }
2545
                }
2546
 
2547
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2548
                target.addAttribute("name", p.mAlias + ".wrap");
2549
 
2550
                if (dependList.length() > 0)
2551
                {
2552
                    target.addAttribute("depends", dependList.toString() );
2553
                }
2554
 
2555
                if ( !mDaemon )
2556
                {
2557
                    boolean hasDependenciesBuiltInThisIteration = false;
7163 dpurdie 2558
                    if ( ( !p.mDependencyCollection.isEmpty()) )
6914 dpurdie 2559
                    {
7163 dpurdie 2560
                        for (Iterator<PkgDependency> it = p.mDependencyCollection.iterator(); it.hasNext(); )
6914 dpurdie 2561
                        {
7163 dpurdie 2562
                            PkgDependency depEntry = it.next();
6914 dpurdie 2563
 
7163 dpurdie 2564
                            if ( depEntry.pkg.mBuildFile == buildFile )
6914 dpurdie 2565
                            {
2566
                                hasDependenciesBuiltInThisIteration = true;
2567
                                break;
2568
                            }
2569
                        }
2570
                    }
2571
 
2572
                    if ( hasDependenciesBuiltInThisIteration )
2573
                    {
2574
                        XmlBuilder condition = target.addNewElement("condition");
2575
                        condition.addAttribute("property",  p.mAlias + ".build");
2576
 
2577
                        XmlBuilder and = condition.addNewElement("and");
2578
 
7163 dpurdie 2579
                        for (Iterator<PkgDependency> it = p.mDependencyCollection.iterator(); it.hasNext(); )
6914 dpurdie 2580
                        {
7163 dpurdie 2581
                            PkgDependency depEntry = it.next();
6914 dpurdie 2582
 
7163 dpurdie 2583
                            if ( depEntry.pkg.mBuildFile == buildFile )
6914 dpurdie 2584
                            {
2585
                                XmlBuilder or = and.addNewElement("or");
2586
 
2587
                                XmlBuilder equal1 = or.addNewElement("equals");
7163 dpurdie 2588
                                equal1.addAttribute("arg1", "${" + depEntry.pkg.mAlias + ".res}");
6914 dpurdie 2589
                                equal1.addAttribute("arg2", "0");
2590
 
2591
                                XmlBuilder equal2 = or.addNewElement("equals");
7163 dpurdie 2592
                                equal2.addAttribute("arg1", "${" + depEntry.pkg.mAlias + ".res}");
6914 dpurdie 2593
                                equal2.addAttribute("arg2", "257");
2594
                            }
2595
                        }
2596
                    }
2597
                    else
2598
                    {
2599
                        target.addProperty(p.mAlias + ".build", "");
2600
                    }
2601
                }
2602
            }
2603
 
2604
 
2605
            //
2606
            //  Generate the 'body' of the target package
2607
            //  Escrow Mode: Always
2608
            //  Daemon Mode: Only for the one target we are building
2609
            //                  Simplifies the XML
2610
            //                  Reduces noise in the logs
2611
            //              Don't add target dependencies. 
2612
            //                  We are only building one target and the 
2613
            //                  dependency management has been done way before now.
2614
            //                  All it does is makes the logs noisy.
2615
            //
2616
            if ( ( mDaemon && p.mBuildFile == 1 ) || !mDaemon )
2617
            {
2618
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2619
                target.addAttribute("name", p.mAlias);
2620
 
2621
                if ( !mDaemon )
2622
                {
2623
                    target.addAttribute("depends",  p.mAlias + ".wrap");
2624
                    target.addAttribute("if",p.mAlias + ".build");
2625
                }
2626
 
2627
                if ( mDaemon && p.mBuildFile == 1 )
2628
                {
2629
                    target.addProperty(p.mAlias + "pkg_id",p.mPid);
2630
                    target.addProperty(p.mAlias + "pv_id",p.mId);
2631
                }
2632
 
2633
                target.addProperty(p.mAlias + "packagename",p.mName);        		
2634
                target.addProperty(p.mAlias + "packageversion",p.mVersion);
2635
                target.addProperty(p.mAlias + "packageextension",p.mExtension);
2636
                target.addProperty(p.mAlias + "packagevcstag",p.mVcsTag);
2637
 
2638
                target.makePropertyTag(p.mAlias + "directchange", p.mDirectlyPlanned); 
2639
                target.makePropertyTag(p.mAlias + "doesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2640
 
2641
                buildEntry.state = BuildFile.BuildFileState.NonGeneric;
2642
                if ( p.isGeneric() )
2643
                {
2644
                    buildEntry.state = BuildFile.BuildFileState.Generic;
2645
                    target.makePropertyTag(p.mAlias + "generic", true); 
2646
                }
2647
 
2648
                target.addProperty(p.mAlias + "loc", getBuildLocation(p));
2649
                target.makePropertyTag(p.mAlias + "unittests", p.mHasAutomatedUnitTests && mDaemon);
2650
 
2651
                //    Add our own task and associated information
2652
                //
2653
                XmlBuilder abt = target.addNewElement("abt").isExpanded();
2654
 
7163 dpurdie 2655
                for (Iterator<PkgDependency> it = p.mDependencyCollection.iterator(); it.hasNext(); )
6914 dpurdie 2656
                {
7163 dpurdie 2657
                    PkgDependency depEntry = it.next();
6914 dpurdie 2658
                    XmlBuilder depend = abt.addNewElement("depend");
7163 dpurdie 2659
                    depend.addAttribute("package_alias", "${" + depEntry.pkg.mAlias + "}");
6914 dpurdie 2660
                }
2661
 
2662
                buildInfo(abt,p);
2663
 
2664
                if ( mDaemon && p.mBuildFile == 1 )
2665
                {
2666
                    //    AbtTestPath
2667
                    target = xml.addNewElement("target").isExpanded();
2668
                    target.addAttribute("name", "AbtTestPath");
2669
                    target.addProperty("AbtTestPathpackagevcstag", p.mVcsTag);
2670
                    target.addProperty("AbtTestPathpackagename", p.mName);
2671
                    abt = target.addNewElement("abt").isExpanded();
2672
                    buildInfo(abt, p);
2673
 
2674
 
2675
                    //    AbtSetUp
2676
                    target = xml.addNewElement("target").isExpanded();
2677
                    target.addAttribute("name", "AbtSetUp");
2678
                    target.addProperty("AbtSetUppackagevcstag", p.mVcsTag);
2679
                    target.addProperty("AbtSetUppackagename", p.mName);
2680
 
2681
                    abt = target.addNewElement("abt").isExpanded();
2682
                    buildInfo(abt, p);
2683
 
2684
                    //    AbtTearDown
2685
                    target = xml.addNewElement("target").isExpanded();
2686
                    target.addAttribute("name", "AbtTearDown");
2687
                    target.addProperty("AbtTearDownpackagevcstag", p.mVcsTag);
2688
                    target.addProperty("AbtTearDownpackagename", p.mName);
2689
                    target.addProperty("AbtTearDownpackageversion", p.mVersion);
2690
                    target.addProperty("AbtTearDownpackageextension", p.mExtension);
2691
                    target.makePropertyTag(p.mAlias + "generic", p.isGeneric());
2692
 
2693
                    abt = target.addNewElement("abt").isExpanded();
2694
                    buildInfo(abt, p);
2695
 
2696
 
2697
                    //  AbtPublish
2698
                    target = xml.addNewElement("target").isExpanded();
2699
                    target.addAttribute("name", "AbtPublish");
2700
 
2701
                    target.addProperty("AbtPublishpackagevcstag", p.mVcsTag);
2702
                    target.addProperty("AbtPublishpackagename", p.mName);
2703
                    target.addProperty("AbtPublishpackageversion", p.mVersion);
2704
                    target.addProperty("AbtPublishpackageextension", p.mExtension);
2705
                    target.makePropertyTag("AbtPublishdirectchange", p.mDirectlyPlanned);
2706
                    target.makePropertyTag("AbtPublishdoesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2707
                    target.makePropertyTag("AbtPublishgeneric", p.isGeneric());
2708
                    target.addProperty("AbtPublishloc", getBuildLocation(p));
2709
 
2710
                    abt = target.addNewElement("abt").isExpanded();
2711
                    buildInfo(abt, p);
2712
 
2713
                }
2714
            }
2715
        }
2716
    }
2717
 
2718
    /** Extends the xml object. Adds ant default target for the current build iteration
2719
     * @param xml - The XmlBuilder Object to extend
2720
     * @param buildFile - The current build file level. This differs for Daemon and Escrow mode. In Daemon mode it will not be a '1' 
2721
     */
2722
    private void generateDefaultTarget(XmlBuilder xml, int buildFile)
2723
    {
2724
        mLogger.debug("generateDefaultTarget");
2725
 
2726
        XmlBuilder target = xml.addNewElement("target").isExpanded();
2727
        target.addAttribute("name", "fullstart");
2728
 
2729
        if (buildFile == 1)
2730
        {
2731
            antEcho(target, "${line.separator}" + mAnyBuildPlatforms + "${line.separator}${line.separator}");
7082 dpurdie 2732
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2733
            {
2734
                Package p = it.next();
2735
 
2736
                if ( p.mBuildFile == -1 )
2737
                {
2738
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2739
                }
2740
            }
2741
 
2742
            antEcho(target, "${line.separator}" + mAssocBuildPlatforms + "${line.separator}${line.separator}");
7082 dpurdie 2743
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2744
            {
2745
                Package p = it.next();
2746
 
2747
                if ( p.mBuildFile == -2 )
2748
                {
2749
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2750
                }
2751
            }
2752
 
2753
            antEcho(target, "${line.separator}" + mNotInBaseline + "${line.separator}${line.separator}");
7082 dpurdie 2754
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2755
            {
2756
                Package p = it.next();
2757
 
2758
                if ( p.mBuildFile == -4 )
2759
                {
2760
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2761
                }
2762
            }
2763
 
2764
            antEcho(target, "${line.separator}" + mDependent + "${line.separator}${line.separator}");
7082 dpurdie 2765
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2766
            {
2767
                Package p = it.next();
2768
 
2769
                if ( p.mBuildFile == -5 )
2770
                {
2771
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2772
                }
2773
            }
2774
        }
2775
 
2776
        if ( !mDaemon )
2777
        {
2778
            antEcho(target, "${line.separator}Build Started:${line.separator}${line.separator}");
2779
        }
2780
 
2781
        //
2782
        //	Create a comma separated list of all the required targets
2783
        //      Escrow : All packages
2784
        //      Daemon : Just the package being built
2785
        //
2786
        StringAppender dependList = new StringAppender(",");
2787
        dependList.append("fullstart");
7082 dpurdie 2788
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2789
        {
2790
            Package p = it.next();
2791
 
2792
            if ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) )
2793
            {
2794
                if ((mDaemon && p.mBuildFile == 1) || !mDaemon)
2795
                {
2796
                    dependList.append(p.mAlias);                    
2797
                }
2798
            }
2799
        }
2800
 
2801
        target = xml.addNewElement("target").isExpanded();
2802
        target.addAttribute("name", "full");
2803
        target.addAttribute("depends", dependList.toString());
2804
 
2805
        if ( !mDaemon )
2806
        {
2807
            antEcho(target, "${line.separator}Build Finished${line.separator}");
2808
        }
2809
    }
2810
 
2811
    /** Internal helper function to create an ant 'echo statement
2812
     *  Many of the parameters are fixed
2813
     */
2814
    private void antEcho( XmlBuilder xml, String message)
2815
    {
2816
        XmlBuilder msg = xml.addNewElement("echo");
2817
        msg.addAttribute("message", message);
2818
        msg.addAttribute("file", "publish.log");
2819
        msg.addAttribute("append", "true");
2820
    }
2821
 
2822
    /**sets the mIndirectlyPlanned true for the package and all dependent packages
2823
     */
2824
    private void rippleIndirectlyPlanned(Package p)
2825
    {
2826
        mLogger.debug("rippleIndirectlyPlanned");
2827
        if ( !p.mIndirectlyPlanned && p.mBuildFile == 0 )
2828
        {
2829
            p.mIndirectlyPlanned = true;
2830
 
7082 dpurdie 2831
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2832
            {
2833
                Package pkg = it.next();
2834
 
2835
                if ( pkg != p )
2836
                {
7163 dpurdie 2837
                    for (Iterator<PkgDependency> it2 = pkg.mDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 2838
                    {
7163 dpurdie 2839
                        PkgDependency depEntry = it2.next();
6914 dpurdie 2840
 
7163 dpurdie 2841
                        if ( depEntry.pkg == p )
6914 dpurdie 2842
                        {
2843
                            rippleIndirectlyPlanned( pkg );
2844
                            break;
2845
                        }
2846
                    }
2847
                }
2848
            }
2849
        }
7044 dpurdie 2850
        mLogger.info("rippleIndirectlyPlanned set {} {}", p.mName, p.mIndirectlyPlanned);    
6914 dpurdie 2851
    }
2852
 
2853
    /**accessor method
2854
     */
2855
    public String getEscrowSetUp()
2856
    {
2857
        mLogger.debug("getEscrowSetUp");
2858
        String retVal = mEscrowSetup;
2859
 
7044 dpurdie 2860
        mLogger.debug("getEscrowSetUp returned {}", retVal);
6914 dpurdie 2861
        return retVal;
2862
    }
2863
 
2864
    /**accessor method
2865
     */
2866
    public String getRawData()
2867
    {
2868
        mLogger.debug("getRawData");
2869
        String retVal = mEscrowRawData;
2870
 
7044 dpurdie 2871
        mLogger.debug("getRawData returned {}", retVal);
6914 dpurdie 2872
        return retVal;
2873
    }
2874
 
2875
    /**Get the build loc (location)
2876
     * This is package specific and will depend on the build mode (Escrow/Daemon)
2877
     * 
2878
     * @param	p - Package being built
2879
     * @return A string that describes the build location
2880
     */
2881
    private String getBuildLocation(Package p)
2882
    {
2883
        mLogger.debug("locationProperty");
2884
        String location = "";
2885
 
2886
        if (mDaemon)
2887
        {
2888
            // Daemon: Start in root of view/workspace
2889
            location += mBaseline;
2890
        }
2891
        else
2892
        {
2893
            // Escrow: mAlias used with jats -extractfiles -view
2894
            location += p.mAlias;
2895
        }
2896
 
2897
        //
2898
        //  Always use '/' as a path separator - even if user has specified '\'
2899
        //  Ant can handle it.
2900
        //
2901
        location = location.replace('\\', '/');
2902
        return location;
2903
    }
2904
 
2905
    /**Adds package build into as XML elements 
2906
     * @param	  xml 	- Xml element to extend
2907
     * @param   p       - Package to process
2908
     */
2909
    private void buildInfo(XmlBuilder xml, Package p)
2910
    {
2911
        mLogger.debug("buildInfo");
2912
 
2913
        //
2914
        // Create the xml build information
2915
        // <platform gbe_machtype="linux_i386" type="jats" arg="all"/>
2916
        //
2917
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext();)
2918
        {
2919
            BuildStandard bs = it.next();
2920
            bs.getBuildStandardXml(xml);
2921
        }
2922
    }
2923
 
2924
    /**returns the buildInfo as a single line of text
2925
     * Used for reporting purposes only
2926
     * @param   p       - Package to process
2927
     * 
2928
     */
2929
    public String buildInfoText(Package p)
2930
    {
2931
        mLogger.debug("buildInfoText");
2932
 
2933
        StringAppender result = new StringAppender (";");
2934
 
2935
        //
2936
        //  Create platform:standards
2937
        //      
2938
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext(); )
2939
        {
2940
            BuildStandard bs = it.next();
2941
 
2942
            if ( bs.isActive() )
2943
            {
2944
                String info = bs.getBuildStandardText();
2945
                result.append(info);
2946
            }
2947
        }
2948
 
7176 dpurdie 2949
        mLogger.debug("buildInfoText returned {}", result);
6914 dpurdie 2950
        return result.toString();
2951
    }
2952
 
2953
    /**prints to standard out in escrow mode only
2954
     * <br>Prints a title and information. The title is only printed once.
2955
     * 
2956
     * @param header - The message title to display, if printMessage is true
2957
     * @param text - A package name. Really just the 2nd line of the message
2958
     * @param printHeader -  Controls the printing of the message argument
2959
     */
2960
    private void standardOut(final String header, final String text, boolean printHeader)
2961
    {
2962
        mLogger.debug("standardOut");
2963
        if (!mDaemon)
2964
        {
2965
            if ( printHeader )
2966
            {
2967
                System.out.println(header);
2968
            }
2969
 
2970
            System.out.println(text);
2971
        }
2972
    }
2973
 
2974
 
2975
    /**
2976
     *  Email users about a rejected daemon instruction
2977
     *  @param  reason  - Reason for the rejection
2978
     *  @param  pkg     - Package to be affected by the instruction
2979
     *  
2980
     */
2981
    public void emailRejectedDaemonInstruction(String reason, Package p)
2982
    {
2983
        mLogger.debug("emailRejectedDaemonInstruction");
2984
 
2985
        //  Email Subject
2986
        String subject = "BUILD FAILURE of Daemon Instruction on package " + p.mAlias;
2987
 
2988
        // Email Body
2989
        String mailBody = "The build system reject the the Daemon Instruction";
7164 dpurdie 2990
 
6914 dpurdie 2991
        mailBody += "<p>Release: " + mBaselineName 
7164 dpurdie 2992
                 +  "<br>Package: " + p.mAlias
2993
                 +  "<br>Cause : " + reason
2994
                 +  "<br>Rm Ref: " + CreateUrls.generateRmUrl(getRtagId(), p.mId); 
6914 dpurdie 2995
 
2996
        mailBody += "<p><hr>";
2997
 
2998
        String target = p.emailInfoNonAntTask(this);
2999
 
7176 dpurdie 3000
        mLogger.info("emailRejectedDaemonInstruction Server: {}", getMailServer());
3001
        mLogger.info("emailRejectedDaemonInstruction Sender: {}", getMailSender());
3002
        mLogger.warn("emailRejectedDaemonInstruction Target: {}", target);
6914 dpurdie 3003
 
3004
        try
3005
        {
3006
            //    
7082 dpurdie 3007
            Smtpsend.send(getMailServer(),  // mailServer
3008
                    getMailSender(),        // source
3009
                    target,                 // target
3010
                    getMailSender(),        // cc
3011
                    null,                   // bcc
3012
                    subject,                // subject
3013
                    mailBody,               // body
3014
                    null                    // attachment
6914 dpurdie 3015
                    );
3016
        } catch (Exception e)
3017
        {
7044 dpurdie 3018
            mLogger.warn("Email Failure: emailRejectedDaemonInstruction:{}", e.getMessage());
6914 dpurdie 3019
        }
3020
    }
3021
 
7164 dpurdie 3022
    /** Send an email notifying users that a rippleStop has been triggered
3023
     *  The use will need to take some action
3024
     * @param p - Package
3025
     */
3026
    private void emailRippleStop(Package p) {
3027
        mLogger.debug("emailRippleStop");
3028
 
3029
        //  Email Subject
3030
        String subject = "BUILD FAILURE on package " + p.mAlias;
3031
 
3032
        // Failure Reason
3033
        String reason = "Ripple Required. Waiting for user action";
3034
 
3035
        // Email Body
3036
        String mailBody = "<p>Release: " + mBaselineName 
3037
                       +  "<br>Package: " + p.mAlias
3038
                       +  "<br>Cause : " + reason
3039
                       +  "<br>Rm Ref: " + CreateUrls.generateRmUrl(getRtagId(), p.mId); 
3040
 
3041
        mailBody += "<p><hr>";
3042
 
3043
        String target = p.emailInfoNonAntTask(this);
3044
 
7176 dpurdie 3045
        mLogger.info("emailRippleStop Server: {}", getMailServer());
3046
        mLogger.info("emailRippleStop Sender: {}", getMailSender());
7164 dpurdie 3047
        mLogger.warn("emailRippleStop Target: {}", target);
3048
 
3049
        try
3050
        {
3051
            //    
3052
            Smtpsend.send(getMailServer(),  // mailServer
3053
                    getMailSender(),        // source
3054
                    target,                 // target
3055
                    getMailSender(),        // cc
3056
                    null,                   // bcc
3057
                    subject,                // subject
3058
                    mailBody,               // body
3059
                    null                    // attachment
3060
                    );
3061
        } catch (Exception e)
3062
        {
3063
            mLogger.warn("Email Failure: emailRippleStop:{}", e.getMessage());
3064
        }
3065
 
3066
    }
3067
 
6914 dpurdie 3068
    /**
3069
     * @return the mMailServer
3070
     */
3071
    public String getMailServer() {
3072
        return mMailServer;
3073
    }
3074
 
3075
    /**
3076
     * @param mMailServer the mMailServer to set
3077
     */
3078
    public void setMailServer(String mMailServer) {
3079
        this.mMailServer = mMailServer;
3080
    }
3081
 
3082
    /**
3083
     * @return the mMailSender
3084
     */
3085
    public String getMailSender() {
3086
        return mMailSender;
3087
    }
3088
 
3089
    /**
3090
     * @param mMailSender the mMailSender to set
3091
     */
3092
    public void setMailSender(String mMailSender) {
3093
        this.mMailSender = mMailSender;
3094
    }
3095
 
3096
    /**
3097
     * @return the mMailGlobalTarget
3098
     */
3099
    public String getMailGlobalTarget() {
3100
        return mMailGlobalTarget;
3101
    }
3102
 
3103
    /**
3104
     * @param mMailGlobalTarget the mMailGlobalTarget to set
3105
     */
3106
    public void setMailGlobalTarget(String mMailGlobalTarget) {
3107
        this.mMailGlobalTarget = mMailGlobalTarget;
3108
    }
3109
 
3110
}