Subversion Repositories DevTools

Rev

Rev 7169 | Rev 7186 | 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
     */
81
    private ArrayList<Package> mPackageCollection = new ArrayList<Package>();
7082 dpurdie 82
    private ArrayList<Package> mPackageCollectionWip = new ArrayList<Package>();
83
    private ArrayList<Package> mPackageCollectionTest = new ArrayList<Package>();
84
    private ArrayList<Package> mPackageCollectionRipple = new ArrayList<Package>();
85
    private ArrayList<Package> mPackageCollectionAll = new ArrayList<Package>();
86
 
6914 dpurdie 87
 
88
    /**index to current String item
89
     * @attribute
90
     */
91
    private int mBuildIndex;
92
 
93
    /**Database abstraction
94
     * @attribute
95
     */
96
    ReleaseManager mReleaseManager;
97
 
98
    /**Baseline identifier (rtag_id for a release manager baseline, bom_id for deployment manager baseline)
99
     * @attribute
100
     */
101
    private int mBaseline;
102
 
103
    /** Escrow Only: SBOM_ID
104
     */
105
    private int mSbomId;
106
 
107
    /** RTAG_ID
108
     *  Set from mBaseline
109
     */
110
    private int mRtagId;
111
 
112
    /**When true, mBuildCollection contains one item based on a release manager rtag_id and contains a daemon property
113
     * When false, mBuildCollection contains at least one item based on a deployment manager bom_id
114
     * Will be accessed by the Package class to calculate its mAlias
115
     * @attribute
116
     */
117
    public boolean mDaemon;
118
 
119
    /**collection of build file content in String form
120
     * @attribute
121
     */
122
    private ArrayList<BuildFile> mBuildCollection = new ArrayList<BuildFile>();
123
 
124
    /** List of packages that we plan to build
125
     * Used to provide feedback into RM
126
     * Only the first entry is about to be built as we re-plan every cycle
127
     */
7082 dpurdie 128
    private ArrayList<PlannedPackage> mBuildOrder = new ArrayList  <PlannedPackage>();
7163 dpurdie 129
 
6914 dpurdie 130
    /**Warning message
131
     * @attribute
132
     */
133
    private static final String mAnyBuildPlatforms = "Warning. The following package versions are not reproducible on any build platform: ";
134
 
135
    /**Flag to control output to standard out
136
     * @attribute
137
     */
138
    private boolean mAnyBuildPlatformsFlag = true;
139
 
140
    /**Warning message
141
     * @attribute
142
     */
143
    private static final String mAssocBuildPlatforms = "Warning. The following package versions are not reproducible on the build platforms associated with this baseline: ";
144
 
145
    /**Flag to control output to standard out
146
     * @attribute
147
     */
148
    private boolean mAssocBuildPlatformsFlag = true;
149
 
150
    /**Warning message
151
     * @attribute
152
     */
153
    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: ";
154
 
155
    /**Flag to control output to standard out
156
     * @attribute
157
     */
158
    private boolean mNotInBaselineFlag = true;
159
 
160
    /**Warning message
161
     * @attribute
162
     */
163
    private static final String mDependent = "Warning. The following package versions are not reproducible as they are directly/indirectly dependent upon not reproducible package versions: ";
164
 
165
    /**Flag to control output to standard out
166
     * @attribute
167
     */
168
    private boolean mDependentFlag = true;
169
 
170
    /**Warning message
171
     * @attribute
172
     */
173
    private static final String mCircularDependency = "Warning. The following package versions are not reproducible as they have circular dependencies: ";
174
 
175
    /**Flag to control output to standard out
176
     * @attribute
177
     */
178
    private boolean mCircularDependencyFlag = true;
179
 
180
    /** String used to terminate lines
181
     * @attribute
182
     */
183
    private static final  String mlf = System.getProperty("line.separator");
184
 
185
    /** XML File Prefix
186
     */
187
    private static final String mXmlHeader = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>" + mlf;
188
 
189
    /**RippleEngine constructor
190
     * @param releaseManager  - Associated releaseManager instance
191
     * @param rtagId         - Release Identifier
192
     * @param isDaemon        - Mode of operation. False: Escrow, True: Daemon
193
     */
194
    public RippleEngine(ReleaseManager releaseManager, int rtagId, boolean isDaemon)
195
    {
7044 dpurdie 196
        mLogger.debug("RippleEngine rtag_id {} isDaemon {}", rtagId, isDaemon);
6914 dpurdie 197
        mReleaseManager = releaseManager;
198
        mBaseline = rtagId;
199
        mRtagId = rtagId;
200
        mDaemon = isDaemon;
201
        mReleaseManager.setDaemonMode(mDaemon);
202
    }
203
 
204
    /**
205
     * getRtagId
7044 dpurdie 206
     * @return The rtagId of the Release attached to this instance of the RippleEngine
6914 dpurdie 207
     */
208
    public int getRtagId()
209
    {
210
        return mRtagId;
211
    }
212
 
213
    /**Plan what is to be built
214
     * 	<br>Discards all build file content
215
     * 	<br>Generates new build file content
216
     * 
217
     * @param lastBuildActive 		- False. Daemon Mode. The last build was a dummy. 
218
     *                                This planning session may not result in a build
219
     *                              - True. Daemon Mode. The last build was not a dummy.
220
     *                                There is a very good chance that this planning session
221
     *                                will result in a build, so it is given priority to connect 
222
     *                                to the database.	
223
     */
224
    public void planRelease(final boolean lastBuildActive) throws SQLException, Exception
225
    {
7044 dpurdie 226
        mLogger.warn("planRelease mDaemon {}", mDaemon);
6914 dpurdie 227
 
7145 dpurdie 228
        //
229
        //  Diagnostic output
230
        //  Having issues with memory usage
231
        //
232
        long totalMem = Runtime.getRuntime().totalMemory();
233
        long freeMem = Runtime.getRuntime().freeMemory();
7176 dpurdie 234
        mLogger.warn("Memory Usage: Total: {}, Free: {}, Used: {}", totalMem, freeMem, totalMem - freeMem);
7145 dpurdie 235
 
6914 dpurdie 236
        mBuildCollection.clear();
237
        mPackageCollection.clear();
7082 dpurdie 238
        mPackageCollectionRipple.clear();
239
        mPackageCollectionTest.clear();
240
        mPackageCollectionWip.clear();
7163 dpurdie 241
        mPackageCollectionAll.clear();
6914 dpurdie 242
        mBuildOrder.clear();
243
        mEscrowRawData = "";
244
        mEscrowSetup = "";
245
        Phase phase = new Phase("Plan");
246
 
247
        // use finally block in planRelease to ensure the connection is released
248
        try
249
        {
250
            phase.setPhase("connectForPlanning");
251
            mReleaseManager.connectForPlanning(lastBuildActive);
252
 
253
            if ( mDaemon )
254
            {
255
                // claim the mutex
256
                mLogger.warn("planRelease claimMutex");
257
                phase.setPhase("claimMutex");
258
                mReleaseManager.claimMutex();
259
 
260
                // Populate the mBuildExclusionCollection
261
                //
262
                // Builds are either 'Directly excluded' or 'Indirectly excluded'
263
                // Direct excludes result from:
264
                //      User request
265
                //      Build failure
266
                //      Inability to build package
267
                // Indirectly excluded packages result from have a build dependency on a package
268
                // that is directly excluded.
269
                //  
270
                // In the following code we will extract from the Database all build exclusions
271
                // We will then add 'Relevant' entries to mBuildExclusionCollection
272
                // and delete, from the database those that are no longer relevant - ie indirectly excluded
273
                // items where the root cause is no longer in the set.
274
                phase.setPhase("mBuildExclusionCollection");
275
                mBuildExclusionCollection.clear();
276
                ArrayList<BuildExclusion> tempBuildExclusionCollection = new ArrayList<BuildExclusion>();
277
 
278
                mLogger.debug("planRelease queryBuildExclusions");
279
                mReleaseManager.queryBuildExclusions(tempBuildExclusionCollection, mBaseline);
280
 
281
                // only populate mBuildExclusionCollection with tempBuildExclusionCollection entries which have a relevant root_pv_id
282
                // The entry is relevant if:
283
                //     It is for a directly excluded package,other than a RippleStop
284
                //     It is for an indirectly excluded package AND the reason for exclusion still exists
285
                //
286
 
287
                for (Iterator<BuildExclusion> it = tempBuildExclusionCollection.iterator(); it.hasNext(); )
288
                {
289
                    BuildExclusion buildExclusion = it.next();
290
 
291
                    if ( buildExclusion.isRelevant(tempBuildExclusionCollection) )
292
                    {
293
                        mBuildExclusionCollection.add(buildExclusion);
294
                    }
295
                    else
296
                    {
297
                        // Remove the indirectly excluded entry as its root cause
298
                        // is no longer present.
299
                        buildExclusion.includeToBuild(mReleaseManager, mBaseline);
300
                    }
301
                }
302
            }
303
 
304
            //-----------------------------------------------------------------------
305
            //	Query package versions
306
            //
307
            phase.setPhase("queryPackageVersions");
308
            mLogger.debug("planRelease queryPackageVersions");
309
            mReleaseManager.queryPackageVersions(this, mPackageCollection, mBaseline);
7118 dpurdie 310
 
311
            phase.setPhase("queryPackageWips");
7082 dpurdie 312
            mReleaseManager.queryWips(this, mPackageCollectionWip, mBaseline);
313
            mReleaseManager.queryTest(this, mPackageCollectionTest, mBaseline);
314
            mReleaseManager.queryRipples(this, mPackageCollectionRipple, mBaseline);
7118 dpurdie 315
 
7082 dpurdie 316
            mPackageCollectionAll.addAll(mPackageCollection);
317
            mPackageCollectionAll.addAll(mPackageCollectionWip);
318
            mPackageCollectionAll.addAll(mPackageCollectionTest);
319
            mPackageCollectionAll.addAll(mPackageCollectionRipple);
320
 
321
            // Sort the collection by PVID
322
            //      Unit Test output order is known
323
            //      May assist in creating repeatable build orders
324
            //
325
            Collections.sort(mPackageCollectionAll, Package.SeqComparator);
6914 dpurdie 326
 
327
            //------------------------------------------------------------------------
328
            //    Process packages collected
329
            //    Determine and tag those we can't build
330
            phase.setPhase("processPackages");
331
            processPackages();
332
 
333
            //-----------------------------------------------------------------------
334
            //    At this point we have tagged all the packages that we cannot build
335
            //    Now we can determine what we are building
336
            phase.setPhase("planBuildOrder");
337
            mLogger.debug("planRelease process Remaining");
338
            planBuildOrder();
339
 
340
            //  Report excluded packages and the build plan
341
            //  This is being done with the MUTEX being held, but the 
342
            //  trade off is the cost of getting a connection.
343
            //
344
            if ( mDaemon )
345
            {
346
                phase.setPhase("Report Change");
347
                reportChange();
348
                phase.setPhase("Report Plan");            
349
                reportPlan();
350
            }
351
 
352
            //
353
            //	Generate the build Files
354
            //
355
            phase.setPhase("generateBuildFiles");
356
            generateBuildFiles();
357
        }
358
        finally
359
        {
360
            mLogger.debug("planRelease finally");
361
            // this block is executed regardless of what happens in the try block
362
            // even if an exception is thrown
363
            // ensure the SELECT FOR UPDATE is released
364
            try
365
            {
366
                if ( mDaemon )
367
                {
368
                    // attempt to release the SELECT FOR UPDATE through a commit
369
                    // a commit must be done in the normal case
370
                    // a commit may as well be done in the Exception case
371
                    // in the case of a SQLException indicating database connectivity has been lost
372
                    // having a go at the commit is superfluous
373
                    // as the SELECT FOR UPDATE will have been released upon disconnection
374
                    phase.setPhase("releaseMutex");
375
                    mReleaseManager.releaseMutex();
376
                }
377
            }
378
            finally
379
            {
380
                // ensure disconnect under all error conditions
381
                phase.setPhase("disconnectForPlanning");
382
                mReleaseManager.disconnectForPlanning(lastBuildActive);
383
            }
384
        }
385
 
7145 dpurdie 386
        //
387
        //  Attempt to release objects that have been created during the planning phase
388
        //
389
        mPackageCollection.clear();
390
        mPackageCollectionRipple.clear();
391
        mPackageCollectionTest.clear();
392
        mPackageCollectionWip.clear();
7163 dpurdie 393
        mPackageCollectionAll.clear();
7145 dpurdie 394
        mBuildOrder.clear();
395
 
7044 dpurdie 396
        mLogger.warn("planRelease mDaemon {} returned", mDaemon);
6914 dpurdie 397
        phase.setPhase("EndPlan");
398
    }
399
 
400
    /** Process packages that have been collected as a part of the plan
401
     * @param phase
402
     * @throws SQLException
403
     * @throws Exception
404
     */
405
    private void processPackages() throws SQLException, Exception {
406
 
407
        // Deal with test builds here as they may impact upon package attributes
7082 dpurdie 408
        //    eg: dependency collection and build standard differences
6914 dpurdie 409
        //    Note: Done before mPackageDependencyCollection is setup
410
        //
7123 dpurdie 411
        Phase phase = new Phase("processPackages");
6914 dpurdie 412
        if ( mDaemon )
413
        {
7082 dpurdie 414
            // Process test builds - they are in their own collection
7123 dpurdie 415
            phase.setPhase("TestBuilds");
7082 dpurdie 416
            for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
6914 dpurdie 417
            {
418
                Package p = it.next();
7176 dpurdie 419
                mLogger.debug("planRelease package test build {}", p.mAlias);
6914 dpurdie 420
 
7082 dpurdie 421
                //
422
                //    Cannot test build an SDK based package or a Pegged Package
423
                //        Remove the test build request from the database
424
                //        Send a warning email
425
                //
426
                if(p.mIsPegged || p.mIsSdk)
6914 dpurdie 427
                {
7088 dpurdie 428
                    String reason;
429
                    reason = (p.mIsPegged) ? "Pegged" : "SDK Based";
6914 dpurdie 430
 
7176 dpurdie 431
                    mLogger.warn("planRelease Daemon Instruction (testBuild) of {} package deleted: {}", reason, p.mAlias);
7082 dpurdie 432
                    mReleaseManager.markDaemonInstCompleted( p.mTestBuildInstruction );
433
                    emailRejectedDaemonInstruction("Cannot 'Test Build' a " + reason + " package",p);
434
                }
6914 dpurdie 435
 
7088 dpurdie 436
                // force patch for test build numbering
437
                p.mDirectlyPlanned = true;
438
                p.mChangeType.setPatch();
439
                p.mRequiresSourceControlInteraction = false;
440
                p.mBuildReason = BuildReason.Test;
441
                p.mIndirectlyPlanned = true;
6914 dpurdie 442
            }
443
        }
444
 
445
        // Set up mPackageDependencyCollection on each package
446
        //    Examine the dependencies by alias and convert this to a 'package' selected from the released package set
7123 dpurdie 447
        phase.setPhase("setPackageDependencyCollection");
7082 dpurdie 448
        mLogger.debug("planRelease setup setPackageDependencyCollection");
449
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 450
        {
451
            Package p = it.next();
452
 
7163 dpurdie 453
            for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 454
            {
7163 dpurdie 455
                PkgDependency depEntry = it2.next();
456
                Package dependency = findPackage(depEntry.alias);
457
                depEntry.pkg = dependency;
6914 dpurdie 458
            }
7082 dpurdie 459
        }    
6914 dpurdie 460
 
7082 dpurdie 461
        // Detect and deal with circular dependencies
462
        // Examine all packages under consideration
463
        //
7123 dpurdie 464
        phase.setPhase("Detect Circular Dependencies");
6914 dpurdie 465
        mLogger.debug("planRelease deal with circular dependencies");
7082 dpurdie 466
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 467
        {
468
            Package p = it.next();
469
 
7082 dpurdie 470
            if ( p.hasCircularDependency( mPackageCollectionAll ) )
6914 dpurdie 471
            {
7044 dpurdie 472
                mLogger.info("planRelease circular dependency detected {}", p.mAlias);
6914 dpurdie 473
 
474
                //  Force this package to be marked as having a circular dependency - even if its been excluded
475
                p.mBuildFile = 0;
476
 
7082 dpurdie 477
                // Exclude the package
6914 dpurdie 478
                // max 50 chars
7082 dpurdie 479
                rippleBuildExclude(p, p.mId, "Package has circular dependency", -6);
6914 dpurdie 480
 
481
                // take the package out of the build
482
                standardOut(mCircularDependency, p.mAlias, mCircularDependencyFlag);
483
                mCircularDependencyFlag = false;
484
            }
485
        }
486
 
487
        // Scan for packages with missing dependencies
488
        //    ie: The dependent package is not in the package Collection
7123 dpurdie 489
        phase.setPhase("Scan missing dpendencies");
6914 dpurdie 490
        mLogger.debug("planRelease use the fully built mPackageDependencyCollection");
7082 dpurdie 491
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 492
        {
493
            Package p = it.next();
494
 
495
            if ( mDaemon )
496
            {
497
                //  Daemon Mode Only
498
                //  Not interested in the dependencies of a pegged package or a package provided from an SDK.
499
                //  Such packages will be deemed to not have missing dependencies
500
                if (p.mIsPegged || p.mIsSdk)
501
                {
502
                    continue;
503
                }
504
            }
505
 
7163 dpurdie 506
            for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 507
            {
7163 dpurdie 508
                PkgDependency depEntry = it2.next();
509
                Package dependency = findPackage(depEntry.alias);
6914 dpurdie 510
 
511
                if (dependency == ReleaseManager.NULL_PACKAGE)
512
                {
7163 dpurdie 513
                    mLogger.info("planRelease dependency is not in the baseline {}", depEntry);
7088 dpurdie 514
                    // Exclude the package
6914 dpurdie 515
                    // max 50 chars
7082 dpurdie 516
                    rippleBuildExclude(p, p.mId, "Package build dependency not in the release", -4);
6914 dpurdie 517
 
518
                    // take the package out of the build
519
                    standardOut(mNotInBaseline, p.mAlias, mNotInBaselineFlag);
520
                    mNotInBaselineFlag = false;
521
                    break;
522
                }
523
            }
524
        }
525
 
7082 dpurdie 526
        // Detect packages with no build standard and exclude them from the build
7123 dpurdie 527
        phase.setPhase("Scan not reproducible");
6914 dpurdie 528
        mLogger.debug("planRelease process packages which are not reproducible");
7082 dpurdie 529
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 530
        {
531
            Package p = it.next();
532
 
533
            if (p.mBuildFile == 0)
534
            {
535
                if ( mDaemon )
536
                {
537
                    //  Daemon Mode Only
538
                    //  Not interested in the reproducibility of a pegged package or a package provided from an SDK.
539
                    //  Such packages will be deemed to be reproducible - but out side of this release
540
                    if (p.mIsPegged || p.mIsSdk)
541
                    {
542
                        continue;
543
                    }
544
                }
545
 
7082 dpurdie 546
                // Does the package have a build standard. If not then we can't reproduce it.
547
                // Escrow - Assume the package is provided
548
                // Daemon - Exclude this package, but not its consumers. If the package is available then we can use it.
6914 dpurdie 549
                if (!p.isReproducible())
550
                {
7044 dpurdie 551
                    mLogger.info("planRelease package not reproducible {}" ,p.mName);
7088 dpurdie 552
 
553
                    // Exclude the package
6914 dpurdie 554
                    // max 50 chars
7082 dpurdie 555
                    rippleBuildExclude(p, p.mId, "Package has no build environment", -1);
6914 dpurdie 556
 
557
                    // package is not reproducible, discard
558
                    standardOut(mAnyBuildPlatforms, p.mAlias, mAnyBuildPlatformsFlag);
559
                    mAnyBuildPlatformsFlag = false;
560
                }
561
            }
562
        }
563
 
7082 dpurdie 564
        //    Process packages which are not reproducible on the configured set of build machines.
6914 dpurdie 565
        //
566
        //    Test each package and determine if the package contains a buildStandard that
567
        //    can be processed by one of the machines in the build set
568
        //
569
        //    ie: Package: Win32:Production and we have a BM with a class of 'Win32'
570
        //
571
        //    Only exclude the failing package and not its dependents
572
        //    May be legitimate in the release
573
        //
7123 dpurdie 574
        phase.setPhase("Scan not reproducible2");
6914 dpurdie 575
        mLogger.debug("planRelease process packages which are not reproducible2");
7082 dpurdie 576
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 577
        {
578
            Package p = it.next();
579
 
580
            if (p.mBuildFile == 0)
581
            {
582
                if ( mDaemon )
583
                {
584
                    //  Daemon Mode Only
585
                    //  Not interested in the reproducibility of a pegged package or a package provided from an SDK.
586
                    //  Such packages will be deemed to be reproducible - but out side of this release
587
                    if (p.mIsPegged || p.mIsSdk)
588
                    {
589
                        continue;
590
                    }
591
                }
592
 
593
                // package has yet to be processed
594
                // assume it does not need to be reproduced for this baseline
595
                //
596
                //    For each machineClass in the buildset
597
                boolean reproduce = false;
598
 
599
                for (Iterator<String> it2 = mReleaseManager.mReleaseConfigCollection.mMachineClasses.iterator(); it2.hasNext(); )
600
                {
601
                    String machineClass = it2.next();
602
 
603
                    if ( p.canBeBuildby(machineClass))
604
                    {
605
                        reproduce = true;
7044 dpurdie 606
                        mLogger.info("planRelease package built on {} {}", machineClass, p.mAlias );
6914 dpurdie 607
                        break;
608
                    }
609
                }
610
 
611
                if ( !reproduce )
612
                {
7044 dpurdie 613
                    mLogger.info("planRelease package not reproducible on the build platforms configured for this baseline {}", p.mName);
6914 dpurdie 614
 
7082 dpurdie 615
                    // Exclude the package
616
                    // max 50 chars
617
                    rippleBuildExclude(p, p.mId, "Package not built for configured platforms", -2);
6914 dpurdie 618
 
619
                    // package is not reproducible on the build platforms configured for this baseline, discard
620
                    standardOut(mAssocBuildPlatforms, p.mAlias, mAssocBuildPlatformsFlag);
621
                    mAssocBuildPlatformsFlag = false;
622
                }
623
            }
624
        }      
625
 
7082 dpurdie 626
        if (mDaemon )
6914 dpurdie 627
        {
628
 
629
            //  Daemon Mode Only
630
            //  Process packages which need to be ripple built
7123 dpurdie 631
            phase.setPhase("Scan for ripples");
632
            mLogger.debug("Process packages which need to be ripple built");
6914 dpurdie 633
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
634
            {
635
                Package p = it.next();
636
 
637
                if (p.mBuildFile == 0)
638
                {
639
                    //  Not interested in a pegged package or a package provided from an SDK.
640
                    //  Such packages are not rippled
641
                    if (p.mIsPegged || p.mIsSdk)
642
                    {
643
                        continue;
644
                    }
645
 
7082 dpurdie 646
                    //    Examine this packages dependencies
647
                    //    If one of them does not exist in the 'official release' set then
648
                    //    the package needs to be built against the official release set
649
                    //    and we can't build any of its dependent packages
7163 dpurdie 650
                    Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator();
651
                    while ( it2.hasNext() )
6914 dpurdie 652
                    {
7163 dpurdie 653
                        PkgDependency depEntry = it2.next();
7088 dpurdie 654
 
7163 dpurdie 655
                        if ( !depEntry.pkg.mAdvisoryRipple )
6914 dpurdie 656
                        {
7082 dpurdie 657
                            // not advisory, ie: has ripple build impact
7163 dpurdie 658
                            if ( !isInRelease(depEntry.pvId) )
6914 dpurdie 659
                            {
7082 dpurdie 660
                                // the package is out of date
661
                                // exclude all dependent package versions
662
                                mLogger.info("planRelease package out of date {}", p.mName);
663
                                p.mBuildReason = BuildReason.Ripple;
664
                                rippleIndirectlyPlanned(p);
665
 
666
                                //  This package needs to be rippled
667
                                //  If this package has a rippleStop marker of 's', then we cannot
668
                                //  build this package at the moment.
669
                                //  Packages that depend on this package have been excluded
670
                                //  We need to exclude this one too
671
                                //
672
                                if (p.mRippleStop == 's' || p.mRippleStop == 'w') 
6914 dpurdie 673
                                {
7088 dpurdie 674
                                    // Package marked as a rippleStop
675
                                    // max 50 chars
676
                                    rippleBuildExclude(p, -2, "Ripple Required." + " Waiting for user", -11);
6914 dpurdie 677
 
7088 dpurdie 678
                                    if (p.mRippleStop == 's' ) {
7164 dpurdie 679
 
7088 dpurdie 680
                                        // Need to flag to users that the package build is waiting user action
681
                                        mLogger.info("planRelease Ripple Required. Stopped by flag {}", p.mName);
682
                                        mReleaseManager.setRippleStopWait(mRtagId,p);
7164 dpurdie 683
                                        emailRippleStop(p);
6914 dpurdie 684
                                    }
7164 dpurdie 685
 
6914 dpurdie 686
                                }
7082 dpurdie 687
 
688
                                break;
6914 dpurdie 689
                            }
690
                        }
691
                    }
692
                }
693
            }
694
 
695
            //  Daemon Mode Only
696
            //  Process packages which do not exist in the archive
697
            //  For unit test purposes, assume all packages exist in the archive if released
698
            mLogger.debug("planRelease process packages which do not exist in the archive");
7123 dpurdie 699
            phase.setPhase("Scan dpkg_archive");
7046 dpurdie 700
            if ( mReleaseManager.mUseDatabase )
6914 dpurdie 701
            {
702
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
703
                {
704
                    Package p = it.next();
705
 
706
                    if (p.mBuildFile == 0)
707
                    {
708
                        // package has yet to be processed
709
                        if (!p.mDirectlyPlanned && !p.mIndirectlyPlanned && p.mForcedRippleInstruction == 0)
710
                        {
711
                            // check package version archive existence
712
                            if (!p.existsInDpkgArchive())
713
                            {
714
                                if (! p.mIsBuildable)
715
                                {
716
                                    //  Package does not exist in dpkg_archive and it has been flagged as unbuildable
717
                                    //  This may be because is Unbuildable or Manually built
7044 dpurdie 718
                                    mLogger.info("planRelease Unbuildable package not found in archive {}", p.mName);
7088 dpurdie 719
                                    // Exclude the package
6914 dpurdie 720
                                    // max 50 chars
7082 dpurdie 721
                                    rippleBuildExclude(p, p.mId, "Unbuildable" + " package not found in archive", -10);
6914 dpurdie 722
 
723
                                }
724
                                //  Not interested in a pegged package or a package provided from an SDK.
725
                                //  Such packages are not rippled
726
                                else if (p.mIsPegged || p.mIsSdk)
727
                                {
728
                                    String reason;
729
                                    reason = (p.mIsPegged) ? "Pegged" : "SDK";
730
 
731
                                    //  Pegged packages or packages provided from an SDK MUST exist in dpkg_archive
732
                                    //  They will not be built within the context of this release. It is the responsibility
733
                                    //  of another release to build them.
7044 dpurdie 734
                                    mLogger.info("planRelease {} package not found in archive {}", reason, p.mName);
7088 dpurdie 735
                                    // Exclude the package
6914 dpurdie 736
                                    // max 50 chars
7082 dpurdie 737
                                    rippleBuildExclude(p, p.mId, reason + " package not found in archive", -7);
6914 dpurdie 738
                                }
739
                                else if (p.mForcedRippleInstruction == 0)
740
                                {
741
                                    //  [JATS-331] Unable to rebuild package with Advisory Ripple dependencies
742
                                    //    Examine this packages dependencies
743
                                    //    If one of them does not exist in the 'official release' set then
744
                                    //    the package cannot be rebuilt in this release.
7163 dpurdie 745
                                    for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator() ; it2.hasNext() ;)
6914 dpurdie 746
                                    {
7163 dpurdie 747
                                        PkgDependency dpvId = it2.next();
748
                                        if ( !isInRelease(dpvId.pvId) )
6914 dpurdie 749
                                        {
750
                                            // This package cannot be rebuilt as one of its dependents is NOT in this release
751
                                            // exclude all dependent package versions
752
 
7044 dpurdie 753
                                            mLogger.info("planRelease package not found in archive. Cannot be rebuilt due to {}", p.mName);
7088 dpurdie 754
                                            // Exclude the package
6914 dpurdie 755
                                            // max 50 chars
7082 dpurdie 756
                                            rippleBuildExclude(p, p.mId, "Package cannot be rebuilt in this release", -4);
6914 dpurdie 757
                                            break;
758
                                        }
759
                                    }
760
 
761
                                    //  The package has not been excluded from the build
762
                                    if (p.mBuildFile == 0)
763
                                    {
7044 dpurdie 764
                                        mLogger.info("planRelease package not found in archive {}", p.mName);
6914 dpurdie 765
                                        // DEVI 47395 the cause of this build is not WIP or ripple induced,
766
                                        // it simply does not exist in the archive (has been removed)
767
                                        // prevent source control interaction
768
                                        p.mRequiresSourceControlInteraction = false;
769
                                        p.mBuildReason = BuildReason.Restore;
770
                                        rippleIndirectlyPlanned(p);
771
                                    }
772
                                }
773
                            }
774
                        }
775
                    }
776
                }
777
            }
778
 
779
            //  Daemon Mode Only
7082 dpurdie 780
            //  Detect bad forced ripples requests and reject them
6914 dpurdie 781
            mLogger.debug("planRelease process forced ripples");
7123 dpurdie 782
            phase.setPhase("Test bad ripple requests");
7082 dpurdie 783
            for (Iterator<Package> it = mPackageCollectionRipple.iterator(); it.hasNext(); )
6914 dpurdie 784
            {
785
                Package p = it.next();
786
 
787
                if (p.mBuildFile == 0)
788
                {
7082 dpurdie 789
                    //
790
                    //    Cannot force a ripple on an SDK based package or a Pegged Package
791
                    //        Remove the daemon instruction from the database
792
                    //        Send a warning email
793
                    //
794
                    if(p.mIsPegged || p.mIsSdk)
6914 dpurdie 795
                    {
7082 dpurdie 796
                        String reason;
797
                        reason = (p.mIsPegged) ? "Pegged" : "SDK Based";
6914 dpurdie 798
 
7176 dpurdie 799
                        mLogger.warn("planRelease Daemon Instruction of {} package deleted: {}", reason, p.mName);
7088 dpurdie 800
                        mReleaseManager.markDaemonInstCompleted( p.mForcedRippleInstruction );
801
                        emailRejectedDaemonInstruction("Cannot 'Ripple' a " + reason + " package",p);
6914 dpurdie 802
 
7088 dpurdie 803
                        p.mBuildFile = -8; 
6914 dpurdie 804
                    }
805
                }
806
            }
807
 
808
            //  Daemon Mode Only
809
            //  Mark Pegged and SDK packages as not to be built
7082 dpurdie 810
            //  Mark RippleStoped packages as not to be build
6914 dpurdie 811
            //  Have previously detected conflicts between pegged/sdk packages and daemon instructions
812
            //
813
            mLogger.debug("planRelease remove pegged and SDK packages from the build set");
7123 dpurdie 814
            phase.setPhase("Remove Pegged and SDKs");
6914 dpurdie 815
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
816
            {
817
                Package p = it.next();
818
 
819
                if (p.mBuildFile == 0)
820
                {
7082 dpurdie 821
                    String reason = null;
822
 
823
                    //  Not interested in a pegged package or a package provided from an SDK or packages with an active RippleStop
6914 dpurdie 824
                    //  Such packages are not built
7088 dpurdie 825
                    if (p.mIsPegged ) {
826
                        reason = "Pegged";
6914 dpurdie 827
                        p.mBuildFile = -8;
7082 dpurdie 828
                    } else if (p.mIsSdk) {
829
                        reason = "SDK";
830
                        p.mBuildFile = -8;
831
                    } else if (p.mRippleStop == 's' || p.mRippleStop == 'w') {
832
                        reason = "RippleStop";
833
                        p.mBuildFile = -11;
6914 dpurdie 834
                    }
7082 dpurdie 835
 
836
                    if (reason != null)
837
                    {
838
                        mLogger.info("planRelease {} not built in this release {}", reason, p.mName);
839
                    }
6914 dpurdie 840
                }
841
            }
842
        }
843
        else
844
        {
845
            // escrow reporting only
846
            // Report packages that are not reproducible
847
            //
848
            //  Note: I don't believe this code can be executed
849
            //        The -3 is only set in daemon mode
850
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
851
            {
852
                Package p = it.next();
853
 
854
                if (p.mBuildFile == -3)
855
                {
856
                    standardOut(mDependent, p.mAlias, mDependentFlag);
857
                    mDependentFlag = false;
858
                }
859
            }
860
        }
7123 dpurdie 861
        phase.setPhase("End");
6914 dpurdie 862
    }
7082 dpurdie 863
 
6914 dpurdie 864
    /** Plan the build order.
7082 dpurdie 865
         *  Assumes that a great deal of work has been done.
866
         *  This is a stand alone method to contain the work
867
         *  
868
         * @throws Exception
869
         * @throws SQLException
870
         */
871
        private void planBuildOrder() throws Exception, SQLException 
872
        {
873
 
7133 dpurdie 874
        /**
875
         * Current status
876
         *  basicPlan - time to complete current ripple
877
         *  FullPlan - Include all WIPS/RIPPLES into the release set
878
         *  
879
         *  If the full Plan does NOT extend the time of the basicPLan by 20% then use the full plan
880
         *  otherwise complete the current ripple and the include WIPs/RIPPLEs\
881
         *  
882
         *  TEST requests will be done first.
883
         *
884
         */
885
 
7082 dpurdie 886
            // Process remaining packages which are need to be reproduced for this baseline.
887
            //    Determine the build file for each package
888
            //    For daemon builds:
889
            //      Determine the next package that can be built now
890
            //          Sounds simple - doesn't it
891
            //      Set its mBuildNumber to 1, all remaining reproducible packages to 2
892
            //    For escrow builds:
893
            //      Determine the package versions that can be built in the build iteration
894
            //      Set their mBuildNumber to the build iteration
895
            //      Increment the build iteration and repeat until all package versions 
896
            //      that need to be reproduced have been assigned a build iteration        
897
 
898
            //
899
            //  Generate a plan for the packages that are in the current release
900
            //  These may be the result of a ripple going through the system 
901
            //  or a rebuild of a missing package or the result of a merge.
902
            //
903
            //  This will provide our basic plan, before we consider adding new packages to the
904
            //  mix, such as those from user WIPS and RIPPLE requests.
905
            //  
906
            PlanResults basicPlan = planCollection("Basic", mPackageCollection, true);
907
 
908
            //  Have not considered any of the WIP or RIPPLE packages
909
            //  If any of them are in the basic plan, then we can ignore them as we will build them
910
            //  when we build the basic plan
911
            //
912
            //  Determine a set of packages that will not be included if we build the basic plan
913
            //
914
            //  At the moment - lets assume there are none
915
            //  What do we do ?
916
            //      Select the first request
917
            //      Replace the package in the released collection
918
            //      Run the plan algorithm
919
            //      Restore the release collection
920
            //
921
            if ( mDaemon )
922
            {
923
                //
924
                //  Need to consider the TEST requests
925
                //      - Valid requests will be placed first on the build order
926
                //
927
                mBuildOrder.clear();
928
                for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
929
                {
930
                    Package p = it.next();
931
                    if (p.mBuildFile >= 0)
932
                    {
7133 dpurdie 933
                        mBuildOrder.add( new PlannedPackage(p) );
7082 dpurdie 934
                    }
935
                }
936
 
7169 dpurdie 937
                //
938
                //  Examine Plan control
939
                //      DropPlan - do not use the basic plan. This is a one-shot request
940
                //      Threshold == 0. Always use a full plan
941
                if (mPlanControl.mDumpPlan || mPlanControl.mThreshold == 0)
942
                {
943
                    mLogger.warn("Drop basicPlan and use fullPlan");
944
                    basicPlan.planTime = 0;
945
                    basicPlan.planCollection.clear();
946
 
947
                    //  Always reset the one-shot request to drop the current plan
948
                    mReleaseManager.resetPlanControl(mBaseline);
949
                }
950
 
7082 dpurdie 951
                //  First attempt
952
                //  Insert all the WIPs and RIPPLES into the buildset. 
953
                //  Generate a plan and see how much the time is extended.
954
                //
955
                //  Don't modify mPackageCollection, although data in the 'Package' in the underlying packages may change
956
 
957
                PlanResults fullPlan = postRipplePlan("Full", basicPlan, true);
958
 
959
                //  Decide with plan to use
960
                //  At the moment we have, at most two.
961
                //      - (basic) Current Release ripples
962
                //      - (full) Current Release + All WIPS and RIPPLES
963
                //
7169 dpurdie 964
                //  If we have both then use the planContol threshold to determine which plan to use
965
                //  The threshold number is taken as a percent by which the fullPlan Time impacts basicPlan time
966
                //  before the fullPlan will be rejected.
967
                //  ie: threshold = 20.  If fullPlan is  20% longer that the basicPlan, then use the basicPlan then a modified fullPlan (Cautious)
968
                //  ie: threshold = 100. If fullPlan is 100% longer that the basicPlan, then use the basicPlan then a modified fullPlan (Aggressive)
969
                //
970
                //  A modified fullPlan is one without the natural ripples as these will have been done in the basicPlan
971
                //
7082 dpurdie 972
                //  Add the planned packages into the buildOrder
973
 
974
                if( !basicPlan.planCollection.isEmpty() && !fullPlan.planCollection.isEmpty() )
975
                {
7169 dpurdie 976
                    //  Calculate the build impact as a percentage
977
                    //  The impact of the fullPlan over the basicPlan
7099 dpurdie 978
                    //
7169 dpurdie 979
                    int buildImpact = 0;
980
                    if (fullPlan.planTime != basicPlan.planTime &&  basicPlan.planTime  != 0) {
981
                        buildImpact = ((fullPlan.planTime - basicPlan.planTime) * 100) / (basicPlan.planTime);
7099 dpurdie 982
                    }
7176 dpurdie 983
                    mLogger.warn("Two plan selection: Basic:{} Full:{}, Impact:{}% Threshold:{}% Exceeded: {}", basicPlan.planTime,fullPlan.planTime, buildImpact, mPlanControl.mThreshold, buildImpact >= mPlanControl.mThreshold);
7169 dpurdie 984
 
985
                    if ( buildImpact >= mPlanControl.mThreshold )
7082 dpurdie 986
                    {
7169 dpurdie 987
                        //  BuildImpact too high
7082 dpurdie 988
                        //  Use the basic plan FOLLOWED by a plan that does not include
989
                        //      Ripples done by the basic plan
990
                        //      WIPs/RIPPLES done in the course of doing the basic plan
7176 dpurdie 991
                        mLogger.warn("Use basic plan, then modified full plan");
7082 dpurdie 992
                        mBuildOrder.addAll(basicPlan.planCollection);
7147 dpurdie 993
 
7082 dpurdie 994
                        fullPlan = postRipplePlan("Full-Ripples", basicPlan, false);
995
                        mBuildOrder.addAll(fullPlan.planCollection);
996
 
997
                    } else {
998
                        //  Use the full plan
7176 dpurdie 999
                        mLogger.warn("Use full plan");
7082 dpurdie 1000
                        mBuildOrder.addAll(fullPlan.planCollection);
1001
                    }
1002
                } else if (!basicPlan.planCollection.isEmpty() ) {
1003
                    // Use the basic plan
7176 dpurdie 1004
                    mLogger.warn("Use basic plan");
7082 dpurdie 1005
                    mBuildOrder.addAll(basicPlan.planCollection);
1006
 
1007
                } else if ( !fullPlan.planCollection.isEmpty() ) {
1008
                    // Use the full plan
7176 dpurdie 1009
                    mLogger.warn("Use full plan");
7082 dpurdie 1010
                    mBuildOrder.addAll(fullPlan.planCollection);
1011
 
1012
                } else {
1013
                    // Do not have a plan
1014
                    // May have tests requests
7176 dpurdie 1015
                    mLogger.warn("Use NO plan");
7082 dpurdie 1016
                }
1017
 
1018
                //
7099 dpurdie 1019
                //  Now have a build order
1020
                //  Allocate new version numbers
1021
                //      Examine packages with a buidLevel of zero
1022
                //  If we fail all of them then we can't build anything
1023
                //
7176 dpurdie 1024
                mLogger.warn("Determine new version numbers");
7082 dpurdie 1025
                Package build = ReleaseManager.NULL_PACKAGE;
7099 dpurdie 1026
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1027
                {
1028
                    PlannedPackage pkg = it.next();
1029
                    if (pkg.mBuildLevel != 0)
1030
                    {
1031
                        continue;
1032
                    }
1033
 
1034
                    //
1035
                    //  Attempt to allocate a new version number
1036
                    //  If we can't generate a new version number, then this is considered to be a build failure
1037
                    //  The package will be excluded and the user will be emailed
1038
                    //
1039
                    Package p = pkg.mPkg;
1040
 
1041
                    int pvApplied = p.applyPV(mReleaseManager);
1042
 
1043
                    if ( pvApplied == 0)
1044
                    {
1045
                        build = p;
1046
                        break;
1047
                    }
1048
                    else if ( pvApplied == 1 )
1049
                    {
1050
                        // max 50 chars
1051
                        rippleBuildExclude(p, p.mId, "Package has non standard versioning", -12);
1052
                    }
1053
                    else if ( pvApplied == 2 )
1054
                    {
1055
                        // max 50 chars
1056
                        rippleBuildExclude(p, p.mId, "Package has reached ripple field limitations", -12);
1057
                    }
1058
                    else if ( pvApplied == 3 )
1059
                    {
1060
                        // max 50 chars
1061
                        rippleBuildExclude(p, p.mId, "Package has invalid change type", -12);
1062
                    }
1063
                    else
1064
                    {
1065
                        // max 50 chars
1066
                        // Bad programming - should not get here
1067
                        rippleBuildExclude(p, p.mId, "Unable to calculate next version", -12);
1068
                    }
1069
                }
1070
 
1071
 
1072
                //  Now have an mBuildOrder
1073
                //  Mark the selected package in the build order as the one to be built
1074
                //  May need to process its it a bit more
1075
                //  
7107 dpurdie 1076
                if ( build != ReleaseManager.NULL_PACKAGE)
1077
                {
7082 dpurdie 1078
                    build.mBuildFile = 1;
1079
 
1080
                    if ( build.mForcedRippleInstruction > 0 )
1081
                    {
1082
                        mReleaseManager.markDaemonInstCompleted( build.mForcedRippleInstruction );
1083
                    }
1084
 
1085
                    if ( build.mTestBuildInstruction > 0 )
1086
                    {
1087
                        mReleaseManager.markDaemonInstInProgress( build.mTestBuildInstruction );
1088
                    }
1089
 
1090
                    //  Now that we know which package we are building
1091
                    //      Set the previously calculated nextVersion as the packages version number
1092
                    //      Claim the version number to prevent other builds from using it. Even if doing a test build
1093
                    //
7118 dpurdie 1094
                    mLogger.debug("Update mVersion: {}", build);
7082 dpurdie 1095
                    if (build.mNextVersion != null)
1096
                    {
1097
                        mReleaseManager.claimVersion(build.mPid, build.mNextVersion + build.mExtension, mBaseline);
1098
                        build.mVersion = build.mNextVersion;
7176 dpurdie 1099
                        mLogger.warn("Update mVersion: {} to {}", build, build.mVersion);
7082 dpurdie 1100
                    }
1101
 
7107 dpurdie 1102
                    //
1103
                    //  Ensure that the package we are about to build is present in the mPackageCollection as its
1104
                    //  this list that is used to generate the build.xml file - that may be a bad way to do it , but ...
1105
                    //
1106
                    //  Note: Can't really modify others as they will be used as dependencies
1107
                    //
1108
                    Package pEntry = findPackage(build.mAlias);
1109
                    if ( pEntry != ReleaseManager.NULL_PACKAGE)
7082 dpurdie 1110
                    {
7107 dpurdie 1111
                        mPackageCollection.set(mReleaseManager.findPackageLastIndex, build);
1112
                        build.mIsNotReleased = false;
1113
                    } else {
1114
                        mPackageCollection.add(build);
1115
                        build.mIsNotReleased = false;
7082 dpurdie 1116
                    }
1117
                }
7107 dpurdie 1118
 
7082 dpurdie 1119
                //
1120
                //  Report packages that are indirectly excluded
7145 dpurdie 1121
                //  ie: They will not be built because one, or more, of their dependents is not buildable
7082 dpurdie 1122
                //
7163 dpurdie 1123
                mLogger.warn("planBuildOrder process packages which are not ripple buildable");
7082 dpurdie 1124
 
7129 dpurdie 1125
                Package.resetCircularDependency (mPackageCollection);
7176 dpurdie 1126
                for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
1127
                {
1128
                    BuildExclusion be = it.next();
1129
 
1130
                    //  Only process direct exclusions
1131
                    //      mBuildExclusionCollection is at this point based on relevant (direct and indirect) 
1132
                    //      excluded pv's in the database
1133
                    //
1134
                    if ( be.isARootCause() )
1135
                    {
7082 dpurdie 1136
 
7176 dpurdie 1137
                        for (Iterator<Package> it1 = mPackageCollectionAll.iterator(); it1.hasNext(); )
1138
                        {
1139
                            Package p = it1.next();
7082 dpurdie 1140
 
7176 dpurdie 1141
                            // TODO - Do we need && p.mTestBuildInstruction == 0 && p.mForcedRippleInstruction == 0
7082 dpurdie 1142
 
7176 dpurdie 1143
                            if ( be.compare(p.mId)  )
1144
                            {
1145
                                // package is not reproducible, discard it and its consumers
1146
                                //
1147
                                mLogger.warn("Excluded Package {}, {}", p, be );                                     
1148
 
1149
                                ArrayList<Package> toExclude = new ArrayList<Package>();
1150
                                toExclude.addAll(usedByAnyPackages(p, mPackageCollectionAll ));
1151
 
1152
                                //  Process packages that we need to exclude indirectly
1153
                                //
1154
                                while ( ! toExclude.isEmpty())
1155
                                {
1156
                                    Package pkg = toExclude.remove(0);
1157
 
1158
                                    // If this package has not been excluded (for whatever reason), than add it
1159
                                    boolean found = false;
1160
                                    for (Iterator<BuildExclusion> it2 = mBuildExclusionCollection.iterator(); it2.hasNext(); )
1161
                                    {
1162
                                        BuildExclusion buildExclusion = it2.next();
1163
                                        if (buildExclusion.compare(pkg.mId) )
1164
                                        {
1165
                                            found = true;
1166
                                            if  ( buildExclusion.isImported() )
1167
                                            {
1168
                                                // An exclusion for this package already exists
1169
                                                // If it was 'imported' from the database then 
1170
                                                // mark it as processed so that it will be persisted
1171
                                                //
1172
                                                // Otherwise it will be a new one
1173
                                                //
1174
                                                buildExclusion.setProcessed();
1175
                                            }
1176
                                            break;
1177
                                        }
1178
                                    }
1179
 
1180
                                    if (!found)
1181
                                    {
1182
                                        BuildExclusion buildExclusion = new BuildExclusion(pkg.mId, p.mId, null, p.mTestBuildInstruction);
1183
                                        it.add(buildExclusion);
1184
                                        mLogger.warn("Indirectly Excluded Package {}", pkg.mAlias);
1185
                                        pkg.mBuildFile = -5; 
1186
                                    }
1187
 
1188
                                    // Determine all packages that use this excluded package
1189
                                    // THAT WE HAVE NOT ALREADY PROCESSED - circular dependencies are a killer
1190
                                    ArrayList<Package> usedBy = usedByAnyPackages(pkg, mPackageCollectionAll );
1191
                                    for (Iterator<Package> it2 = usedBy.iterator(); it2.hasNext(); )
1192
                                    {
1193
                                        Package uPkg = it2.next();
1194
                                        if (!uPkg.mCheckedCircularDependency)
1195
                                        {
1196
                                            toExclude.add(uPkg);
1197
                                            uPkg.mCheckedCircularDependency = true;
1198
                                        }
1199
                                    }
1200
 
1201
                                }
1202
                            }
1203
                        }
1204
                    }
1205
                }
7099 dpurdie 1206
 
1207
                 //
7163 dpurdie 1208
                 // Handle daemon Instructions that cannot be satisfied
1209
                 // Need to be rejected to prevent continuous planning
1210
                 //
1211
                 mLogger.warn("Handle unsatisfied Daemon Instructions");
1212
                 reportUnsatisfiedDaemonInstructions();
1213
 
1214
                 //
7099 dpurdie 1215
                 //  Examine the build order and 'delete' entries with a -ve mBuildFile
1216
                 //  These will be the product of pvApply errors and the packages that depend on them
7147 dpurdie 1217
                 //
7163 dpurdie 1218
                 //  Insert a dummy marker between build plans
1219
                 //     Detect the index of the insertion point
7147 dpurdie 1220
                 //
1221
                 int lastLevel = -1;
1222
                 int listIndex = 0;
1223
                 int insertMarker = -1;
1224
                 for (Iterator<PlannedPackage> it = mBuildOrder.listIterator(); it.hasNext(); )
7099 dpurdie 1225
                 {
1226
                     PlannedPackage pkg = it.next();
1227
                     if (pkg.mPkg.mBuildFile < 0)
1228
                     {
1229
                         it.remove();
7176 dpurdie 1230
                         mLogger.warn("Purge mBuildOrder {}", pkg.mPkg);
7147 dpurdie 1231
                         continue;
7099 dpurdie 1232
                     }
7147 dpurdie 1233
 
1234
                     if ( pkg.mBuildLevel < lastLevel && insertMarker < 0)
1235
                     {
1236
                         insertMarker = listIndex;
1237
                     }
1238
                     listIndex++;
1239
                     lastLevel = pkg.mBuildLevel;
7099 dpurdie 1240
                 }
7147 dpurdie 1241
 
1242
                 if (insertMarker > 0)
1243
                 {
1244
                     PlannedPackage pp = new PlannedPackage( new Package() );
1245
                     pp.mBuildLevel = -1;
1246
                     mBuildOrder.add(insertMarker, pp);                     
1247
                 }
7082 dpurdie 1248
 
1249
                //
1250
                //  To fit in with the old algorithm ( ie: could be improved )
1251
                //  Insert marks into all packages
1252
                //  Not sure exactly why - Its used in the generation of the ant build file
1253
                //                     Want to set mNoBuildReason, mBuildFile
1254
                //
1255
                //      Package we have selected to build: 0     , 1
1256
                //      Package we could have built      : 0     , 2
1257
                //      Packages we can't build          : reason, 3
1258
                //      Packages that are OK             : 3     , 3
1259
                //      ????                             : 0     , 3
1260
 
1261
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
1262
                {
1263
                    Package p = it.next();
1264
                    if (p == build ) {
1265
                        p.mNoBuildReason = 0;
1266
                        p.mBuildFile = 1;
1267
                    } 
1268
                    else if ( p.mBuildFile < 0 )
1269
                    {
1270
                        p.mNoBuildReason = p.mBuildFile;
1271
                        p.mBuildFile = 3;
1272
                    }
1273
                    else if (p.mBuildReason != null)
1274
                    {
1275
                        p.mNoBuildReason = 0;
1276
                        p.mBuildFile = 2;
1277
                    }
1278
                    else
1279
                    {
1280
                        p.mNoBuildReason = 0;
1281
                        p.mBuildFile = 3;
1282
                    }
1283
                }
1284
 
1285
            }
1286
            else
1287
            {
1288
                //  Escrow
1289
                //  The basic plan is the escrow build order
1290
                mBuildOrder = basicPlan.planCollection;
7133 dpurdie 1291
 
1292
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1293
                {
1294
                    PlannedPackage p = it.next();
1295
                    p.mPkg.mNoBuildReason = p.mPkg.mBuildFile;
1296
                    p.mPkg.mBuildFile = p.mBuildLevel + 1;
1297
                }
7082 dpurdie 1298
            }
1299
 
7118 dpurdie 1300
            mLogger.warn("Final Plan");
7082 dpurdie 1301
            for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1302
            {
1303
                PlannedPackage p = it.next();
7118 dpurdie 1304
                mLogger.warn("Plan: {} {} {}", p.mBuildLevel, p.mPkg.mAlias, p.mPkg.mId);
7082 dpurdie 1305
            }
1306
 
1307
 
1308
        }
1309
 
1310
    /** Internal class to contain intermediate results
1311
     */
1312
    class PlanResults {
1313
        int planTime = 0;
1314
        ArrayList<PlannedPackage> planCollection = new ArrayList<PlannedPackage>(); 
1315
    }
1316
 
1317
    /**
1318
     * Process a collection of packages and generate a collection of package plans
1319
     * A package plan is a collection of packages that can be built
1320
     *      The first item in the list is a package that can be built right now
1321
     *      Other items in the list will be packages that can be built now or will need to be built as the result
1322
     *      of a ripple
1323
     *      
1324
     * The method will be called multiple times so that we can evaluate different plans
1325
     * The underling packages will have data and flags that will need to be rested before a calculation      
1326
     *
1327
     * @param name - Name of the plan
1328
     * @param packageCollection - Base collection of packages to plan
1329
     * @param mode - true: Include 'Ripples'
1330
     * 
1331
     * @return
1332
     */
1333
    private PlanResults planCollection(String name, ArrayList<Package> packageCollection, boolean mode)
1334
    {
7118 dpurdie 1335
        Phase phase = new Phase("Plan-" + name); 
7082 dpurdie 1336
        ArrayList<PlannedPackage> ripplePlan = new ArrayList<PlannedPackage>();
1337
        PlanResults results = new PlanResults();
1338
 
1339
        //  Reset flags used in the calculations
1340
        Package.resetProcessed(packageCollection);
6914 dpurdie 1341
 
7163 dpurdie 1342
 
7082 dpurdie 1343
        //  Exclude all packages that cannot be built and all packages that depend on them
1344
        //      First find packages to be directly excluded
1345
        ArrayList<Package>exclude = new ArrayList<Package>();
7099 dpurdie 1346
        phase.setPhase("Exclude Unbuildable");
7082 dpurdie 1347
        for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1348
        {
7082 dpurdie 1349
            Package p = it.next();
1350
            if ( p.mBuildFile == -8 ) {
1351
 
1352
                //  Mark SDK or Pegged so that we don't build them, but can build their dependents
1353
                p.mProcessed = true;
1354
                p.mIsProcessed = true;
7176 dpurdie 1355
                mLogger.warn("SDK/Peg Exclude: {}", p);
7082 dpurdie 1356
 
1357
            } else if (p.mBuildFile < 0 ) {
1358
                exclude.add(p);
7176 dpurdie 1359
                mLogger.warn("Direct Exclude: {}", p);
7082 dpurdie 1360
 
1361
            }
6914 dpurdie 1362
        }
1363
 
7082 dpurdie 1364
        //  Exclude packages that have failed to be built
1365
        //      These are recorded in mBuildExclusionCollection
7099 dpurdie 1366
        phase.setPhase("Exclude Build Failures");
7082 dpurdie 1367
        for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
1368
        {
1369
            BuildExclusion be = it.next();
7176 dpurdie 1370
            mLogger.warn("BE: {}", be);
7099 dpurdie 1371
            if ( !be.isAIndirectError() )
7082 dpurdie 1372
            {
1373
                for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1374
                {
1375
                    Package p = it1.next();
1376
                    if (p.mBuildFile >= 0 && p.mId == be.mId) {
1377
                        p.mBuildFile  = -3;
7176 dpurdie 1378
                        mLogger.warn("AddExclude {}",p);
7082 dpurdie 1379
                        exclude.add(p);
1380
                        break;
1381
                    }
1382
                }
1383
            }
1384
        }
1385
 
1386
 
1387
        //  Process the list of packages to be excluded
1388
        //  Add to the list packages that depend on the excluded package that have not already been excluded
7099 dpurdie 1389
        phase.setPhase("ExcludeAllUsed");
7082 dpurdie 1390
        while( !exclude.isEmpty() )
1391
        {
1392
            Package p = exclude.remove(0);
7118 dpurdie 1393
            mLogger.info("planCollection package not buildable {}. {},{}", p, p.mProcessed, p.mIsProcessed);
7082 dpurdie 1394
 
7118 dpurdie 1395
            p.mProcessed = true;                        // Used to indicate pkg has had its dependencies scanned
1396
            p.mIsProcessed = true;                      // Used to indicate pkg has been added to list to process 
1397
 
7163 dpurdie 1398
 
7082 dpurdie 1399
            for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1400
            {
1401
                Package pkg = it1.next();
1402
                if (pkg.mProcessed) {
1403
                    continue;
1404
                }
1405
 
7163 dpurdie 1406
                for (Iterator<PkgDependency> it = pkg.mDependencyCollection.iterator(); it.hasNext(); )
7082 dpurdie 1407
                {
7163 dpurdie 1408
                    PkgDependency depEntry = it.next();
1409
                    if ( p.mAlias.compareTo( depEntry.alias ) == 0 ) {
7118 dpurdie 1410
                        if (!pkg.mIsProcessed) {
1411
                            pkg.mIsProcessed = true;
7114 dpurdie 1412
                            exclude.add(pkg);
1413
                        }
7082 dpurdie 1414
                    }
1415
                }
1416
            }
1417
        }
1418
 
7133 dpurdie 1419
        // Have a collection packages that we can build right now
1420
        // Create the ripplePlan
6914 dpurdie 1421
 
7133 dpurdie 1422
        phase.setPhase("Calc Build Order");
1423
        if (mDaemon)
6914 dpurdie 1424
        {
7133 dpurdie 1425
            ArrayList<PlannedPackage> toBuild = new ArrayList<PlannedPackage>();
1426
 
7082 dpurdie 1427
            //
7133 dpurdie 1428
            //  Daemon Mode
7163 dpurdie 1429
            //  Generate the ripplePlan - collection of packages that we need to build in the current ripple
7137 dpurdie 1430
            //
7133 dpurdie 1431
            //  Determine if we have a reason to build anything in this collection of buildable packages
1432
            //      Reset the mCheckedCircularDependency - it will be used to detect  that we have processed a package
7082 dpurdie 1433
 
1434
            for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
1435
            {
1436
                Package p = it.next();
7133 dpurdie 1437
                if (!p.mIsProcessed) {
1438
                    PlannedPackage pPkg = new PlannedPackage(p); 
1439
 
1440
                    results.planCollection.add(pPkg);
1441
                    pPkg.mPkg.mCheckedCircularDependency = false;
1442
 
1443
                    if (p.mBuildReason != null) {
1444
                        if (mode || ( !mode && p.mBuildReason != BuildReason.Ripple )) {
1445
                            toBuild.add(pPkg);
1446
                        }
6914 dpurdie 1447
                    }
1448
                }
1449
            }
7082 dpurdie 1450
 
1451
            //  Need (would like to) build stuff
1452
            //  Determine the packages that we need to build and the time that it will take
1453
            //
1454
            if ( !toBuild.isEmpty() )
6914 dpurdie 1455
            {
7099 dpurdie 1456
                //  Locate the packages that we need to build
1457
                //  The build order cannot be correctly determined at this time
1458
                //      Need to add elements to the end of the list while processing
1459
                //      Sum the buildTimes of the packages that we add to the list
7082 dpurdie 1460
                while ( ! toBuild.isEmpty())
6914 dpurdie 1461
                {
7082 dpurdie 1462
                    PlannedPackage pkg = toBuild.remove(0);
1463
 
7099 dpurdie 1464
                    if (pkg.mBuildLevel > 400 ) {
7082 dpurdie 1465
                        mLogger.error("Circular dependency detected - not handled well");
1466
                        break;
1467
                    }
1468
 
7099 dpurdie 1469
                    if ( ! pkg.mPkg.mCheckedCircularDependency )
6914 dpurdie 1470
                    {
7082 dpurdie 1471
                        ripplePlan.add(pkg);
1472
                        results.planTime += pkg.mPkg.mBuildTime;
7099 dpurdie 1473
                        pkg.mPkg.mCheckedCircularDependency = true;
1474
 
7163 dpurdie 1475
                        // How do we handle duplicates ?
7099 dpurdie 1476
                        ArrayList<PlannedPackage> usedBy = usedByPackages(pkg, results.planCollection);
1477
                        toBuild.addAll(usedBy);
6914 dpurdie 1478
                    }
1479
                }
7133 dpurdie 1480
            }
1481
        }
1482
        else
1483
        {
1484
            //  Escrow
1485
            //      Add all (not excluded) packages directly to the ripplePlan
1486
            for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
1487
            {
1488
                Package p = it.next();
1489
                if (!p.mIsProcessed) {
1490
                    ripplePlan.add(new PlannedPackage(p));
1491
                }
1492
            }  
1493
        }
1494
 
1495
        //
1496
        //  Now we have a collection of packages to build (and only the packages to build)
1497
        //  Need to determine the order in which it can be done and assign build levels
1498
        //  Basically:
1499
        //      Scan the collection looking for any package whose dependencies do not exist in the collection
1500
        //      or they have been allocated a build level.
1501
        //
1502
        //      Need to do this in waves so that we can correctly determine the build level.
1503
        //  
1504
        //
1505
        for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1506
        {
1507
            PlannedPackage p = it.next();
1508
            p.mPkg.mCheckedCircularDependency = true;
1509
            p.mBuildLevel = 0;
1510
        }
1511
 
1512
        int buildLevel = 0;
1513
        boolean more = true;
1514
        do  {
1515
            ArrayList<PlannedPackage> thisLevel = new ArrayList<PlannedPackage>();
1516
            for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1517
            {
1518
                PlannedPackage p = it.next();
1519
                if ( p.mPkg.mCheckedCircularDependency )
7099 dpurdie 1520
                {
7133 dpurdie 1521
                    boolean found = false;
7163 dpurdie 1522
                    for (Iterator<PkgDependency> it2 = p.mPkg.mDependencyCollection.iterator(); !found && it2.hasNext(); )
7099 dpurdie 1523
                    {
7163 dpurdie 1524
                        PkgDependency depEntry = it2.next();
7133 dpurdie 1525
                        for (Iterator<PlannedPackage> it3 = ripplePlan.iterator(); !found && it3.hasNext(); )
7099 dpurdie 1526
                        {
7133 dpurdie 1527
                            PlannedPackage pkg = it3.next();
7163 dpurdie 1528
                            if (pkg.mPkg.mAlias.compareTo( depEntry.alias ) == 0)
7099 dpurdie 1529
                            {
7133 dpurdie 1530
                                found = pkg.mPkg.mCheckedCircularDependency ;
1531
                                break;
7099 dpurdie 1532
                            }
1533
                        }
1534
                    }
1535
 
7133 dpurdie 1536
                    if (!found)
7099 dpurdie 1537
                    {
7133 dpurdie 1538
                        //  None of this packages dependencies can be found in the collection of packages to build
1539
                        //  Thus we can build it - at the current level
1540
                        p.mBuildLevel = buildLevel;
1541
                        thisLevel.add(p);
7099 dpurdie 1542
                    }
7082 dpurdie 1543
                }
1544
            }
1545
 
7133 dpurdie 1546
            //  Mark all the packages at this level as have been processed
1547
            //  Cannot do this while we are determining the packages in the level 
1548
            for (Iterator<PlannedPackage> it = thisLevel.iterator(); it.hasNext(); )
1549
            {
1550
                PlannedPackage p = it.next();
1551
                p.mPkg.mCheckedCircularDependency = false;
1552
            }
1553
 
7137 dpurdie 1554
            //
1555
            //  If any packages needed to be build at this level, then there might be a higher level
1556
            //  If no packages needed to be build at this level, then there is nothing to do.
7133 dpurdie 1557
            more = !thisLevel.isEmpty(); 
1558
            buildLevel++;
1559
 
1560
        } while (more);
1561
 
1562
        //  Sort the packages by buildOrder and buildTime
1563
        phase.setPhase("Sort Plan");
1564
        Collections.sort(ripplePlan, PlannedPackage.BuildOrderComparitor);
1565
 
7137 dpurdie 1566
        //  Optionally - Display the calculated plan
1567
        //      It will fill the log, but ...
7133 dpurdie 1568
        if (mLogger.isInfoEnabled() )
1569
        {
1570
            phase.setPhase("Display Build Order");
1571
            mLogger.info("Plan Build {} Time: {}", name, results.planTime);
1572
            for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
1573
            {
1574
                PlannedPackage p = it.next();
1575
                mLogger.info("Plan: {} {} t:{}", p.mBuildLevel, p.mPkg.mAlias, p.mPkg.mBuildTime);
1576
            }
7082 dpurdie 1577
        }
7133 dpurdie 1578
 
1579
        results.planCollection = ripplePlan;
7137 dpurdie 1580
 
7099 dpurdie 1581
        phase.setPhase("EndPlanCollection");
7082 dpurdie 1582
        return results;
1583
    }
6914 dpurdie 1584
 
7082 dpurdie 1585
    /** Generate a plan based on a modified set of packages
1586
     * 
1587
     * @param name      - Name of the plan
1588
     * @param basicPlan - basicPlan
1589
     * @param mode      - True: Include natural ripples and WIPS/RIPPLES that would have been done
1590
     *                          as a part of the basic plan
1591
     * @return
1592
     */
1593
    private PlanResults postRipplePlan(String name, PlanResults basicPlan, boolean mode) {
6914 dpurdie 1594
 
7082 dpurdie 1595
        ArrayList<Package> fullPlanCollection = new ArrayList<Package>(mPackageCollection);
1596
        ArrayList<Package> buildCandidates = new ArrayList<Package>();
1597
        buildCandidates.addAll(mPackageCollectionWip);
1598
        buildCandidates.addAll(mPackageCollectionRipple);
1599
 
1600
        if ( !buildCandidates.isEmpty() )
1601
        {
1602
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1603
            {
1604
                Package p = it.next();
1605
                if (p.mBuildFile >= 0)
6914 dpurdie 1606
                {
7082 dpurdie 1607
                    if (!mode)
6914 dpurdie 1608
                    {
7088 dpurdie 1609
                        //  Exclude packages that would have been processed in the basicPlan
1610
                        for (Iterator<PlannedPackage> it1 = basicPlan.planCollection.iterator(); it1.hasNext(); )
1611
                        {
1612
                            PlannedPackage pkg = it1.next();
1613
                            if (pkg.mPkg == p)
1614
                            {
7176 dpurdie 1615
                                mLogger.warn("Test Plan without {}", p);
7163 dpurdie 1616
                                break;
7088 dpurdie 1617
                            }
1618
                        }
6914 dpurdie 1619
                    }
7082 dpurdie 1620
 
7176 dpurdie 1621
                    mLogger.warn("Test Plan with {}", p);
7082 dpurdie 1622
                    Package foundInRelease = mReleaseManager.findPackage(p.mAlias, fullPlanCollection);
1623
                    int foundIndex = mReleaseManager.findPackageLastIndex;
1624
                    if (foundInRelease == ReleaseManager.NULL_PACKAGE)
1625
                    {
1626
                        fullPlanCollection.add(p);
1627
                    }
1628
                    else
1629
                    {
1630
                        fullPlanCollection.set(foundIndex, p);
1631
                    }
1632
 
1633
                    Package.resetCircularDependency (fullPlanCollection);
1634
                    if ( p.hasCircularDependency( fullPlanCollection ) )
1635
                    {
7176 dpurdie 1636
                        mLogger.info("planRelease circular dependency detected {}", p);
7082 dpurdie 1637
 
1638
                        //  Force this package to be marked as having a circular dependency - even if its been excluded
1639
                        p.mBuildFile = 0;
1640
 
1641
                        // Exclude the package
1642
                        // max 50 chars
1643
                        rippleBuildExclude(p, p.mId, "Package has circular dependency", -6);
1644
                    }
6914 dpurdie 1645
                }
1646
            }
7082 dpurdie 1647
 
1648
        }
1649
        return planCollection(name, fullPlanCollection, mode);
1650
    }
1651
 
1652
    /** 
1653
     *  Calculate a collection of packages that actively use the named package
1654
     *  A consumer package does NOT use the named package,
1655
     *      If the consumer is an SDK or is Pegged
1656
     *      If the consumer is marked as advisoryRipple
1657
     *      If the consumer cannot be built
1658
     *   
1659
     * @param pkg - Package to process
1660
     * @param planCollection - collection of packages to scan
1661
     *
1662
     * @return A collection of packages that actively 'use' the specified package
1663
 
1664
     */
7099 dpurdie 1665
    private ArrayList<PlannedPackage> usedByPackages(PlannedPackage pkg, ArrayList<PlannedPackage> planCollection) {
7082 dpurdie 1666
 
1667
        ArrayList<PlannedPackage> usedBy = new ArrayList<PlannedPackage>();
1668
 
1669
        for (Iterator<PlannedPackage> it = planCollection.iterator(); it.hasNext(); )
1670
        {
1671
            PlannedPackage p = it.next();
1672
 
1673
            //  Is this package 'actively used' in the current build
1674
            if (p.mPkg.mBuildFile >= 0)
6914 dpurdie 1675
            {
7163 dpurdie 1676
                for (Iterator<PkgDependency> it2 = p.mPkg.mDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 1677
                {
7163 dpurdie 1678
                    PkgDependency depEntry = it2.next();
1679
                    if (  pkg.mPkg.mAlias.compareTo( depEntry.alias ) == 0  ) {
7088 dpurdie 1680
                        //  Have found a consumer of 'pkg'
1681
                        usedBy.add(p);
6914 dpurdie 1682
                        break;
1683
                    }
1684
                }
7082 dpurdie 1685
            }
1686
        }
1687
 
1688
        return usedBy;
1689
    }
1690
 
1691
    /** 
1692
     *  Calculate a collection of packages that use the named package
1693
     *   
1694
     * @param pkg - Package to process
1695
     * @param pkgCollection - collection of packages to scan
1696
     *
1697
     * @return A collection of packages that actively 'use' the specified package
6914 dpurdie 1698
 
7082 dpurdie 1699
     */
1700
    private ArrayList<Package> usedByAnyPackages(Package pkg, ArrayList<Package> pkgCollection) {
1701
 
1702
        ArrayList<Package> usedBy = new ArrayList<Package>();
1703
 
1704
        for (Iterator<Package> it = pkgCollection.iterator(); it.hasNext(); )
1705
        {
1706
            Package p = it.next();
1707
 
7163 dpurdie 1708
            for (Iterator<PkgDependency> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
7082 dpurdie 1709
            {
7163 dpurdie 1710
                PkgDependency depEntry = it2.next();
1711
                if (  pkg.mAlias.compareTo( depEntry.alias ) == 0  ) {
7082 dpurdie 1712
                    usedBy.add(p);
1713
                    break;
1714
                }
6914 dpurdie 1715
            }
7082 dpurdie 1716
        }
1717
 
1718
        return usedBy;
6914 dpurdie 1719
    }
7163 dpurdie 1720
 
1721
    /**
1722
     *  Locate Daemon Instructions ( TEST and RIPPLE ) Requests that cannot be satisfied - will not be built due to
1723
     *  errors in dependent packages. Report the error to the user and remove the request
1724
     *  
1725
     *  These need o be rejected now as the the Master logic will plan a build a build if there is a daemon instruction
1726
     *  present. If an instruction cannot be processed and is not removed, then the daemon will continuously 'plan'
1727
     */
1728
    private void reportUnsatisfiedDaemonInstructions() throws SQLException, Exception {
1729
        ArrayList<Package> toProcess = new ArrayList<Package>();
1730
        toProcess.addAll(mPackageCollectionTest);
1731
        toProcess.addAll(mPackageCollectionRipple);
1732
 
1733
        for (Iterator<Package> it = toProcess.iterator(); it.hasNext(); )
1734
        {
1735
            Package p = it.next();
1736
 
1737
            //
1738
            //  If the package is in the 'plan, then its not excluded
1739
            //
1740
            boolean isPlanned = false;
1741
            for (Iterator<PlannedPackage> it1 = mBuildOrder.listIterator(); it1.hasNext(); )
1742
            {
1743
                PlannedPackage pkg = it1.next();
1744
                if (pkg.mPkg == p)
1745
                {
1746
                    isPlanned = true;
1747
                    break;
1748
                }
1749
            }
1750
 
1751
            if (! isPlanned) 
1752
            {
1753
 
1754
                // If this package has been excluded, then we can't build it
1755
                //
1756
                boolean excluded = false;
1757
                for (ListIterator<BuildExclusion> it1 = mBuildExclusionCollection.listIterator(); it1.hasNext(); )
1758
                {
1759
                    BuildExclusion be = it1.next();
1760
                    if (be.compare(p.mId))
1761
                    {
1762
                        excluded = true;
1763
                        if (p.mBuildFile >= 0)
1764
                            p.mBuildFile = -5;
1765
                        break;
1766
                    }
1767
                }
1768
 
1769
 
1770
                if (excluded)
1771
                {
1772
                    String reason;
1773
                    switch (p.mBuildFile)
1774
                    {
1775
                    case -1:  reason = "Not reproducible"; break;
1776
                    case -2:  reason = "Not reproducible on configured build platforms"; break;
1777
                    case -3:  reason = "Marked as 'Do not ripple'"; break;
1778
                    case -4:  reason = "Dependent on a package not in the release"; break;
1779
                    case -5:  reason = "Indirectly dependent on a package not reproducible in the release"; break;
1780
                    case -6:  reason = "Has a circular dependency"; break;
1781
                    case -7:  reason = "Pegged or SDK package not in dpkg_archive"; break;
1782
                    case -8:  reason = "Is a Pegged or SDK package"; break;
1783
                    case -9:  reason = "Rejected Daemon Instruction"; break;
1784
                    case -10: reason = "Unbuildable package not in dpkg_archive"; break;
1785
                    case -11: reason = "Marked as 'RippleStop'"; break;
1786
                    case -12: reason = "Cannot generate next version number"; break;
1787
                    default:  reason = "Unknown reason. Code:" + p.mBuildFile; break;
1788
                    }
1789
                    mLogger.warn("planRelease Test Build of an unbuildable of package deleted: {}", p);
1790
 
1791
                    int daemonInstruction = p.mTestBuildInstruction > 0  ? p.mTestBuildInstruction : p.mForcedRippleInstruction; 
1792
                    if ( daemonInstruction <= 0)
1793
                    {
7176 dpurdie 1794
                        mLogger.warn("Daemon Instruction number not found for {}", p);
7163 dpurdie 1795
                    }
1796
 
1797
                    mReleaseManager.markDaemonInstCompleted( daemonInstruction );
1798
                    emailRejectedDaemonInstruction(reason,p);
1799
                }
1800
            }
1801
        }
1802
 
1803
    }
6914 dpurdie 1804
 
1805
    /** Determine if a given PVID is a member of the current release.
1806
     *  Used to determine if a package dependency is out of date
1807
     * 
1808
     * @param dpvId
1809
     * @return true - specified pvid is a full member of the Release
1810
     */
1811
    private boolean isInRelease(Integer dpvId) {
1812
 
7082 dpurdie 1813
        boolean inRelease = false;
6914 dpurdie 1814
 
7082 dpurdie 1815
        for ( Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1816
        {
7082 dpurdie 1817
            Package p = it.next();
6914 dpurdie 1818
 
7082 dpurdie 1819
            if ( p.mId == dpvId )
6914 dpurdie 1820
            {
7082 dpurdie 1821
                inRelease = ! p.mIsNotReleased;
6914 dpurdie 1822
                break;
1823
            }
1824
        }
7082 dpurdie 1825
        return inRelease;
6914 dpurdie 1826
    }
1827
 
1828
 
7082 dpurdie 1829
    /** Reports what change in build exceptions happens as part of planRelease
1830
     * 
1831
     *  There are three types of exceptions
1832
     *      PlanError - These may be removed, if the error was not seen in the last plan
1833
     *      BuildErrors - These we persist
1834
     *      IndirectErrors - Packages that depend on a Plan or Build errors
6914 dpurdie 1835
     */
1836
    public void reportChange() throws SQLException, Exception
1837
    {
1838
        int counter = 0;
1839
        for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1840
        {
1841
            BuildExclusion buildExclusion = it.next();
1842
 
7082 dpurdie 1843
            //  Skip 'Processed' entries
7141 dpurdie 1844
            //      These will be the result of a PlanError that we have seen again
7082 dpurdie 1845
            //
7141 dpurdie 1846
            if ( buildExclusion.isProcessed() ) {
1847
                continue;
1848
            }
1849
 
1850
            //  BuildErrors     - Persist ( do nothing) These are handled elsewhere
1851
            //  PackageErrors   - Add new (ie: was not imported)
1852
            //  IndirectErrors  - Add/Remove as detected
7082 dpurdie 1853
            //  
7141 dpurdie 1854
            if (buildExclusion.isABuildError()) {
1855
                continue;
1856
 
1857
            } else if (buildExclusion.isAPackageError()) {
1858
                if (buildExclusion.isImported()) {
1859
                    continue;
7032 dpurdie 1860
                }
6914 dpurdie 1861
            }
7141 dpurdie 1862
 
1863
            if (buildExclusion.isImported()) {
1864
                // Remove from the exclusion list
7176 dpurdie 1865
                mLogger.warn("reportChange remove unused exclusion: {}", buildExclusion );
7141 dpurdie 1866
                buildExclusion.includeToBuild(mReleaseManager, mBaseline);
1867
 
1868
            } else {
1869
                // Exclude and notify
7176 dpurdie 1870
                mLogger.warn("reportChange add new exclusion: {}", buildExclusion );
7141 dpurdie 1871
                buildExclusion.excludeFromBuild(mReleaseManager, mBaseline);
1872
                buildExclusion.email(this, mPackageCollectionAll);
1873
                counter++;
1874
            }
6914 dpurdie 1875
        }
7176 dpurdie 1876
        mLogger.warn("reportChange exclusion count: {}", counter);
6914 dpurdie 1877
    }
1878
 
1879
    /**reports the build plan
1880
     */
1881
    public void reportPlan() throws SQLException, Exception
1882
    {
1883
        mReleaseManager.reportPlan(mRtagId, mBuildOrder);
1884
    }
1885
 
1886
    /**Returns the first build file from the collection
1887
     * The build file will be flagged as empty if none exists
1888
     */
1889
    public BuildFile getFirstBuildFileContent()
1890
    {
1891
        mLogger.debug("getFirstBuildFileContent");
1892
 
1893
        mBuildIndex = -1;
1894
        return getNextBuildFileContent();
1895
    }
1896
 
1897
    /**Returns next build file from the collection
1898
     * The build file will be flagged as empty if none exists
1899
     */
1900
    public BuildFile getNextBuildFileContent()
1901
    {
1902
        mLogger.debug("getNextBuildFileContent");
1903
        BuildFile retVal = null;
1904
 
1905
        try
1906
        {
1907
            mBuildIndex++;
1908
            retVal = mBuildCollection.get( mBuildIndex );
1909
        }
1910
        catch( IndexOutOfBoundsException e )
1911
        {
1912
            // Ignore exception. retVal is still null.
1913
        }
1914
 
1915
        if (retVal == null)
1916
        {
1917
            retVal = new BuildFile();
1918
        }
1919
 
7044 dpurdie 1920
        mLogger.debug("getNextBuildFileContent returned {}", retVal.state.name() );
6914 dpurdie 1921
        return retVal;
1922
    }
1923
 
1924
 
1925
    /**collects meta data associated with the baseline
1926
     * this is sufficient to send an indefinite pause email notification 
1927
     *  
1928
     * Escrow: Used once to collect information about the SBOM and associated Release 
1929
     *         mBaseline is an SBOMID 
1930
     * Daemon: Used each build cycle to refresh the information 
1931
     *          mBaseline is an RTAGID
1932
     */
1933
    public void collectMetaData() throws SQLException, Exception
1934
    {
1935
        Phase phase = new Phase("cmd");
7044 dpurdie 1936
        mLogger.debug("collectMetaData mDaemon {}", mDaemon);
6914 dpurdie 1937
 
1938
        try
1939
        {
1940
            phase.setPhase("connect");
1941
            mReleaseManager.connect();
1942
 
1943
            if (! mDaemon)
1944
            {
1945
                mSbomId = mBaseline;
1946
                phase.setPhase("queryRtagIdForSbom");
1947
                mRtagId = mReleaseManager.queryRtagIdForSbom(mBaseline);
1948
                if (mRtagId == 0)
1949
                {
7033 dpurdie 1950
                    mLogger.error("SBOM does not have a matching Release. Cannot be used as a base for an Escrow"); 
6914 dpurdie 1951
                    throw new Exception("rtagIdForSbom show stopper. SBOM does not have an associated Release");
1952
                }
1953
            }
1954
 
1955
            phase.setPhase("queryReleaseConfig");
1956
            mReleaseManager.queryReleaseConfig(mRtagId);
1957
 
1958
            if (mDaemon)
1959
            {
1960
                phase.setPhase("queryMailServer");
1961
                setMailServer(mReleaseManager.queryMailServer());
1962
                phase.setPhase("queryMailSender");
1963
                setMailSender(mReleaseManager.queryMailSender());
1964
                phase.setPhase("queryGlobalAddresses");
1965
                setMailGlobalTarget(mReleaseManager.queryGlobalAddresses());
1966
                phase.setPhase("queryProjectEmail");
1967
                mMailGlobalCollection = mReleaseManager.queryProjectEmail(mBaseline);
1968
                phase.setPhase("mMailGlobalTarget");
1969
                mMailGlobalCollection.add(0,getMailGlobalTarget());
7169 dpurdie 1970
                phase.setPhase("mPlanControl");
1971
                mReleaseManager.queryPlanControl(mBaseline, mPlanControl);
6914 dpurdie 1972
            }
1973
            phase.setPhase("queryBaselineName");
1974
            mBaselineName = mReleaseManager.queryBaselineName(mBaseline);
1975
            phase.setPhase("Done");
1976
        }
1977
        finally
1978
        {
1979
            // this block is executed regardless of what happens in the try block
1980
            // even if an exception is thrown
1981
            // ensure disconnect
1982
            mReleaseManager.disconnect();
1983
        }
1984
    }
1985
 
1986
    /**
1987
     * Find Package by package alias
7082 dpurdie 1988
     * Searches the released package collection
6914 dpurdie 1989
     * @param   alias               - alias of package to locate
1990
     * @return  Package with the matching mAlias or NULL_PACKAGE if no package has the mAlias
1991
     */
1992
    public Package findPackage(String alias)
1993
    {
1994
        mLogger.debug("findPackage");
1995
 
1996
        Package retVal = mReleaseManager.findPackage(alias, mPackageCollection);
1997
 
7176 dpurdie 1998
        mLogger.debug("findPackage returned {}", retVal.mName);
6914 dpurdie 1999
        return retVal;
2000
    }
7082 dpurdie 2001
 
6914 dpurdie 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
}