Subversion Repositories DevTools

Rev

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

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