Subversion Repositories DevTools

Rev

Rev 7079 | Rev 7081 | 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
7079 dpurdie 1032
                    mBuildOrder.addAll(basicPlan.planCollection);
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
1104
                //  ie: They will be built because one, or more, of there dependents is not buildable
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
1119
                         if ( be.compare(p.mId) && be.isARootCause() && p.mTestBuildInstruction == 0 && p.mForcedRippleInstruction == 0 )
1120
                         {
1121
                             // package is not reproducible, discard it and its consumers
1122
                             //
7080 dpurdie 1123
                             mLogger.info("Excluded Package {}, {}", p.mAlias, be.mRootCause);                                     
7079 dpurdie 1124
 
1125
                             ArrayList<Package> toExclude = new ArrayList<Package>();
1126
                             toExclude.addAll(usedByAnyPackages(p, mPackageCollection ));
1127
 
1128
                             //  Process packages that we need to exclude indirectly
1129
                             //
1130
                             while ( ! toExclude.isEmpty())
1131
                             {
1132
                                 Package pkg = toExclude.remove(0);
1133
 
1134
                                 // If this package has not been excluded ( for whatever reason), than add it
1135
                                 boolean found = false;
1136
                                 for (Iterator<BuildExclusion> it2 = mBuildExclusionCollection.iterator(); it2.hasNext(); )
1137
                                 {
1138
                                     BuildExclusion buildExclusion = it2.next();
1139
                                     if (buildExclusion.compare(pkg.mId) )
1140
                                     {
1141
                                         found = true;
1142
                                         break;
1143
                                     }
1144
                                 }
1145
 
1146
                                 if (!found)
1147
                                 {
1148
                                     BuildExclusion buildExclusion = new BuildExclusion(pkg.mId, p.mId, null, p.mTestBuildInstruction);
1149
                                     it.add(buildExclusion);
7080 dpurdie 1150
                                     mLogger.info("Indirectly Excluded Package {}", pkg.mAlias);  
7079 dpurdie 1151
 
1152
                                     ArrayList<Package> usedBy = usedByAnyPackages(p, mPackageCollectionAll );
1153
                                     toExclude.addAll(usedBy);
1154
                                 }
1155
                             }
1156
                         }
1157
                     }
1158
                 }
1159
 
1160
                //
1161
                //  To fit in with the old algorithm ( ie: could be improved )
1162
                //  Insert marks into all packages
1163
                //  Not sure exactly why - Its used in the generation of the ant build file
1164
                //                     Want to set mNoBuildReason, mBuildFile
1165
                //
1166
                //      Package we have selected to build: 0     , 1
1167
                //      Package we could have built      : 0     , 2
1168
                //      Packages we can't build          : reason, 3
1169
                //      Packages that are OK             : 3     , 3
1170
                //      ????                             : 0     , 3
1171
 
1172
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
1173
                {
1174
                    Package p = it.next();
1175
                    if (p == build ) {
1176
                        p.mNoBuildReason = 0;
1177
                        p.mBuildFile = 1;
1178
                    } 
1179
                    else if ( p.mBuildFile < 0 )
1180
                    {
1181
                        p.mNoBuildReason = p.mBuildFile;
1182
                        p.mBuildFile = 3;
1183
                    }
1184
                    else if (p.mBuildReason != null)
1185
                    {
1186
                        p.mNoBuildReason = 0;
1187
                        p.mBuildFile = 2;
1188
                    }
1189
                    else
1190
                    {
1191
                        p.mNoBuildReason = 0;
1192
                        p.mBuildFile = 3;
1193
                    }
1194
                }
1195
 
1196
            }
1197
            else
1198
            {
1199
                //  Escrow
1200
                //  The basic plan is the escrow build order
1201
                mBuildOrder = basicPlan.planCollection;
1202
            }
1203
 
1204
            mLogger.error("Final Plan");
1205
            for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
1206
            {
1207
                PlannedPackage p = it.next();
7080 dpurdie 1208
                mLogger.error("Plan: {} {} {}", p.mBuildLevel, p.mPkg.mAlias, p.mPkg.mId);
7079 dpurdie 1209
            }
1210
 
1211
 
1212
        }
1213
 
7078 dpurdie 1214
    /** Internal class to contain intermediate results
6914 dpurdie 1215
     */
7078 dpurdie 1216
    class PlanResults {
1217
        int planTime = 0;
7079 dpurdie 1218
        ArrayList<PlannedPackage> planCollection = new ArrayList<PlannedPackage>(); 
7078 dpurdie 1219
    }
1220
 
1221
    /**
1222
     * Process a collection of packages and generate a collection of package plans
1223
     * A package plan is a collection of packages that can be built
1224
     *      The first item in the list is a package that can be built right now
1225
     *      Other items in the list will be packages that can be built now or will need to be built as the result
1226
     *      of a ripple
1227
     *      
1228
     * The method will be called multiple times so that we can evaluate different plans
1229
     * The underling packages will have data and flags that will need to be rested before a calculation      
1230
     *
1231
     * @param name - Name of the plan
1232
     * @param packageCollection - Base collection of packages to plan
1233
     * @param mode - true: Include 'Ripples'
1234
     * 
1235
     * @return
1236
     */
1237
    private PlanResults planCollection(String name, ArrayList<Package> packageCollection, boolean mode)
7070 dpurdie 1238
    {
7079 dpurdie 1239
        ArrayList<PlannedPackage> ripplePlan = new ArrayList<PlannedPackage>();
7078 dpurdie 1240
        PlanResults results = new PlanResults();
6914 dpurdie 1241
 
7078 dpurdie 1242
        //  Reset flags used in the calculations
1243
        Package.resetProcessed(packageCollection);
6914 dpurdie 1244
 
7078 dpurdie 1245
        //  Exclude all packages that cannot be built and all packages that depend on them
1246
        //      First find packages to be directly excluded
1247
        ArrayList<Package>exclude = new ArrayList<Package>();
1248
        for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
1249
        {
1250
            Package p = it.next();
1251
            if (p.mBuildFile < 0) {
1252
                exclude.add(p);
1253
            }
1254
        }
1255
 
7080 dpurdie 1256
        //  Exclude packages that have failed to be built
1257
        //      These are recorded in mBuildExclusionCollection
1258
        for (ListIterator<BuildExclusion> it = mBuildExclusionCollection.listIterator(); it.hasNext(); )
1259
        {
1260
            BuildExclusion be = it.next();
1261
            if (be.mRootCause == null && be.mRootId == -1 )
1262
            {
1263
                for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1264
                {
1265
                    Package p = it1.next();
1266
                    if (p.mId == be.mId) {
1267
                        p.mBuildFile  = -3;
1268
                        exclude.add(p);
1269
                        break;
1270
                    }
1271
                }
1272
            }
1273
        }
1274
 
1275
 
7078 dpurdie 1276
        //  Process the list of packages to be excluded
1277
        //  Add to the list packages that depend on the excluded package that have not already been excluded
1278
        while( !exclude.isEmpty() )
1279
        {
1280
            Package p = exclude.remove(0);
1281
            p.mProcessed = true;
1282
            p.mIsProcessed = true;
1283
            mLogger.info("planCollection package not buildable {}", p.mName);
1284
 
1285
            for (Iterator<Package> it1 = packageCollection.iterator(); it1.hasNext(); )
1286
            {
1287
                Package pkg = it1.next();
1288
                if (pkg.mProcessed) {
1289
                    continue;
1290
                }
1291
 
7080 dpurdie 1292
                for (Iterator<String> it = pkg.mDependencyCollection.iterator(); it.hasNext(); )
7078 dpurdie 1293
                {
1294
                    String alias = it.next();
1295
                    if ( p.mAlias.compareTo( alias ) == 0 ) {
1296
                        exclude.add(pkg);
1297
                    }
1298
                }
1299
            }
1300
        }
1301
 
1302
        //  Now have a collection of packages with those that we cannot build have been marked
1303
        //  Process the list and determine packages that we can build right now
1304
        //      ie: they have not been excluded, have not already been discovered and do not depend on any package in the collection
1305
        //      Continue to do this until all packages have been extracted
1306
        //      Allocate build levels as we go
1307
        //
6914 dpurdie 1308
        boolean allProcessed = false;
7078 dpurdie 1309
        int buildLevel = 1;
6914 dpurdie 1310
 
1311
        do
1312
        {
7048 dpurdie 1313
            //
1314
            //  Create the mBuildOrder collection
1315
            //      Same for both Daemon and Escrow modes
1316
            //      Will have package build order and build level
6914 dpurdie 1317
            boolean allDependenciesProcessed = true;
1318
            do
1319
            {
1320
                allDependenciesProcessed = true;
7078 dpurdie 1321
                for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1322
                {
1323
                    Package p = it.next();
7078 dpurdie 1324
 
1325
                    //  Skip packages that have been processed - have determined build order, or cannot build
1326
                    if (p.mIsProcessed) {
1327
                        continue;
1328
                    }
6914 dpurdie 1329
 
7078 dpurdie 1330
                    // Package yet to be processed and
1331
                    //      Daemon mode: Could be built
1332
                    //      Escrow mode: Can be reproduced
1333
                    boolean canBeBuiltNow = true;
1334
                    boolean allDependenciesForThisPackageProcessed = true;
1335
 
1336
                    //  Scan the packages dependencies
1337
                    for ( Iterator<Package> it2 = p.mPackageDependencyCollection.iterator(); it2.hasNext(); )
6914 dpurdie 1338
                    {
7078 dpurdie 1339
                        Package dependency = it2.next();
6914 dpurdie 1340
 
7078 dpurdie 1341
                        if ( !dependency.mProcessed )
6914 dpurdie 1342
                        {
7078 dpurdie 1343
                            //  If all the dependencies have been processed, then we can potentially build this package
1344
                            //  If any of them have not been processed, then cannot calculate canBeBuiltNow until this 
1345
                            //  dependency has been processed
1346
                            allDependenciesForThisPackageProcessed = false;
1347
                            allDependenciesProcessed = false;
6914 dpurdie 1348
                        }
7078 dpurdie 1349
                        else if (  (  mDaemon && (   dependency.mBuildFile == 0 ) ||  (dependency.mBuildFile == buildLevel)) 
1350
                                || ( !mDaemon && ( ( dependency.mBuildFile == 0 ) ||
1351
                                                       ( dependency.mBuildFile == buildLevel &&
1352
                                                       ( !p.haveSameBuildStandards(dependency)  ) ) ) ) )
1353
                        {
1354
                            // Can be built - yet
1355
                            // Daemon mode:
1356
                            //    This processed dependency has not been assigned to a build iteration
1357
                            //    This processed dependency has been assigned to this build iteration
1358
                            // Escrow mode: This package cannot be built now if
1359
                            //    This processed dependency has not been assigned to a build iteration or
1360
                            //    This processed dependency has been assigned to this build iteration, but the 
1361
                            //    build standards of the package and this dependency prevent the package being
1362
                            //    built in this iteration.   
1363
                            canBeBuiltNow = false;
1364
                            mLogger.info("planRelease package cannot be built in this iteration {}", p.mName);
1365
                            break;
1366
                        }
1367
                    }
6914 dpurdie 1368
 
7078 dpurdie 1369
                    //  All dependencies have been processed. May be able to build this package
1370
                    //      Add the package to the build order list
1371
                    //
1372
                    if (allDependenciesForThisPackageProcessed)
1373
                    {
1374
                        p.mProcessed = true;
1375
                        if ( canBeBuiltNow )
6914 dpurdie 1376
                        {
7079 dpurdie 1377
                            results.planCollection.add( new PlannedPackage(p, buildLevel));
7078 dpurdie 1378
                            p.mBuildFile = buildLevel;
1379
                            p.mIsProcessed = true;
1380
                            mLogger.info("planRelease set mBuildFile to {} for package {}",buildLevel, p.mAlias );
6914 dpurdie 1381
                        }
1382
                    }
1383
                }
1384
            } while( !allDependenciesProcessed );
7048 dpurdie 1385
 
1386
            //  Have process all the packages that we can at the moment
1387
            //      Examine all the packages in the collection to see if there are more that need to be extracted
1388
            //      These will be done at a different build-level
1389
            //  
1390
            allProcessed = true;
7078 dpurdie 1391
            for (Iterator<Package> it = packageCollection.iterator(); it.hasNext(); )
7048 dpurdie 1392
            {
1393
                Package p = it.next();
7078 dpurdie 1394
                if ( !  p.mIsProcessed )
7048 dpurdie 1395
                {
1396
                    // more build files are required
1397
                    allProcessed = false;
1398
                    mLogger.info("planRelease more build files are required for {}", p.mName);
1399
                    break;
1400
                }
1401
            }
6914 dpurdie 1402
 
7078 dpurdie 1403
            buildLevel++;
1404
            if (buildLevel % 500 == 0 ) {
1405
                mLogger.error("planRelease. Too many build levels {}", buildLevel);
7048 dpurdie 1406
            }
1407
        } while( !allProcessed );
7078 dpurdie 1408
 
1409
        //  Now we have a collection packages that we can build right now
1410
        //      The packages currently have a build level set into mBuildFile
1411
        //
1412
        if (mDaemon)
7048 dpurdie 1413
        {
7078 dpurdie 1414
            //  Determine if we have a reason to build anything in this collection of buildable packages
7079 dpurdie 1415
            //  Reset the calculated buildLevel - It will be calculated again
1416
            //
1417
            ArrayList<PlannedPackage> toBuild = new ArrayList<PlannedPackage>();
1418
            for (Iterator<PlannedPackage> it = results.planCollection.iterator(); it.hasNext(); )
6914 dpurdie 1419
            {
7079 dpurdie 1420
                PlannedPackage p = it.next();
1421
                p.mBuildLevel = 0;
1422
 
1423
                if (p.mPkg.mBuildReason != null) {
1424
                    if (mode || ( !mode && p.mPkg.mBuildReason != BuildReason.Ripple ))
7048 dpurdie 1425
                    {
7078 dpurdie 1426
                        toBuild.add(p);
7048 dpurdie 1427
                    }
1428
                }
1429
            }
1430
 
7078 dpurdie 1431
            //  Need (would like to) build stuff
1432
            //  Determine the packages that we need to build and the time that it will take
7070 dpurdie 1433
            //
7078 dpurdie 1434
            if ( !toBuild.isEmpty() )
7048 dpurdie 1435
            {
7078 dpurdie 1436
                results.planTime = 0;
1437
 
1438
 
1439
                //  Need to add elements to the end of the list while processing
1440
                //  Sum the buildTimes of the packages that we add to the list
1441
                while ( ! toBuild.isEmpty())
7048 dpurdie 1442
                {
7079 dpurdie 1443
                    PlannedPackage pkg = toBuild.remove(0);
7078 dpurdie 1444
 
7079 dpurdie 1445
                    if (pkg.mBuildLevel > 100 ) {
7078 dpurdie 1446
                        mLogger.error("Circular dependency detected - not handled well");
1447
                        break;
7048 dpurdie 1448
                    }
1449
 
7078 dpurdie 1450
                    if ( ! ripplePlan.contains( pkg ))
7048 dpurdie 1451
                    {
7078 dpurdie 1452
                        ripplePlan.add(pkg);
7079 dpurdie 1453
                        results.planTime += pkg.mPkg.mBuildTime;
7048 dpurdie 1454
                    }
1455
 
7079 dpurdie 1456
                    ArrayList<PlannedPackage> usedBy = usedByPackages(pkg, results.planCollection, pkg.mBuildLevel + 1);
7078 dpurdie 1457
                    toBuild.addAll(usedBy);
6914 dpurdie 1458
                }
7079 dpurdie 1459
 
7078 dpurdie 1460
                //  Sort the packages by buildOrder and buildTime
7079 dpurdie 1461
                Collections.sort(ripplePlan, PlannedPackage.BuildOrderComparitor);
7078 dpurdie 1462
 
7080 dpurdie 1463
                mLogger.info("Plan Build {} Time: {}", name, results.planTime);
7079 dpurdie 1464
                for (Iterator<PlannedPackage> it = ripplePlan.iterator(); it.hasNext(); )
7078 dpurdie 1465
                {
7079 dpurdie 1466
                    PlannedPackage p = it.next();
7080 dpurdie 1467
                    mLogger.info("Plan: {} {}", p.mBuildLevel, p.mPkg.mAlias);
7078 dpurdie 1468
                }
6914 dpurdie 1469
            }
7048 dpurdie 1470
 
7078 dpurdie 1471
            //  Daemon mode: Returning calculated plan
1472
            results.planCollection = ripplePlan;
1473
        }
1474
 
1475
        return results;
1476
    }
6914 dpurdie 1477
 
7078 dpurdie 1478
    /** Generate a plan based on a modified set of packages
1479
     * 
1480
     * @param name      - Name of the plan
1481
     * @param basicPlan - basicPlan
1482
     * @param mode      - True: Include natural ripples and WIPS/RIPPLES that would have been done
1483
     *                          as a part of the basic plan
1484
     * @return
1485
     */
1486
    private PlanResults postRipplePlan(String name, PlanResults basicPlan, boolean mode) {
1487
 
1488
        ArrayList<Package> fullPlanCollection = new ArrayList<Package>(mPackageCollection);
1489
        ArrayList<Package> buildCandidates = new ArrayList<Package>();
1490
        buildCandidates.addAll(mPackageCollectionWip);
1491
        buildCandidates.addAll(mPackageCollectionRipple);
1492
 
1493
        if ( !buildCandidates.isEmpty() )
1494
        {
7048 dpurdie 1495
            for (Iterator<Package> it = buildCandidates.iterator(); it.hasNext(); )
1496
            {
1497
                Package p = it.next();
7078 dpurdie 1498
                if (p.mBuildFile >= 0)
6914 dpurdie 1499
                {
7078 dpurdie 1500
                    if (!mode)
6914 dpurdie 1501
                    {
7078 dpurdie 1502
                        //  Exclude packages that would have been processed in the basicPlan
7079 dpurdie 1503
                        for (Iterator<PlannedPackage> it1 = basicPlan.planCollection.iterator(); it1.hasNext(); )
7048 dpurdie 1504
                        {
7079 dpurdie 1505
                            PlannedPackage pkg = it1.next();
1506
                            if (pkg.mPkg == p)
7078 dpurdie 1507
                            {
7080 dpurdie 1508
                                mLogger.info("Test Plan without {}", p.mAlias);
7078 dpurdie 1509
                                continue;
1510
                            }
7048 dpurdie 1511
                        }
6914 dpurdie 1512
                    }
7078 dpurdie 1513
 
7080 dpurdie 1514
                    mLogger.info("Test Plan with {}", p.mAlias);
7078 dpurdie 1515
                    Package foundInRelease = mReleaseManager.findPackage(p.mAlias, fullPlanCollection);
1516
                    int foundIndex = mReleaseManager.findPackageLastIndex;
1517
                    if (foundInRelease == ReleaseManager.NULL_PACKAGE)
1518
                    {
1519
                        fullPlanCollection.add(p);
1520
                    }
1521
                    else
1522
                    {
1523
                        fullPlanCollection.set(foundIndex, p);
1524
                    }
1525
 
1526
                    Package.resetCircularDependency (fullPlanCollection);
1527
                    if ( p.hasCircularDependency( fullPlanCollection ) )
1528
                    {
1529
                        mLogger.info("planRelease circular dependency detected {}", p.mAlias);
1530
 
1531
                        //  Force this package to be marked as having a circular dependency - even if its been excluded
1532
                        p.mBuildFile = 0;
1533
 
7079 dpurdie 1534
                        // Exclude the package
7078 dpurdie 1535
                        // max 50 chars
7079 dpurdie 1536
                        rippleBuildExclude(p, p.mId, "Package has circular dependency", -6);
7078 dpurdie 1537
                    }
6914 dpurdie 1538
                }
1539
            }
7048 dpurdie 1540
 
7078 dpurdie 1541
        }
1542
        return planCollection(name, fullPlanCollection, mode);
1543
    }
1544
 
7079 dpurdie 1545
    /** 
1546
     *  Calculate a collection of packages that actively use the named package
1547
     *  A consumer package does NOT use the named package,
1548
     *      If the consumer is an SDK or is Pegged
1549
     *      If the consumer is marked as advisoryRipple
1550
     *      If the consumer cannot be built
1551
     *   
1552
     * @param pkg - Package to process
1553
     * @param planCollection - collection of packages to scan
1554
     * @param rippleOrder - Set the ripple oder, if >= 0
1555
     *
1556
     * @return A collection of packages that actively 'use' the specified package
1557
 
7078 dpurdie 1558
     */
7079 dpurdie 1559
    private ArrayList<PlannedPackage> usedByPackages(PlannedPackage pkg, ArrayList<PlannedPackage> planCollection, int rippleOrder) {
7078 dpurdie 1560
 
7079 dpurdie 1561
        ArrayList<PlannedPackage> usedBy = new ArrayList<PlannedPackage>();
7078 dpurdie 1562
 
7079 dpurdie 1563
        for (Iterator<PlannedPackage> it = planCollection.iterator(); it.hasNext(); )
7078 dpurdie 1564
        {
7079 dpurdie 1565
            PlannedPackage p = it.next();
7070 dpurdie 1566
 
7079 dpurdie 1567
            //  Is this package 'actively used' in the current build
1568
            if (p.mPkg.mBuildFile >= 0)
7070 dpurdie 1569
            {
7079 dpurdie 1570
                for (Iterator<String> it2 = p.mPkg.mDependencyCollection.iterator(); it2.hasNext(); )
7070 dpurdie 1571
                {
7079 dpurdie 1572
                    String alias = it2.next();
1573
                    if (  pkg.mPkg.mAlias.compareTo( alias ) == 0  ) {
1574
                        //  Have found a consumer of 'pkg'
1575
                        usedBy.add(p);
1576
                        if (rippleOrder >= 0)
1577
                            p.mBuildLevel = rippleOrder;
1578
                        break;
7070 dpurdie 1579
                    }
1580
                }
1581
            }
7048 dpurdie 1582
        }
7079 dpurdie 1583
 
1584
        return usedBy;
7048 dpurdie 1585
    }
7079 dpurdie 1586
 
7048 dpurdie 1587
    /** 
7079 dpurdie 1588
     *  Calculate a collection of packages that use the named package
7048 dpurdie 1589
     *   
1590
     * @param pkg - Package to process
7070 dpurdie 1591
     * @param pkgCollection - collection of packages to scan
7078 dpurdie 1592
     *
7048 dpurdie 1593
     * @return A collection of packages that actively 'use' the specified package
1594
 
1595
     */
7079 dpurdie 1596
    private ArrayList<Package> usedByAnyPackages(Package pkg, ArrayList<Package> pkgCollection) {
7048 dpurdie 1597
 
1598
        ArrayList<Package> usedBy = new ArrayList<Package>();
1599
 
7070 dpurdie 1600
        for (Iterator<Package> it = pkgCollection.iterator(); it.hasNext(); )
7048 dpurdie 1601
        {
1602
            Package p = it.next();
1603
 
7079 dpurdie 1604
            for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
7048 dpurdie 1605
            {
7079 dpurdie 1606
                String alias = it2.next();
1607
                if (  pkg.mAlias.compareTo( alias ) == 0  ) {
1608
                    usedBy.add(p);
1609
                    break;
6914 dpurdie 1610
                }
1611
            }
7048 dpurdie 1612
        }
1613
 
1614
        return usedBy;
6914 dpurdie 1615
    }
1616
 
1617
    /** Determine if a given PVID is a member of the current release.
1618
     *  Used to determine if a package dependency is out of date
1619
     * 
1620
     * @param dpvId
1621
     * @return true - specified pvid is a full member of the Release
1622
     */
1623
    private boolean isInRelease(Integer dpvId) {
1624
 
7048 dpurdie 1625
        boolean inRelease = false;
6914 dpurdie 1626
 
7048 dpurdie 1627
        for ( Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1628
        {
7048 dpurdie 1629
            Package p = it.next();
6914 dpurdie 1630
 
7048 dpurdie 1631
            if ( p.mId == dpvId )
6914 dpurdie 1632
            {
7048 dpurdie 1633
                inRelease = ! p.mIsNotReleased;
6914 dpurdie 1634
                break;
1635
            }
1636
        }
7048 dpurdie 1637
        return inRelease;
6914 dpurdie 1638
    }
1639
 
1640
 
1641
    /**reports what change in build exceptions happens as part of planRelease
1642
     */
1643
    public void reportChange() throws SQLException, Exception
1644
    {
1645
        int counter = 0;
1646
        for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1647
        {
1648
            BuildExclusion buildExclusion = it.next();
1649
 
1650
            if ( !buildExclusion.isProcessed() )
1651
            {
7032 dpurdie 1652
                if (buildExclusion.isImported() && ! buildExclusion.isARootCause() ) {
1653
                    // Remove from the exclusion list
1654
                    buildExclusion.includeToBuild(mReleaseManager, mBaseline);
7048 dpurdie 1655
                    mLogger.error("reportChange remove unused exclusion: {}", buildExclusion.info());
7032 dpurdie 1656
                } else {
1657
                    // Exclude and notify
1658
                    buildExclusion.excludeFromBuild(mReleaseManager, mBaseline);
7071 dpurdie 1659
                    buildExclusion.email(this, mPackageCollectionAll);
7032 dpurdie 1660
                    counter++;
1661
                }
6914 dpurdie 1662
            }
1663
        }
7048 dpurdie 1664
        mLogger.error("reportChange exclusion count: {}", counter);
6914 dpurdie 1665
    }
1666
 
1667
    /**reports the build plan
1668
     */
1669
    public void reportPlan() throws SQLException, Exception
1670
    {
1671
        mReleaseManager.reportPlan(mRtagId, mBuildOrder);
1672
    }
1673
 
1674
    /**Returns the first build file from the collection
1675
     * The build file will be flagged as empty if none exists
1676
     */
1677
    public BuildFile getFirstBuildFileContent()
1678
    {
1679
        mLogger.debug("getFirstBuildFileContent");
1680
 
1681
        mBuildIndex = -1;
1682
        return getNextBuildFileContent();
1683
    }
1684
 
1685
    /**Returns next build file from the collection
1686
     * The build file will be flagged as empty if none exists
1687
     */
1688
    public BuildFile getNextBuildFileContent()
1689
    {
1690
        mLogger.debug("getNextBuildFileContent");
1691
        BuildFile retVal = null;
1692
 
1693
        try
1694
        {
1695
            mBuildIndex++;
1696
            retVal = mBuildCollection.get( mBuildIndex );
1697
        }
1698
        catch( IndexOutOfBoundsException e )
1699
        {
1700
            // Ignore exception. retVal is still null.
1701
        }
1702
 
1703
        if (retVal == null)
1704
        {
1705
            retVal = new BuildFile();
1706
        }
1707
 
7048 dpurdie 1708
        mLogger.debug("getNextBuildFileContent returned {}", retVal.state.name() );
6914 dpurdie 1709
        return retVal;
1710
    }
1711
 
1712
 
1713
    /**collects meta data associated with the baseline
1714
     * this is sufficient to send an indefinite pause email notification 
1715
     *  
1716
     * Escrow: Used once to collect information about the SBOM and associated Release 
1717
     *         mBaseline is an SBOMID 
1718
     * Daemon: Used each build cycle to refresh the information 
1719
     *          mBaseline is an RTAGID
1720
     */
1721
    public void collectMetaData() throws SQLException, Exception
1722
    {
1723
        Phase phase = new Phase("cmd");
7048 dpurdie 1724
        mLogger.debug("collectMetaData mDaemon {}", mDaemon);
6914 dpurdie 1725
 
1726
        try
1727
        {
1728
            phase.setPhase("connect");
1729
            mReleaseManager.connect();
1730
 
1731
            if (! mDaemon)
1732
            {
1733
                mSbomId = mBaseline;
1734
                phase.setPhase("queryRtagIdForSbom");
1735
                mRtagId = mReleaseManager.queryRtagIdForSbom(mBaseline);
1736
                if (mRtagId == 0)
1737
                {
7033 dpurdie 1738
                    mLogger.error("SBOM does not have a matching Release. Cannot be used as a base for an Escrow"); 
6914 dpurdie 1739
                    throw new Exception("rtagIdForSbom show stopper. SBOM does not have an associated Release");
1740
                }
1741
            }
1742
 
1743
            phase.setPhase("queryReleaseConfig");
1744
            mReleaseManager.queryReleaseConfig(mRtagId);
1745
 
1746
            if (mDaemon)
1747
            {
1748
                phase.setPhase("queryMailServer");
1749
                setMailServer(mReleaseManager.queryMailServer());
1750
                phase.setPhase("queryMailSender");
1751
                setMailSender(mReleaseManager.queryMailSender());
1752
                phase.setPhase("queryGlobalAddresses");
1753
                setMailGlobalTarget(mReleaseManager.queryGlobalAddresses());
1754
                phase.setPhase("queryProjectEmail");
1755
                mMailGlobalCollection = mReleaseManager.queryProjectEmail(mBaseline);
1756
                phase.setPhase("mMailGlobalTarget");
1757
                mMailGlobalCollection.add(0,getMailGlobalTarget());
1758
            }
1759
            phase.setPhase("queryBaselineName");
1760
            mBaselineName = mReleaseManager.queryBaselineName(mBaseline);
1761
            phase.setPhase("Done");
1762
        }
1763
        finally
1764
        {
1765
            // this block is executed regardless of what happens in the try block
1766
            // even if an exception is thrown
1767
            // ensure disconnect
1768
            mReleaseManager.disconnect();
1769
        }
1770
    }
1771
 
1772
    /**
1773
     * Find Package by package alias
7070 dpurdie 1774
     * Searches the released package collection
6914 dpurdie 1775
     * @param   alias               - alias of package to locate
1776
     * @return  Package with the matching mAlias or NULL_PACKAGE if no package has the mAlias
1777
     */
1778
    public Package findPackage(String alias)
1779
    {
1780
        mLogger.debug("findPackage");
1781
 
1782
        Package retVal = mReleaseManager.findPackage(alias, mPackageCollection);
1783
 
7048 dpurdie 1784
        mLogger.info("findPackage returned {}", retVal.mName);
6914 dpurdie 1785
        return retVal;
1786
    }
7070 dpurdie 1787
 
6914 dpurdie 1788
    /**
7079 dpurdie 1789
     * Sets the mBuildFile to the specified value for the package
1790
     * Does not handle dependent packages - this will be done later  
7048 dpurdie 1791
     *  
7032 dpurdie 1792
     * @param p             The package being excluded 
1793
     * @param rootPvId      The PVID of the package that is causing the exclusion. Null or -ve values are special
1794
     *                      This package is the root cause, -2: Excluded by Ripple Stop 
1795
     * @param rootCause     Text message. Max 50 characters imposed by RM database 
7079 dpurdie 1796
     * @param reason        New value for mBuildFile
6914 dpurdie 1797
     */
7079 dpurdie 1798
    private void rippleBuildExclude(Package p, int rootPvId, String rootCause, int reason )
6914 dpurdie 1799
    {
1800
        mLogger.debug("rippleBuildExclude");
7048 dpurdie 1801
 
6914 dpurdie 1802
        if ( p.mBuildFile == 0 || p.mBuildFile == 1 )
1803
        {
7079 dpurdie 1804
            p.mBuildFile = reason;
7048 dpurdie 1805
            mLogger.info("rippleBuildExclude set mBuildFile to -5 for package {}", p.mAlias );
7079 dpurdie 1806
 
1807
            //  Scan the complete collection looking for a matching item
1808
            //  If found, process it, else add it (unprocessed)
1809
            boolean found = false;
1810
            for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1811
            {
1812
                BuildExclusion buildExclusion = it.next();
6914 dpurdie 1813
 
7079 dpurdie 1814
                if ( buildExclusion.compare(p.mId, rootPvId, rootCause))
1815
                {
1816
                    buildExclusion.setProcessed();
1817
                    found = true;
1818
                    break;
1819
                }
6914 dpurdie 1820
            }
7079 dpurdie 1821
 
1822
            if (!found)
6914 dpurdie 1823
            {
7079 dpurdie 1824
                // Entry not found in the mBuildExclusionCollection
1825
                // Mark all occurrences for this package as processed
1826
                // These will be superseded by a new build exclusion entry
6914 dpurdie 1827
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1828
                {
1829
                    BuildExclusion buildExclusion = it.next();
1830
 
7079 dpurdie 1831
                    if ( buildExclusion.compare(p.mId))
6914 dpurdie 1832
                    {
7032 dpurdie 1833
                        buildExclusion.setProcessed();
6914 dpurdie 1834
                    }
1835
                }
1836
 
7079 dpurdie 1837
                BuildExclusion buildExclusion = new BuildExclusion(p.mId, rootPvId, rootCause, p.mTestBuildInstruction);
6914 dpurdie 1838
 
7079 dpurdie 1839
                //
1840
                //  Add the new build exclusion to a list
1841
                //    Either the default list or a user-specified list
1842
                mBuildExclusionCollection.add(buildExclusion);
6914 dpurdie 1843
            }
7079 dpurdie 1844
        }
6914 dpurdie 1845
 
7079 dpurdie 1846
        mLogger.info("rippleBuildExclude set {} {}", p.mAlias, p.mBuildFile);
6914 dpurdie 1847
    }
1848
 
1849
    /**Simple XML string escaping
1850
     * 
1851
     * @param xml		- String to escape
1852
     * @return		- A copy of the string with XML-unfriendly characters escaped 
1853
     */
1854
    public static String escapeXml( String xml )
1855
    {
1856
        xml = xml.replaceAll("&", "&amp;");
1857
        xml = xml.replaceAll("<", "&lt;");
1858
        xml = xml.replaceAll(">", "&gt;");
1859
        xml = xml.replaceAll("\"","&quot;");
1860
        xml = xml.replaceAll("'", "&apos;");
1861
        xml = xml.replaceAll("\\$", "\\$\\$");
1862
 
1863
        return xml;
1864
    }
1865
 
1866
    /** Quote a string or a string pair
1867
     *  If two strings are provided, then they will be joined with a comma.
1868
     *   
1869
     * @param text		- First string to quote
1870
     * @param text2		- Optional, second string
1871
     * @return A string of the form 'text','text2'
1872
     */
1873
    public static String quoteString(String text, String text2)
1874
    {
1875
        String result;
1876
        result =  "\'" + text + "\'";
1877
        if (text2 != null )
1878
        {
1879
            result +=  ",\'" + text2 + "\'";  
1880
        }
1881
        return result;
1882
    }
1883
 
1884
    /** Generate build file information
1885
     * 
1886
     */
1887
    private void generateBuildFiles() 
1888
    {
1889
 
1890
        // persist the build files
1891
        boolean allProcessed = false;
1892
        int buildFile = 1;
1893
        StringBuilder rawData = new StringBuilder();
1894
        StringBuilder setUp = new StringBuilder();
1895
 
1896
        mLogger.debug("generateBuildFiles");
1897
 
1898
        if ( mDaemon )
1899
        {
1900
            // all interesting packages in daemon mode match the following filter
1901
            buildFile = 3;
1902
        }
1903
 
1904
        //-----------------------------------------------------------------------
1905
        //    Generate the build file
1906
        do
1907
        {
1908
            BuildFile buildEntry = new  BuildFile();
1909
            buildEntry.state = BuildFileState.Dummy;
1910
            XmlBuilder xml = generateBuildFileHeader();
1911
 
1912
 
1913
            //	Generate properties for each package in this build level or lower build levels
1914
            //	The properties link the packageAlias to the PackageName and PackageVersion
1915
            //
1916
            //	[DEVI 54816] In escrow mode all unreproducible packages are included 
7070 dpurdie 1917
            for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1918
            {
1919
                Package p = it.next();
1920
 
1921
                if ( ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) ) || ( !mDaemon && p.mBuildFile == -2 ) )
1922
                {
1923
                    xml.addProperty(p.mAlias, p.mName + " " + p.mVersion + p.mExtension);
1924
                }
1925
            }
1926
 
1927
            //	UTF Support
1928
            //	Insert additional info into the build file to provide extra checking
1929
            //
7048 dpurdie 1930
            if ( ! mReleaseManager.mUseDatabase )
6914 dpurdie 1931
            {
1932
                // UTF Support
1933
                // Insert per-package planning information
1934
                //
7070 dpurdie 1935
                xml.addComment("mPackageCollection");
1936
                for (Iterator<Package> it = mPackageCollection.iterator(); it.hasNext(); )
6914 dpurdie 1937
                {
1938
                    Package p = it.next();
1939
                    generatePackageInfo(xml, p);
1940
                }
1941
 
7070 dpurdie 1942
                xml.addComment("mPackageCollectionWip");
1943
                for (Iterator<Package> it = mPackageCollectionWip.iterator(); it.hasNext(); )
1944
                {
1945
                    Package p = it.next();
1946
                    if (p.mIsNotReleased )
1947
                        generatePackageInfo(xml, p);
1948
                }
1949
 
1950
                xml.addComment("mPackageCollectionTest");
1951
                for (Iterator<Package> it = mPackageCollectionTest.iterator(); it.hasNext(); )
1952
                {
1953
                    Package p = it.next();
1954
                    if (p.mIsNotReleased )
1955
                        generatePackageInfo(xml, p);
1956
                }
1957
 
1958
                xml.addComment("mPackageCollectionTestRipple");
1959
                for (Iterator<Package> it = mPackageCollectionRipple.iterator(); it.hasNext(); )
1960
                {
1961
                    Package p = it.next();
1962
                    if (p.mIsNotReleased )
1963
                        generatePackageInfo(xml, p);
1964
                }
1965
 
6914 dpurdie 1966
                // UTF Support
1967
                // Insert build exclusion information
1968
                xml.addComment("mBuildExclusionCollection");
1969
                for (Iterator<BuildExclusion> it = mBuildExclusionCollection.iterator(); it.hasNext(); )
1970
                {
1971
                    BuildExclusion buildExclusion = it.next();
7079 dpurdie 1972
                    //if (!buildExclusion.isProcessed())
6914 dpurdie 1973
                    {
1974
                        xml.addComment(buildExclusion.info());
1975
                    }
1976
                }
7080 dpurdie 1977
            }
1978
 
1979
            // UTF Support (Also while trailing the changes)
1980
            // Insert build Plan
1981
            if (mDaemon)
1982
            {
1983
                xml.addComment("mBuildOrder");
1984
                for (Iterator<PlannedPackage> it = mBuildOrder.iterator(); it.hasNext(); )
6914 dpurdie 1985
                {
7080 dpurdie 1986
                    PlannedPackage p = it.next();
1987
                    String comment =
1988
                            "pvid="+ p.mPkg.mId +
1989
                            " order=" + p.mBuildLevel +
1990
                            " time=" + p.mPkg.mBuildTime +
1991
                            " name=\"" + p.mPkg.mAlias + "\"";
1992
                    xml.addComment(comment);
6914 dpurdie 1993
                }
1994
            }
1995
 
1996
            //  Generate Taskdef information
1997
            generateTaskdef(xml);
1998
 
1999
            //
2000
            //  Insert known Machine Information
2001
            //  Escrow usage: 
2002
            //      Map machType to machClass
2003
            //  Also serves as a snapshot of the required build configuration
2004
            //  ie: machine types and buildfilters
2005
            //
2006
            if (!mDaemon)
2007
            {
2008
                generateMachineInfo(xml, null);
2009
            }
2010
 
2011
            //
2012
            //	Generate target rules for each package to be built within the current build file
2013
            //
2014
            boolean daemonHasTarget = false;
2015
 
7048 dpurdie 2016
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2017
            {
2018
                Package p = it.next();
2019
 
2020
                if ( p.mBuildFile > 0 && p.mBuildFile <= buildFile )
2021
                {
2022
                    generateTarget(xml, buildEntry, p, buildFile);
2023
 
2024
                    if ( p.mBuildFile == 1 )
2025
                    {
2026
                        daemonHasTarget = true;
2027
 
2028
                        // Retain information about the target package
2029
                        buildEntry.mPkgId = p.mPid;
2030
                        buildEntry.mPvId = p.mId;
2031
                    }
2032
                }
2033
 
2034
                //	Generate escrow extraction commands
2035
                //	Only done on the first pass though the packages
2036
                //
2037
                if ( !mDaemon && buildFile == 1 )
2038
                {
2039
                    setUp.append("jats jats_vcsrelease -extractfiles"
2040
                                + " \"-label=" + p.mVcsTag + "\""
2041
                                + " \"-view=" + p.mAlias + "\""
2042
                                + " -root=. -noprefix"
2043
                                + mlf );
2044
                }
2045
 
2046
                //	Generate escrow raw CSV data
2047
                //	Note: I don't think this data is used at all
2048
 
2049
                if ( !mDaemon && ( p.mBuildFile == buildFile))
2050
                {
2051
                    StringAppender machines = new StringAppender(",");
2052
                    for (Iterator<BuildStandard> it1 = p.mBuildStandardCollection.iterator(); it1.hasNext();)
2053
                    {
2054
                        BuildStandard bs = it1.next();
2055
                        machines.append(bs.mMachClass);
2056
                    }
2057
 
2058
                    rawData.append(p.mAlias + "," +
2059
                                    buildFile + "," +
2060
                                    machines +
2061
                                    mlf);
2062
                }
2063
            }
2064
 
2065
            if ( mDaemon && !daemonHasTarget )
2066
            {
2067
                // must have AbtTestPath, AbtSetUp, AbtTearDown, and AbtPublish targets
2068
                XmlBuilder target = xml.addNewElement("target");
2069
                target.addAttribute("name", "AbtTestPath");
2070
 
2071
                target = xml.addNewElement("target");
2072
                target.addAttribute("name", "AbtSetUp");
2073
 
2074
                target = xml.addNewElement("target");
2075
                target.addAttribute("name", "AbtTearDown");
2076
 
2077
                target = xml.addNewElement("target");
2078
                target.addAttribute("name", "AbtPublish");
2079
            }
2080
 
2081
            generateDefaultTarget( xml, buildFile);
2082
 
2083
            //	Convert the Xml structure into text and save it in the build file
2084
            //	Add this build file to the mBuildCollection
2085
            buildEntry.content = mXmlHeader + xml.toString();
2086
            mBuildCollection.add(buildEntry);
2087
 
2088
            // are more build files required
2089
            allProcessed = true;
2090
 
2091
            if (!mDaemon)
2092
            {
2093
                // this is escrow mode centric
7048 dpurdie 2094
                for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2095
                {
2096
                    Package p = it.next();
2097
 
2098
                    if ( p.mBuildFile > buildFile )
2099
                    {
2100
                        // more build files are required
2101
                        allProcessed = false;
7048 dpurdie 2102
                        mLogger.info("planRelease reiterating package has no build requirement {} {} {}",p.mName, p.mBuildFile,  buildFile);
6914 dpurdie 2103
                        break;
2104
                    }
2105
                } 
2106
 
2107
                buildFile++;
2108
            }
2109
 
2110
        } while( !allProcessed );
2111
 
2112
        //	Save additional escrow data
2113
        if ( !mDaemon )
2114
        {
2115
            mEscrowSetup = setUp.toString();
2116
            mEscrowRawData = rawData.toString();
2117
        }
2118
    }
2119
 
2120
    /**returns a build file header for the mBaseline
2121
     */
2122
    private XmlBuilder generateBuildFileHeader()
2123
    {
2124
        mLogger.debug("generateBuildFileHeader");
2125
        XmlBuilder element = new XmlBuilder("project");
2126
 
2127
        element.addAttribute("name", "mass");
2128
        element.addAttribute("default", "full");
2129
        element.addAttribute("basedir", ".");
2130
 
2131
        if ( mDaemon )
2132
        {
2133
            element.addProperty("abt_mail_server", getMailServer());
2134
            element.addProperty("abt_mail_sender", getMailSender()); 
2135
            element.addProperty("abt_rtag_id", mBaseline);
2136
            element.addProperty("abt_daemon", mReleaseManager.currentTimeMillis());
2137
            element.makePropertyTag("abt_packagetarball", true);
2138
            element.makePropertyTag("abt_usetestarchive", !ReleaseManager.getUseMutex());
2139
 
7048 dpurdie 2140
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2141
            {
2142
                Package p = it.next();
2143
 
2144
                if ( p.mBuildFile == 1 )
2145
                {
2146
                    element.addProperty("abt_package_name", p.mName);
2147
                    element.addProperty("abt_package_version", p.mVersion + p.mExtension);
2148
                    element.addProperty("abt_package_extension", p.mExtension);
2149
                    element.addProperty("abt_package_location", getBuildLocation(p));
2150
                    element.addProperty("abt_package_ownerlist", p.emailInfoNonAntTask(this));
2151
                    element.addProperty("abt_package_build_info", buildInfoText(p));
2152
 
2153
                    // depends in the form 'cs','25.1.0000.cr';'Dinkumware_STL','1.0.0.cots'
2154
                    StringAppender depends = new StringAppender(";");
2155
 
2156
                    for (Iterator<Package> it3 = p.mPackageDependencyCollection.iterator(); it3.hasNext(); )
2157
                    {
2158
                        Package depend = it3.next();
2159
                        depends.append( quoteString(depend.mName, depend.mVersion + depend.mExtension) );
2160
                    }
2161
 
2162
                    element.addProperty("abt_package_depends", depends.toString());
2163
                    element.addProperty("abt_is_ripple", p.mDirectlyPlanned ? "0" : "1");
2164
                    element.addProperty("abt_build_reason", p.mBuildReason.toString());
2165
                    element.addProperty("abt_package_version_id", p.mId);
2166
                    element.addProperty("abt_does_not_require_source_control_interaction", ! p.mRequiresSourceControlInteraction ? "true" : "false" );
2167
                    element.addProperty("abt_test_build_instruction", p.mTestBuildInstruction);
2168
                }
2169
            }
2170
        }
2171
        else
2172
        {
2173
            //    Escrow Mode
2174
            element.addProperty("abt_rtag_id", mRtagId);
2175
            element.addProperty("abt_sbom_id", mSbomId);
2176
        }
2177
 
2178
        element.addProperty("abt_release", escapeXml(mBaselineName));
2179
        element.addProperty("abt_buildtool_version", mReleaseManager.getMajorVersionNumber() );
2180
 
2181
        element.addNewElement("condition")
2182
        .addAttribute("property", "abt_family")
2183
        .addAttribute("value", "windows")
2184
        .addNewElement("os")
2185
        .addAttribute("family", "windows");
2186
        element.addProperty("abt_family", "unix");
2187
 
2188
        return element;
2189
    }
2190
 
2191
    /** Add task def XML items taskdef for the abt ant task
2192
     * @param xml 	- xml item to extend
2193
     */
2194
    private void generateTaskdef(XmlBuilder xml)
2195
    {
2196
        mLogger.debug("generateTaskdef");
2197
        xml.addNewElement("taskdef")
2198
        .addAttribute("name", "abt")
2199
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABT");
2200
 
2201
        xml.addNewElement("taskdef")
2202
        .addAttribute("name", "abtdata")
2203
        .addAttribute("classname", "com.erggroup.buildtool.abt.ABTData");
2204
    }
2205
 
2206
    /** returns the command abtdata items
2207
     *  <br>Common machine information
2208
     *  <br>Common email address
2209
     *  
2210
     *  
2211
     *  @param	xml - Xml element to extend   
2212
     *  @param    p - Package (May be null)
2213
     */
2214
    private void generateMachineInfo(XmlBuilder xml, Package p)
2215
    {
2216
        XmlBuilder element = xml.addNewElement("abtdata");
2217
        element.addAttribute("id", "global-abt-data");
2218
 
2219
        //
2220
        //  Iterate over all the machines and create a nice entry
2221
        //
2222
        for (Iterator<ReleaseConfig> it = mReleaseManager.mReleaseConfigCollection.mReleaseConfig.iterator(); it.hasNext(); )
2223
        {
2224
            ReleaseConfig rc = it.next();
2225
            element.addElement(rc.getMachineEntry());
2226
        }
2227
 
2228
        //
2229
        //  Now the email information
2230
        //
2231
        if ( p != null)
2232
        {
2233
            p.emailInfo(this, element);
2234
        }
2235
    }
2236
 
2237
    /** Generate package information
2238
     *  Only when running unit tests
2239
     *  
2240
     * @param xml	- An xml element to append data to
2241
     * @param p	- Package to process
2242
     */
2243
    private void generatePackageInfo (XmlBuilder xml, Package p)
2244
    {
7071 dpurdie 2245
        StringBuilder comment = new StringBuilder();
2246
        StringBuilder deps = new StringBuilder();
2247
 
7051 dpurdie 2248
        String joiner = "";
2249
        for (Iterator<String> it2 = p.mDependencyCollection.iterator(); it2.hasNext(); )
2250
        {
2251
            String alias = it2.next();
7071 dpurdie 2252
            deps.append(joiner).append(alias); 
7051 dpurdie 2253
            joiner = ",";
2254
        }
2255
 
7071 dpurdie 2256
        comment.append("pvid=").append(p.mId);
2257
        comment.append(" name=").append('"').append(p.mAlias).append('"');
2258
        comment.append(" reason=").append(p.mNoBuildReason);
2259
        comment.append(" buildFile=").append(p.mBuildFile);
2260
        comment.append(" directlyPlanned=").append(p.mDirectlyPlanned);
2261
        comment.append(" indirectlyPlanned=").append(p.mIndirectlyPlanned);
2262
        comment.append(" depends=[").append(deps).append("]");
6914 dpurdie 2263
 
7071 dpurdie 2264
        xml.addComment(comment.toString());            
6914 dpurdie 2265
    }
2266
 
2267
    /**returns an ant target for the passed Package
2268
     * in daemon mode:
2269
     *  packages are categorized with one of three mBuildFile values:
2270
     *   1 the package to be built by this buildfile
2271
     *   2 the packages with a future build requirement
2272
     *   3 the packages with no build requirement
2273
     *  the returned target depends on this categorization and will have
2274
     *   1 full abt info
2275
     *   2 full dependency info to determine future build ordering but no abt info (will not build this package)
2276
     *   3 only a name attribute (will not build this package)
2277
     * in escrow mode:
2278
     *  if the passed Package's mBuildFile is different (less than) the passed build file,
2279
     *  the returned target have only a name attribute (will not build this package)
2280
     *   
2281
     * @param xml - Xml element to extend
2282
     * @param buildEntry - Record build type (dummy/generic/not generic)
2283
     * @param p - Package to process
2284
     * @param buildFile - buildfile level being processed
2285
     */
2286
    private void generateTarget(XmlBuilder xml, BuildFile buildEntry, Package p, int buildFile)
2287
    {
2288
        mLogger.debug("generateTarget");
2289
 
2290
        //---------------------------------------------------------------------
2291
        //  Generate the AbtData - common machine and email information
2292
        //  Only used by the daemon builds
2293
        //
2294
        if ( mDaemon && p.mBuildFile == 1 )
2295
        {
2296
            generateMachineInfo(xml, p );
2297
        }
2298
 
2299
        //-------------------------------------------------------------------------
2300
        //  Generate the <target name=... /> construct
2301
        //  There are two types
2302
        //      1) Simple dummy place holder. Just has the PackageName.PackageExt
2303
        //      2) Full target. Has all information to build the package including
2304
        //              AbtSetUp, AbtTearDown and AbtPublish targets
2305
        //
2306
 
2307
        if ( !mDaemon && ( p.mBuildFile < buildFile ) )
2308
        {
2309
            XmlBuilder target = xml.addNewElement("target");
2310
            target.addAttribute("name", p.mAlias);
2311
        }
2312
        else
2313
        {
2314
            if (!mDaemon) 
2315
            {
2316
                //  Escrow Only:
2317
                //  Generate the 'wrapper' target
2318
                //  This is used to ensure that the required dependencies have been built - I think
2319
                //
2320
                StringAppender dependList = new StringAppender(",");
2321
                if ( !p.mPackageDependencyCollection.isEmpty() )
2322
                {
2323
                    for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2324
                    {
2325
                        Package dependency = it.next();
2326
                        if ( !mDaemon && dependency.mBuildFile == -2 )
2327
                        {
2328
                            // ignore targets which build in foreign environments in escrow mode
2329
                            continue;
2330
                        }
2331
                        dependList.append(dependency.mAlias);
2332
                    }
2333
                }
2334
 
2335
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2336
                target.addAttribute("name", p.mAlias + ".wrap");
2337
 
2338
                if (dependList.length() > 0)
2339
                {
2340
                    target.addAttribute("depends", dependList.toString() );
2341
                }
2342
 
2343
                if ( !mDaemon )
2344
                {
2345
                    boolean hasDependenciesBuiltInThisIteration = false;
2346
                    if ( ( !p.mPackageDependencyCollection.isEmpty()) )
2347
                    {
2348
                        for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2349
                        {
2350
                            Package dependency = it.next();
2351
 
2352
                            if ( dependency.mBuildFile == buildFile )
2353
                            {
2354
                                hasDependenciesBuiltInThisIteration = true;
2355
                                break;
2356
                            }
2357
                        }
2358
                    }
2359
 
2360
                    if ( hasDependenciesBuiltInThisIteration )
2361
                    {
2362
                        XmlBuilder condition = target.addNewElement("condition");
2363
                        condition.addAttribute("property",  p.mAlias + ".build");
2364
 
2365
                        XmlBuilder and = condition.addNewElement("and");
2366
 
2367
                        for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2368
                        {
2369
                            Package dependency = it.next();
2370
 
2371
                            if ( dependency.mBuildFile == buildFile )
2372
                            {
2373
                                XmlBuilder or = and.addNewElement("or");
2374
 
2375
                                XmlBuilder equal1 = or.addNewElement("equals");
2376
                                equal1.addAttribute("arg1", "${" + dependency.mAlias + ".res}");
2377
                                equal1.addAttribute("arg2", "0");
2378
 
2379
                                XmlBuilder equal2 = or.addNewElement("equals");
2380
                                equal2.addAttribute("arg1", "${" + dependency.mAlias + ".res}");
2381
                                equal2.addAttribute("arg2", "257");
2382
                            }
2383
                        }
2384
                    }
2385
                    else
2386
                    {
2387
                        target.addProperty(p.mAlias + ".build", "");
2388
                    }
2389
                }
2390
            }
2391
 
2392
 
2393
            //
2394
            //  Generate the 'body' of the target package
2395
            //  Escrow Mode: Always
2396
            //  Daemon Mode: Only for the one target we are building
2397
            //                  Simplifies the XML
2398
            //                  Reduces noise in the logs
2399
            //              Don't add target dependencies. 
2400
            //                  We are only building one target and the 
2401
            //                  dependency management has been done way before now.
2402
            //                  All it does is makes the logs noisy.
2403
            //
2404
            if ( ( mDaemon && p.mBuildFile == 1 ) || !mDaemon )
2405
            {
2406
                XmlBuilder target = xml.addNewElement("target").isExpanded();
2407
                target.addAttribute("name", p.mAlias);
2408
 
2409
                if ( !mDaemon )
2410
                {
2411
                    target.addAttribute("depends",  p.mAlias + ".wrap");
2412
                    target.addAttribute("if",p.mAlias + ".build");
2413
                }
2414
 
2415
                if ( mDaemon && p.mBuildFile == 1 )
2416
                {
2417
                    target.addProperty(p.mAlias + "pkg_id",p.mPid);
2418
                    target.addProperty(p.mAlias + "pv_id",p.mId);
2419
                }
2420
 
2421
                target.addProperty(p.mAlias + "packagename",p.mName);        		
2422
                target.addProperty(p.mAlias + "packageversion",p.mVersion);
2423
                target.addProperty(p.mAlias + "packageextension",p.mExtension);
2424
                target.addProperty(p.mAlias + "packagevcstag",p.mVcsTag);
2425
 
2426
                target.makePropertyTag(p.mAlias + "directchange", p.mDirectlyPlanned); 
2427
                target.makePropertyTag(p.mAlias + "doesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2428
 
2429
                buildEntry.state = BuildFile.BuildFileState.NonGeneric;
2430
                if ( p.isGeneric() )
2431
                {
2432
                    buildEntry.state = BuildFile.BuildFileState.Generic;
2433
                    target.makePropertyTag(p.mAlias + "generic", true); 
2434
                }
2435
 
2436
                target.addProperty(p.mAlias + "loc", getBuildLocation(p));
2437
                target.makePropertyTag(p.mAlias + "unittests", p.mHasAutomatedUnitTests && mDaemon);
2438
 
2439
                //    Add our own task and associated information
2440
                //
2441
                XmlBuilder abt = target.addNewElement("abt").isExpanded();
2442
 
2443
                for (Iterator<Package> it = p.mPackageDependencyCollection.iterator(); it.hasNext(); )
2444
                {
2445
                    Package dependency = it.next();
2446
                    XmlBuilder depend = abt.addNewElement("depend");
2447
                    depend.addAttribute("package_alias", "${" + dependency.mAlias + "}");
2448
                }
2449
 
2450
                buildInfo(abt,p);
2451
 
2452
                if ( mDaemon && p.mBuildFile == 1 )
2453
                {
2454
                    //    AbtTestPath
2455
                    target = xml.addNewElement("target").isExpanded();
2456
                    target.addAttribute("name", "AbtTestPath");
2457
                    target.addProperty("AbtTestPathpackagevcstag", p.mVcsTag);
2458
                    target.addProperty("AbtTestPathpackagename", p.mName);
2459
                    abt = target.addNewElement("abt").isExpanded();
2460
                    buildInfo(abt, p);
2461
 
2462
 
2463
                    //    AbtSetUp
2464
                    target = xml.addNewElement("target").isExpanded();
2465
                    target.addAttribute("name", "AbtSetUp");
2466
                    target.addProperty("AbtSetUppackagevcstag", p.mVcsTag);
2467
                    target.addProperty("AbtSetUppackagename", p.mName);
2468
 
2469
                    abt = target.addNewElement("abt").isExpanded();
2470
                    buildInfo(abt, p);
2471
 
2472
                    //    AbtTearDown
2473
                    target = xml.addNewElement("target").isExpanded();
2474
                    target.addAttribute("name", "AbtTearDown");
2475
                    target.addProperty("AbtTearDownpackagevcstag", p.mVcsTag);
2476
                    target.addProperty("AbtTearDownpackagename", p.mName);
2477
                    target.addProperty("AbtTearDownpackageversion", p.mVersion);
2478
                    target.addProperty("AbtTearDownpackageextension", p.mExtension);
2479
                    target.makePropertyTag(p.mAlias + "generic", p.isGeneric());
2480
 
2481
                    abt = target.addNewElement("abt").isExpanded();
2482
                    buildInfo(abt, p);
2483
 
2484
 
2485
                    //  AbtPublish
2486
                    target = xml.addNewElement("target").isExpanded();
2487
                    target.addAttribute("name", "AbtPublish");
2488
 
2489
                    target.addProperty("AbtPublishpackagevcstag", p.mVcsTag);
2490
                    target.addProperty("AbtPublishpackagename", p.mName);
2491
                    target.addProperty("AbtPublishpackageversion", p.mVersion);
2492
                    target.addProperty("AbtPublishpackageextension", p.mExtension);
2493
                    target.makePropertyTag("AbtPublishdirectchange", p.mDirectlyPlanned);
2494
                    target.makePropertyTag("AbtPublishdoesnotrequiresourcecontrolinteraction", ! p.mRequiresSourceControlInteraction);
2495
                    target.makePropertyTag("AbtPublishgeneric", p.isGeneric());
2496
                    target.addProperty("AbtPublishloc", getBuildLocation(p));
2497
 
2498
                    abt = target.addNewElement("abt").isExpanded();
2499
                    buildInfo(abt, p);
2500
 
2501
                }
2502
            }
2503
        }
2504
    }
2505
 
2506
    /** Extends the xml object. Adds ant default target for the current build iteration
2507
     * @param xml - The XmlBuilder Object to extend
2508
     * @param buildFile - The current build file level. This differs for Daemon and Escrow mode. In Daemon mode it will not be a '1' 
2509
     */
2510
    private void generateDefaultTarget(XmlBuilder xml, int buildFile)
2511
    {
2512
        mLogger.debug("generateDefaultTarget");
2513
 
2514
        XmlBuilder target = xml.addNewElement("target").isExpanded();
2515
        target.addAttribute("name", "fullstart");
2516
 
2517
        if (buildFile == 1)
2518
        {
2519
            antEcho(target, "${line.separator}" + mAnyBuildPlatforms + "${line.separator}${line.separator}");
7048 dpurdie 2520
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2521
            {
2522
                Package p = it.next();
2523
 
2524
                if ( p.mBuildFile == -1 )
2525
                {
2526
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2527
                }
2528
            }
2529
 
2530
            antEcho(target, "${line.separator}" + mAssocBuildPlatforms + "${line.separator}${line.separator}");
7048 dpurdie 2531
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2532
            {
2533
                Package p = it.next();
2534
 
2535
                if ( p.mBuildFile == -2 )
2536
                {
2537
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2538
                }
2539
            }
2540
 
2541
            antEcho(target, "${line.separator}" + mNotInBaseline + "${line.separator}${line.separator}");
7048 dpurdie 2542
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2543
            {
2544
                Package p = it.next();
2545
 
2546
                if ( p.mBuildFile == -4 )
2547
                {
2548
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2549
                }
2550
            }
2551
 
2552
            antEcho(target, "${line.separator}" + mDependent + "${line.separator}${line.separator}");
7048 dpurdie 2553
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2554
            {
2555
                Package p = it.next();
2556
 
2557
                if ( p.mBuildFile == -5 )
2558
                {
2559
                    antEcho(target, "${line.separator}" + p.mAlias + "${line.separator}");
2560
                }
2561
            }
2562
        }
2563
 
2564
        if ( !mDaemon )
2565
        {
2566
            antEcho(target, "${line.separator}Build Started:${line.separator}${line.separator}");
2567
        }
2568
 
2569
        //
2570
        //	Create a comma separated list of all the required targets
2571
        //      Escrow : All packages
2572
        //      Daemon : Just the package being built
2573
        //
2574
        StringAppender dependList = new StringAppender(",");
2575
        dependList.append("fullstart");
7048 dpurdie 2576
        for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2577
        {
2578
            Package p = it.next();
2579
 
2580
            if ( ( p.mBuildFile > 0 ) && ( p.mBuildFile <= buildFile ) )
2581
            {
2582
                if ((mDaemon && p.mBuildFile == 1) || !mDaemon)
2583
                {
2584
                    dependList.append(p.mAlias);                    
2585
                }
2586
            }
2587
        }
2588
 
2589
        target = xml.addNewElement("target").isExpanded();
2590
        target.addAttribute("name", "full");
2591
        target.addAttribute("depends", dependList.toString());
2592
 
2593
        if ( !mDaemon )
2594
        {
2595
            antEcho(target, "${line.separator}Build Finished${line.separator}");
2596
        }
2597
    }
2598
 
2599
    /** Internal helper function to create an ant 'echo statement
2600
     *  Many of the parameters are fixed
2601
     */
2602
    private void antEcho( XmlBuilder xml, String message)
2603
    {
2604
        XmlBuilder msg = xml.addNewElement("echo");
2605
        msg.addAttribute("message", message);
2606
        msg.addAttribute("file", "publish.log");
2607
        msg.addAttribute("append", "true");
2608
    }
2609
 
2610
    /**sets the mIndirectlyPlanned true for the package and all dependent packages
2611
     */
2612
    private void rippleIndirectlyPlanned(Package p)
2613
    {
2614
        mLogger.debug("rippleIndirectlyPlanned");
2615
        if ( !p.mIndirectlyPlanned && p.mBuildFile == 0 )
2616
        {
2617
            p.mIndirectlyPlanned = true;
2618
 
7048 dpurdie 2619
            for (Iterator<Package> it = mPackageCollectionAll.iterator(); it.hasNext(); )
6914 dpurdie 2620
            {
2621
                Package pkg = it.next();
2622
 
2623
                if ( pkg != p )
2624
                {
2625
                    for (Iterator<Package> it2 = pkg.mPackageDependencyCollection.iterator(); it2.hasNext(); )
2626
                    {
2627
                        Package dependency = it2.next();
2628
 
2629
                        if ( dependency == p )
2630
                        {
2631
                            rippleIndirectlyPlanned( pkg );
2632
                            break;
2633
                        }
2634
                    }
2635
                }
2636
            }
2637
        }
7048 dpurdie 2638
        mLogger.info("rippleIndirectlyPlanned set {} {}", p.mName, p.mIndirectlyPlanned);    
6914 dpurdie 2639
    }
2640
 
2641
    /**accessor method
2642
     */
2643
    public String getEscrowSetUp()
2644
    {
2645
        mLogger.debug("getEscrowSetUp");
2646
        String retVal = mEscrowSetup;
2647
 
7048 dpurdie 2648
        mLogger.debug("getEscrowSetUp returned {}", retVal);
6914 dpurdie 2649
        return retVal;
2650
    }
2651
 
2652
    /**accessor method
2653
     */
2654
    public String getRawData()
2655
    {
2656
        mLogger.debug("getRawData");
2657
        String retVal = mEscrowRawData;
2658
 
7048 dpurdie 2659
        mLogger.debug("getRawData returned {}", retVal);
6914 dpurdie 2660
        return retVal;
2661
    }
2662
 
2663
    /**Get the build loc (location)
2664
     * This is package specific and will depend on the build mode (Escrow/Daemon)
2665
     * 
2666
     * @param	p - Package being built
2667
     * @return A string that describes the build location
2668
     */
2669
    private String getBuildLocation(Package p)
2670
    {
2671
        mLogger.debug("locationProperty");
2672
        String location = "";
2673
 
2674
        if (mDaemon)
2675
        {
2676
            // Daemon: Start in root of view/workspace
2677
            location += mBaseline;
2678
        }
2679
        else
2680
        {
2681
            // Escrow: mAlias used with jats -extractfiles -view
2682
            location += p.mAlias;
2683
        }
2684
 
2685
        //
2686
        //  Always use '/' as a path separator - even if user has specified '\'
2687
        //  Ant can handle it.
2688
        //
2689
        location = location.replace('\\', '/');
2690
        return location;
2691
    }
2692
 
2693
    /**Adds package build into as XML elements 
2694
     * @param	  xml 	- Xml element to extend
2695
     * @param   p       - Package to process
2696
     */
2697
    private void buildInfo(XmlBuilder xml, Package p)
2698
    {
2699
        mLogger.debug("buildInfo");
2700
 
2701
        //
2702
        // Create the xml build information
2703
        // <platform gbe_machtype="linux_i386" type="jats" arg="all"/>
2704
        //
2705
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext();)
2706
        {
2707
            BuildStandard bs = it.next();
2708
            bs.getBuildStandardXml(xml);
2709
        }
2710
    }
2711
 
2712
    /**returns the buildInfo as a single line of text
2713
     * Used for reporting purposes only
2714
     * @param   p       - Package to process
2715
     * 
2716
     */
2717
    public String buildInfoText(Package p)
2718
    {
2719
        mLogger.debug("buildInfoText");
2720
 
2721
        StringAppender result = new StringAppender (";");
2722
 
2723
        //
2724
        //  Create platform:standards
2725
        //      
2726
        for (Iterator<BuildStandard> it = p.mBuildStandardCollection.iterator(); it.hasNext(); )
2727
        {
2728
            BuildStandard bs = it.next();
2729
 
2730
            if ( bs.isActive() )
2731
            {
2732
                String info = bs.getBuildStandardText();
2733
                result.append(info);
2734
            }
2735
        }
2736
 
7048 dpurdie 2737
        mLogger.info("buildInfoText returned {}", result);
6914 dpurdie 2738
        return result.toString();
2739
    }
2740
 
2741
    /**prints to standard out in escrow mode only
2742
     * <br>Prints a title and information. The title is only printed once.
2743
     * 
2744
     * @param header - The message title to display, if printMessage is true
2745
     * @param text - A package name. Really just the 2nd line of the message
2746
     * @param printHeader -  Controls the printing of the message argument
2747
     */
2748
    private void standardOut(final String header, final String text, boolean printHeader)
2749
    {
2750
        mLogger.debug("standardOut");
2751
        if (!mDaemon)
2752
        {
2753
            if ( printHeader )
2754
            {
2755
                System.out.println(header);
2756
            }
2757
 
2758
            System.out.println(text);
2759
        }
2760
    }
2761
 
2762
 
2763
    /**
2764
     *  Email users about a rejected daemon instruction
2765
     *  @param  reason  - Reason for the rejection
2766
     *  @param  pkg     - Package to be affected by the instruction
2767
     *  
2768
     */
2769
    public void emailRejectedDaemonInstruction(String reason, Package p)
2770
    {
2771
        mLogger.debug("emailRejectedDaemonInstruction");
2772
 
2773
        //  Email Subject
2774
        String subject = "BUILD FAILURE of Daemon Instruction on package " + p.mAlias;
2775
 
2776
        // Email Body
2777
        String mailBody = "The build system reject the the Daemon Instruction";
2778
        mailBody += "<br>Reason: " + reason; 
2779
 
2780
        mailBody += "<p>Release: " + mBaselineName 
2781
                +  "<br>Package: " + p.mAlias 
2782
                +  "<br>Rm Ref: " + CreateUrls.generateRmUrl(getRtagId(), p.mId); 
2783
 
2784
        mailBody += "<p><hr>";
2785
 
2786
        String target = p.emailInfoNonAntTask(this);
2787
 
7048 dpurdie 2788
        mLogger.error("emailRejectedDaemonInstruction Server: {}", getMailServer());
2789
        mLogger.error("emailRejectedDaemonInstruction Sender: {}", getMailSender());
2790
        mLogger.error("emailRejectedDaemonInstruction Target: {}", target);
6914 dpurdie 2791
 
2792
        try
2793
        {
2794
            //    
7048 dpurdie 2795
            Smtpsend.send(getMailServer(),  // mailServer
2796
                    getMailSender(),        // source
2797
                    target,                 // target
2798
                    getMailSender(),        // cc
2799
                    null,                   // bcc
2800
                    subject,                // subject
2801
                    mailBody,               // body
2802
                    null                    // attachment
6914 dpurdie 2803
                    );
2804
        } catch (Exception e)
2805
        {
7048 dpurdie 2806
            mLogger.warn("Email Failure: emailRejectedDaemonInstruction:{}", e.getMessage());
6914 dpurdie 2807
        }
2808
    }
2809
 
2810
    /**
2811
     * @return the mMailServer
2812
     */
2813
    public String getMailServer() {
2814
        return mMailServer;
2815
    }
2816
 
2817
    /**
2818
     * @param mMailServer the mMailServer to set
2819
     */
2820
    public void setMailServer(String mMailServer) {
2821
        this.mMailServer = mMailServer;
2822
    }
2823
 
2824
    /**
2825
     * @return the mMailSender
2826
     */
2827
    public String getMailSender() {
2828
        return mMailSender;
2829
    }
2830
 
2831
    /**
2832
     * @param mMailSender the mMailSender to set
2833
     */
2834
    public void setMailSender(String mMailSender) {
2835
        this.mMailSender = mMailSender;
2836
    }
2837
 
2838
    /**
2839
     * @return the mMailGlobalTarget
2840
     */
2841
    public String getMailGlobalTarget() {
2842
        return mMailGlobalTarget;
2843
    }
2844
 
2845
    /**
2846
     * @param mMailGlobalTarget the mMailGlobalTarget to set
2847
     */
2848
    public void setMailGlobalTarget(String mMailGlobalTarget) {
2849
        this.mMailGlobalTarget = mMailGlobalTarget;
2850
    }
2851
 
2852
}