Subversion Repositories DevTools

Rev

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