Subversion Repositories DevTools

Rev

Rev 7176 | Rev 7333 | 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.daemon;
2
 
3
import com.erggroup.buildtool.abt.BuildToolException;
4
import com.erggroup.buildtool.abt.RemoteExecution;
5
import com.erggroup.buildtool.abt.RemoteExecution.LogOutput;
6
import com.erggroup.buildtool.daemon.BuildThread;
7
import com.erggroup.buildtool.ripple.*;
8
import com.erggroup.buildtool.ripple.BuildFile.BuildFileState;
9
import com.erggroup.buildtool.ripple.Package;
10
import com.erggroup.buildtool.ripple.ReleaseManager.BuildResult;
11
import com.erggroup.buildtool.ripple.RunLevel.BuildState;
12
import com.erggroup.buildtool.smtp.CreateUrls;
13
import com.erggroup.buildtool.smtp.Smtpsend;
14
import com.erggroup.buildtool.utilities.*;
15
 
16
import java.io.BufferedReader;
17
import java.io.DataInputStream;
18
import java.io.File;
19
import java.io.FileInputStream;
20
import java.io.InputStreamReader;
21
import java.sql.SQLException;
22
import java.util.Iterator;
23
 
7033 dpurdie 24
import org.slf4j.Logger;
25
import org.slf4j.LoggerFactory;
6914 dpurdie 26
 
27
/**Master Thread sub component
28
 */
29
public class MasterThread extends BuildThread
30
{
31
 
32
    /**Logger
33
     * @attribute
34
     */
7033 dpurdie 35
    private static final Logger mLogger = LoggerFactory.getLogger(MasterThread.class);
6914 dpurdie 36
 
37
    /** Current BuildFile
38
     * 
39
     */
40
    private BuildFile mMasterBuildFile = new BuildFile();
41
 
42
    /** Measure the duration of the current build
43
     * 
44
     */
45
    private ElapseTime mBuildDuration = new ElapseTime();
46
 
47
    /**constructor
48
     * @param rtagId          - Identifies the Release
49
     * @param rconId          - Identifies the Controlling entry
50
     * @param releaseManager  - A ReleaseManager entry to use
51
     * @param unitTest        - Unit Test data 
52
     */
53
    public MasterThread(int rtagId, int rconId, ReleaseManager releaseManager, String unitTest)
54
    {
55
        super(rtagId, rconId, releaseManager, unitTest);
56
        mLogger.warn("MasterThread rtag_id " + rtagId + " rcon_id " + rconId);
57
    }
58
 
59
    /**implements the sequence diagrams coordinate slave threads, generate build files, allowed to proceed, check environment
60
     */
61
    public void run()
62
    {
63
        Integer id = Integer.valueOf(mRtagId);
64
        setName(id.toString());
65
        mLogger.warn("Master Thread run");
66
        boolean exit = false;
67
        mRippleEngine = new RippleEngine(mReleaseManager, mRtagId, true);
68
 
69
        while(!exit)
70
        {
71
            try
72
            {
7176 dpurdie 73
                mLogger.warn("run calling sleepCheck");
6914 dpurdie 74
                mPhase.setPhase("sleepCheck");
75
                sleepCheck();
76
 
7176 dpurdie 77
                mLogger.warn("run calling rippleEngine.collectMetaData");
6914 dpurdie 78
                mPhase.setPhase("collectMetaData", 600);
79
                mRippleEngine.collectMetaData();
80
 
81
                if ( Thread.currentThread().isInterrupted() )
82
                {
83
                    mLogger.warn("run is interrupted");
84
                    // unit test technique
85
                    throw new ExitException();
86
                }
87
 
88
                if ( mUnitTest.compareTo("unit test spawn thread") == 0)
89
                {
90
                    throw new Exception();
91
                }
92
 
93
                if ( !mUnitTest.startsWith("unit test check environment"))
94
                {
95
                    if ( mUnitTest.compareTo("unit test generate build files") != 0)
96
                    {
97
                        if ((mUnitTest.compareTo("unit test allowed to proceed") != 0) &&
98
                                (mUnitTest.compareTo("unit test not allowed to proceed") != 0) &&
99
                                (mUnitTest.compareTo("unit test exit") != 0))
100
                        {
101
                            //---------------------------------------------------------------
102
                            //  Wait for all Slaves to enter waiting or paused state
103
                            //      They may be building
104
                            //      They may be starting up
105
                            //
7176 dpurdie 106
                            mLogger.warn("run changing run level to WAITING (New) for rcon_id {}", mRconId);
6914 dpurdie 107
                            mPhase.setPhase("Wait for Slave Threads");
108
                            mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_WAITING);
109
 
110
                            while (true) 
111
                            {
112
                                StringBuilder waitList = new StringBuilder();
113
                                mLogger.info("run calling mReleaseManager.queryRunLevel");
114
                                mReleaseManager.queryRunLevel(mRtagId);
115
 
116
                                //	Process all run entries
117
 
118
                                for (Iterator<RunLevelData> it = mReleaseManager.mRunLevelCollection.iterator(); it.hasNext(); )
119
                                {
120
                                    RunLevelData rl = it.next();
121
 
122
                                    //
123
                                    // Only examine Slaves.
124
                                    // This is being run on a Master and at this point the Master is not waiting
125
                                    // If there are multiple (misconfigured) Masters, then we can get confused
126
                                    //
127
                                    // If I am no longer a Master we will process till the end of the build cycle
128
                                    // at which point it will be detected.
129
                                    //
130
                                    // If there are other Masters, then we assume that they are not waiting
131
                                    //
132
 
133
                                    // Ignore myself. I am not waiting. I am asking the questions
134
                                    if ( rl.get_rcon_id() == mRconId) {
135
                                        continue;
136
                                    }
137
 
138
                                    // Ignore other Master. They should not be waiting.
139
                                    if ( rl.isMaster()) {
140
                                        continue;
141
                                    }
142
 
143
                                    //
144
                                    // A slave that is 'Paused' is not processing a package
145
                                    //      It will have been included in the build-set, so we must wait for
146
                                    //      the pause to be removed.
147
                                    //
148
                                    // A slave that is 'Waiting' must also have no BuildFile present
149
                                    //      This signals that the buildfile has been taken by the slave
150
                                    // 
151
                                    if (! (rl.isAt(BuildState.DB_WAITING) && !rl.hasBuildFile() )  )
152
                                    {
153
                                        // A non-waiting slave has been found
154
                                        waitList.append(" ");
155
                                        waitList.append(rl.get_rcon_id());
156
                                    }
157
                                }
158
 
159
 
160
                                if ( waitList.length() > 0 )
161
                                {
162
                                    // One or more slaves still processing ...
163
                                    if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )
164
                                    {
165
                                        Thread.currentThread().interrupt();
166
                                    }
167
                                    else
168
                                    {
169
 
170
                                        mLogger.warn("Waiting 3 seconds for slaves:" + waitList.toString() );
171
                                        Thread.sleep(3000);
172
                                        mLogger.info("run sleep returned");
173
                                    }
174
                                    continue;
175
                                }
176
                                else
177
                                {
178
                                    // All slaves have completed there tasks
179
                                    break;
180
                                }
181
                            }
182
 
183
                            if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )
184
                            {
185
                                throw new ExitException();
186
                            }
187
 
188
                            //---------------------------------------------------------------
189
                            //    Publish Package Build Results
190
                            //        Indicate to RM that we are publishing
191
                            //        Ensure that all build machines have placed a marker in dpkg_archive
192
                            //        Save updated build files into VCS
193
                            // 
7176 dpurdie 194
                            mLogger.warn("run changing run level to PUBLISHING for rcon_id {}", mRconId);
6914 dpurdie 195
                            mPhase.setPhase("Publishing");
196
                            mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_PUBLISHING);
197
 
198
                            mLogger.info("run calling deliverChange on AbtPublish");
199
                            deliverChange("AbtPublish", true, false);
200
 
201
                            //---------------------------------------------------------------
202
                            //    TearDown the build workspace
203
                            //        Remove the build workspace
204
                            //        Save build log files
205
                            //        Don't update the Reporting Information as it will null out
206
                            //        some essential information that has been collected.
207
                            //
208
                            mLogger.info("run calling deliverChange on AbtTearDown");
209
                            mPhase.setPhase("AbtTearDown");
210
                            deliverChange("AbtTearDown", false, true);
211
 
212
                            // Delete the build file now
213
                            //  This will prevent any chance of multiply publishing a package version
214
                            deleteBuildFile();
215
 
216
 
217
                            //---------------------------------------------------------------
218
                            //    Update Release Manager (publish to Release Manager)
219
                            //
220
                            mPhase.setPhase("Update Release Manager");
221
                            if ( mReporting.packageName != null )
222
                            {
223
                                // A dummy build file did not apply
224
                                // Publishing is done outside ant by design
225
                                //      Do ALL Release Manager work outside ant (and JATS)
226
 
227
                                boolean buildErrorOccurred = true;
228
                                boolean publishError = true;
229
 
230
                                try
231
                                {
232
                                    //  Create a build instance entry in the Release Manager database
233
                                    //        Create one per build
234
                                    //        mReporting.packageVersionId will have been updated if this is a new package-version
235
                                    //        Save the build id
236
                                    mPhase.setPhase("Create Build Instance");
237
                                    mReporting.buildId = mReleaseManager.createBuildInstance(
238
                                            mRtagId, 
239
                                            mReporting.packageVersionId,
7253 dpurdie 240
                                            mReporting.buildReason,
241
                                            mReporting.buildRef);
6914 dpurdie 242
                                    //
243
                                    //  Locate and collect the unit test results
244
                                    //
245
                                    mPhase.setPhase("Parse Unit Test Results");
246
                                    BuildTestResults btr = new BuildTestResults(System.getenv("GBE_DPKG"), mReporting, mLogger);
247
                                    mReleaseManager.insertTestResults(mReporting.buildId, btr);
248
 
249
                                    if ( mReporting.isaTestBuild )
250
                                    {
251
 
252
                                        //    Test Build
253
                                        //    Notify the user requesting the build
254
                                        //        Build Failure emails have already been sent
255
                                        //
256
                                        mLogger.info("run completing test build on " + mReporting.packageName + mReporting.packageExtension);
257
                                        mPhase.setPhase("Report Test Build Complete");
7155 dpurdie 258
                                        completeTestBuild(mRippleEngine, mReporting.isFullyPublished);
6914 dpurdie 259
 
260
                                        //
261
                                        //  Determine the total time taken by the build
262
                                        //      Done as late a possible in the process
263
                                        //      Does not include planning time
264
                                        //      Does not handle case where build cycle is broken
265
                                        //      Only record for successful tests. Don't want to record short build times on failure
266
                                        //      in particular if the package has been released. Would be OK for a WIP, but how to identify these
267
                                        if ( mReporting.isFullyPublished)
268
                                        {
269
                                            int buildDuration = mBuildDuration.toIntSecs();
7176 dpurdie 270
                                            mLogger.warn("Build Duration:{}", buildDuration);
6914 dpurdie 271
                                            mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
272
                                        }
273
 
274
                                        mPhase.setPhase("Update Build Instance for Test");
275
                                        mReleaseManager.updateBuildInstance(mReporting.buildId, 0, mReporting.isFullyPublished ? BuildResult.Complete :BuildResult.BuildError );
276
 
277
                                        // ... and clean up the mess in the archive
278
                                        publishError = false;
279
                                        throw new Exception();                    
280
                                    }
281
 
282
                                    //    Package not fully published
283
                                    //    An error has occurred in the building of the package
284
                                    if ( !mReporting.isFullyPublished )
285
                                    {
286
                                        mLogger.info("run build error occurred on " + mReporting.packageName + mReporting.packageVersion);
287
 
288
                                        // ... and clean up the mess in the archive
289
                                        publishError = false;
290
                                        throw new Exception();
291
                                    }
292
 
293
                                    //---------------------------------------------------------------
294
                                    //  Package was successfully built and published into dpkg_archive by all daemons
295
                                    //    Update Release Manager - formally release the package
296
                                    //    Insert Package Metrics
297
                                    //    Insert Unit Test Results
298
                                    buildErrorOccurred = false;
299
 
300
                                    //
301
                                    //    Detect Badly formed VCS label returned by the builder
302
                                    //      Have had zero length values returned
303
                                    //      Treat as a publishing error
304
                                    //
305
                                    if ( mReporting.newVcsTag == null || mReporting.newVcsTag.isEmpty() )
306
                                    {
7176 dpurdie 307
                                        mLogger.error("run package not labelled in Version Control on {}{}",mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 308
                                        mReporting.errMsg = "Error publishing to Version Control System";     // Max 50 Characters
309
                                        throw new Exception();
310
                                    }
311
 
312
 
313
                                    // Publish to release manager
314
                                    //    On error mReporting.errMsg will contain error string
315
                                    //    Publishing errors only affect the current package
316
                                    //
7176 dpurdie 317
                                    mLogger.warn("run calling mReleaseManager.autoMakeRelease");
6914 dpurdie 318
                                    mPhase.setPhase("autoMakeRelease");
319
                                    publishError =  mReleaseManager.autoMakeRelease(mReporting);
320
                                    if ( publishError )
321
                                    {
7176 dpurdie 322
                                        mLogger.error("autoMakeRelease publishError: {}", mReporting.errMsg);
6914 dpurdie 323
                                        throw new Exception();
324
                                    }
325
 
326
                                    //
327
                                    //  Determine the total time taken by the build
328
                                    //      Done as late a possible in the process
329
                                    //      Does not include planning time
330
                                    //      Does not handle case where build cycle is broken
331
                                    //
332
                                    int buildDuration = mBuildDuration.toIntSecs();
7176 dpurdie 333
                                    mLogger.warn("Build Duration:{}", buildDuration);
6914 dpurdie 334
                                    mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
335
 
336
                                    //
337
                                    //    Update the Build Instance information
338
                                    //    If this has been a ripple then the pv_id of the build needs to be associated with
339
                                    //    the newly created version
340
 
341
                                    mPhase.setPhase("Update Build Instance");
342
                                    mReleaseManager.updateBuildInstance(mReporting.buildId, mReporting.packageVersionId, BuildResult.Complete );
343
 
344
                                    //
345
                                    //    Insert package metrics into Release Manager
346
                                    //        Metrics have been placed in a file in a format suitable for RM
347
                                    //
348
                                    mReporting.errMsg = "Error publishing Package Metrics";     // Max 50 Characters
349
                                    mPhase.setPhase("Insert Metrics");
350
                                    FileInputStream abtmetrics = new FileInputStream( String.valueOf(mRtagId) + "abtmetrics.txt" );
351
                                    DataInputStream din = new DataInputStream( abtmetrics );
352
                                    InputStreamReader isr = new InputStreamReader( din );
353
                                    BufferedReader br = new BufferedReader( isr );
354
                                    String metrics = br.readLine();
7176 dpurdie 355
                                    mLogger.warn( "execute read metrics string {}", metrics );
6914 dpurdie 356
                                    br.close();
357
                                    isr.close();
358
                                    din.close();
359
 
7176 dpurdie 360
                                    mLogger.warn("run calling mReleaseManager.insertPackageMetrics");                      
6914 dpurdie 361
                                    mReleaseManager.insertPackageMetrics(mRtagId, mReporting.packageName, mReporting.packageExtension, metrics );
362
 
363
                                    //
364
                                    //    Info reporting
365
                                    //    Send an email to track build system usage - may be noise
366
                                    //
367
                                    mReporting.errMsg = null;
7176 dpurdie 368
                                    mLogger.warn("run calling emailBuildComplete");
6914 dpurdie 369
                                    mPhase.setPhase("Post Build Email");
370
                                    emailPostBuild(mRippleEngine, false);
371
 
372
                                    //---------------------------------------------------------------
373
                                    //    All done
374
                                    //    The package has been built and released
375
                                    mPhase.setPhase("Build Complete");
376
                                }
377
                                catch( Exception e)
378
                                {
379
                                    // Some form of error has occurred. Types include
380
                                    //    Test build (Treated as an error so that dpkg_archive gets removed)
381
                                    //        buildErrorOccurred - True
382
                                    //        publishError - False    
383
                                    //    Build Error - Package was not fully published to dpkg_archive
384
                                    //        buildErrorOccurred - True
385
                                    //        publishError - False
386
                                    //     
387
                                    //    Badly formed VCS tag (Error Publishing to Version Control)
388
                                    //        buildErrorOccurred - False
389
                                    //        publishError - True    
390
                                    //    Error Publishing to Release Manager
391
                                    //        buildErrorOccurred - False
392
                                    //        publishError - True    
393
                                    //    Error inserting package metrics
394
                                    //        buildErrorOccurred - False
395
                                    //        publishError - True
396
                                    //    Error inserting unit test results
397
                                    //        buildErrorOccurred - False
398
                                    //        publishError - True
399
                                    // 
400
                                    // Uses
401
                                    //    buildErrorOccurred      - Package not in dpkg_archive as expected (or was a test build)
402
                                    //                              Email should have been sent to the user
403
                                    //    publishError            - Could not publish to Release Manager
404
                                    //                              Post build error. Email has not been sent to user
405
                                    //                              Takes precedence over buildErrorOccurred
406
 
407
                                    // Insert generic message if we don't have one
408
                                    //     Should only occur under unexpected conditions
409
                                    if (mReporting.errMsg == null || mReporting.errMsg.isEmpty())
410
                                    {
411
                                        mReporting.errMsg = "Error publishing to Release Manager";
412
                                        mReporting.errMsgDetail = mPhase.sText;
413
                                    }
414
 
415
                                    // Indicate some form of build error
416
                                    if ( ! mReporting.isaTestBuild )
417
                                    {
418
                                        mPhase.setPhase("Update Build Instance");
419
                                        mReleaseManager.updateBuildInstance(mReporting.buildId, 0, publishError ? BuildResult.SystemError :BuildResult.BuildError );
420
                                    }
421
 
422
                                    // 
423
                                    // Delete the dpkg_archive entry - the package is a dud
424
                                    //
425
                                    mPhase.setPhase("Delete package from archive");
7176 dpurdie 426
                                    mLogger.warn("Delete package from archive");
6914 dpurdie 427
                                    deletePackageVersion();
428
 
429
                                    //    A publishing error. The error occurred, after the build, in the RM publishing
430
                                    //        We won't have a log file, but we will have a rootCause
431
                                    //    Exclude package from the build
432
                                    //        Unless its a test build (handled within mReleaseManager.excludeFromBuild) 
433
                                    //
434
                                    if ( publishError  )
435
                                    {
7033 dpurdie 436
                                        mLogger.error("an error occurred publishing to Version Control or Release Manager");
6914 dpurdie 437
 
438
                                        //  Post Build Error
439
                                        //  eMails have not been sent by the ABT class as the error has occurred outside of that process
440
                                        mPhase.setPhase("Post Build Failure Email");
441
                                        emailPostBuild(mRippleEngine, true);
442
 
7176 dpurdie 443
                                        mLogger.warn("run calling excludeFromBuild");
6914 dpurdie 444
                                        mPhase.setPhase("Excluded from build");
445
                                        mReleaseManager.excludeFromBuild(false, 
446
                                                mReporting.packageVersionId, 
447
                                                null, 
448
                                                mReporting.rtagId, 
449
                                                null, 
450
                                                mReporting.errMsg, 
451
                                                null, 
452
                                                false, mReporting.isaTestBuild);
453
 
454
                                    }
455
                                    else if ( buildErrorOccurred )
456
                                    {
457
                                        //    Build Error Occurred
458
                                        //        Package has not been built on all configured platforms
459
                                        //        Under normal circumstances, this root cause will be masked by a previously reported error
460
                                        //        Under abnormal circumstances amidst build activity such as:
461
                                        //            - slave build machine reboots
462
                                        //            - slave build machines with a read only file system
463
                                        //        The rootCause is required to keep the end user informed
464
                                        //
465
                                        //    Use excludeFromBuild such that this call will not supersede existing entries
466
                                        //    In this manner the log file/cause provided here will only be used if we haven't
467
                                        //    already excluded this package from the build
468
 
469
                                        //    If we have a log file, then provide it to the user, else insert a generic message
470
 
471
                                        mReporting.errMsg = (mReporting.buildFailureLogFile == null) ? "Buildtool env error occurred. Attempt build again" : null;
472
 
7176 dpurdie 473
                                        mLogger.warn("run calling excludeFromBuild"); 
6914 dpurdie 474
                                        mPhase.setPhase("Excluded from build");
475
                                        mReleaseManager.excludeFromBuild(false, 
476
                                                mReporting.packageVersionId, 
477
                                                mReporting.packageVersion,
478
                                                mReporting.rtagId, 
479
                                                null, 
480
                                                mReporting.errMsg, 
481
                                                mReporting.buildFailureLogFile, 
482
                                                false, mReporting.isaTestBuild);
483
                                    }
484
                                    else
485
                                    {
486
                                        //  Not a buildError and not a publishing Error
487
                                        //      Don't know how we got here - I don't think we can
488
                                        //      Will cause an indefinite pause !
489
                                        throw new Exception("an error occurred publishing to Version Control or Release Manager");
490
 
491
                                    }
492
                                } // End Catch
493
                            }
494
 
495
                            if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )            
496
                            {
497
                                throw new ExitException();
498
                            }
499
                            mLogger.info("run coordinate slave threads returned");
500
                        }
501
 
502
 
503
                        //---------------------------------------------------------------
504
                        //  Start of a new build cycle
505
                        //      Determine if the daemon has been paused.
506
                        //      Set RunLevel.IDLE (within allowedToProceed)
507
                        //
7176 dpurdie 508
                        mLogger.warn("run calling allowedToProceed");
6914 dpurdie 509
                        mPhase.setPhase("allowedToProceed");
510
                        mReleaseManager.discardVersion();
511
                        mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
512
                        allowedToProceed(true);
513
                        mLogger.info("run allowedToProceed returned");
514
 
515
                        if ( mUnitTest.compareTo("unit test allowed to proceed") == 0 )            
516
                        {
517
                            throw new ExitException();
518
                        }
519
 
520
                        //  Set up mReleaseConfigCollection
521
                        //  This will be used when creating a build file
7176 dpurdie 522
                        mLogger.warn("Collect fresh MetaData");
6914 dpurdie 523
                        mPhase.setPhase("collectMetaData");
524
                        mRippleEngine.collectMetaData();
525
 
526
                        //---------------------------------------------------------------
527
                        //  Plan the next build
528
                        //      Snap current Release Sequence Number
529
                        //      Determine what is to be built
530
                        //      Generate build files
7176 dpurdie 531
                        mLogger.warn("run calling planRelease");
6914 dpurdie 532
                        mPhase.setPhase("Plan Release", 600);
7169 dpurdie 533
                        mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_PLANNING);
6914 dpurdie 534
                        mReleaseSeqNum =  mReleaseManager.queryReleaseSeqNum(mRtagId, mRconId, BuildDaemon.mHostname); 
535
                        mRippleEngine.planRelease(!mLastBuildWasBenign);
536
 
537
                        // get the build file from the ripple engine
538
                        mPhase.setPhase("Get Build File", 10);
539
                        mMasterBuildFile = mRippleEngine.getFirstBuildFileContent();
540
 
541
                    }
542
                }
543
 
544
                //---------------------------------------------------------------
545
                //  Check that we are good to proceed with the build
546
                //      Check environment
547
                //      Ensure we have enough disk space
548
                //     
7176 dpurdie 549
                mLogger.warn("run calling checkEnvironment"); 
6914 dpurdie 550
                mPhase.setPhase("checkEnvironment");
551
                checkEnvironment();
552
                mLogger.info("run checkEnvironment returned");
553
 
554
                if ( mUnitTest.startsWith("unit test check environment") ) 
555
                {
556
                    throw new ExitException();
557
                }
558
 
559
                mLogger.info("run generated build files");
560
                // Start of a build cycle. Set new log file to capture entire build log
561
                mPhase.setPhase("Start Build Cycle");
562
                flagStartBuildCycle();
563
                mBuildDuration.reset();
564
                mReporting.resetData();
565
                mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_ACTIVE);
566
                mReleaseManager.setCurrentPackageBeingBuilt(mRconId, mMasterBuildFile.mPkgId, mMasterBuildFile.mPvId);
567
 
568
                // Save the buildfile
7176 dpurdie 569
                mLogger.warn("Save buildfile");
6914 dpurdie 570
                mPhase.setPhase("Save buildfile");
571
                saveBuildFile(mMasterBuildFile.content);
572
 
573
                // Quick Test to validate the provided Version Control tag/label
574
                mPhase.setPhase("Validate Version Tag");
575
                if ( deliverChange("AbtTestPath", true, false) )
576
                {
577
 
578
                    //---------------------------------------------------------------
579
                    //    Notify all slaves that there is work to be done
580
                    //      This is done by publishing a buildfile for them to consume
581
                    //      A NonGeneric build will be done with a real build file on all machines
582
                    //      Otherwise do a Dummy build on all Machines
583
                    //
584
                    mPhase.setPhase("Notify slaves of work", 10);
585
                    if ( mMasterBuildFile.state != BuildFileState.NonGeneric)
586
                    {
587
                        // publish a dummy build file for either generic or dummy cases
588
                        // this results in the slave not running ant
7176 dpurdie 589
                        mLogger.warn("run calling publishBuildFile on dummy");
6914 dpurdie 590
                        mMasterBuildFile.content = mDummyBuildFileContent;
591
                    }
592
                    else
593
                    {
594
                     // publish the build file
7176 dpurdie 595
                        mLogger.warn("run calling publishBuildFile");    
6914 dpurdie 596
                    }
597
                    mReleaseManager.publishBuildFile(mRtagId, mMasterBuildFile);                    
598
 
599
 
600
                    if ( mUnitTest.compareTo("unit test generate build files") == 0 )
601
                    {
602
                        throw new ExitException();
603
                    }
604
 
605
                    mLogger.info("run changed run levels");
606
 
607
                    //---------------------------------------------------------------
608
                    //  Build the package
609
                    //      Setup the workspace
610
                    //      Build the package - deliver change to product baseline
611
                    //
7176 dpurdie 612
                    mLogger.warn("Build Package {}_{}", mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 613
 
614
                    mLogger.info("run calling setViewUp");
615
                    mPhase.setPhase("Setup View for build");
616
                    deliverChange("AbtSetUp", true, false);
617
 
618
                    mLogger.info("run calling deliverChange - the actual build");
619
                    mPhase.setPhase("Build Package");
620
                    deliverChange(null, true, false);
621
                    mLogger.info("run deliverChange returned");
622
                }
623
 
624
                mLastBuildWasBenign = false;
625
                if ( mMasterBuildFile.state == BuildFileState.Dummy)
626
                {
627
                    // no build requirement, so let things settle
628
                    mLogger.warn("run no build requirement, so let things settle");
629
                    mLastBuildWasBenign = true;
630
                }        
631
            }
632
            //---------------------------------------------------------------
633
            //    Build loop exception handling (only)
634
            //
635
            catch( SQLException e )
636
            {
637
                //  Oracle connection issues
638
                //  Request a prolonged sleep at the start of the build loop
7033 dpurdie 639
                mLogger.error("run oracle connection issues");
6914 dpurdie 640
                mException = true;
641
            }
642
            catch( ExitException e )
643
            {
644
                mLogger.warn("run ExitException");
645
                exit = true;
646
            }
647
            catch( InterruptedException e )
648
            {
649
                mLogger.warn("run InterruptedException");
650
                Thread.currentThread().interrupt();
651
            }
652
            catch (BuildSystemException e) {
653
                // BuildSystem exception - a (possibly) correctable error
654
                // Flag as recoverable
655
                //    - Can't create XML build file
656
                //    - 
657
                // 
7033 dpurdie 658
                mLogger.error("run BuildSystemException");
6914 dpurdie 659
                mPhase.setPhase("BuildSystemException indefinitePause");
660
                notifyIndefinitePause(e.getMessage());
661
                mReleaseManager.indefinitePause(false);
662
                mException = true;
663
                mRecoverable = true;
664
 
665
            }
666
            catch( BuildToolException e)
667
            {
668
                // Buildtool exception - an uncorrectable error
669
                //    - Can't parse XML build file
670
                // 
7033 dpurdie 671
                mLogger.error("run BuildToolException");
6914 dpurdie 672
                mPhase.setPhase("BuildToolException indefinitePause");
673
                notifyIndefinitePause(e.getMessage());
674
                mReleaseManager.indefinitePause(false);
675
                mException = true;
676
            }
677
            catch( Exception e )
678
            {
679
                //  Uncaptured exception
680
                //  These are not good. Current mechanism to handle this condition is:
681
                //      1) Email build system administrator
682
                //      2) Pause the build system
683
                //  
7176 dpurdie 684
                mLogger.error("run indefinitePause {}", e);
6914 dpurdie 685
 
686
                // DEVI 51366 force sleep at beginning of while loop
687
                mException = true;
688
 
689
                String cause = e.getMessage();
690
                if ( cause == null || cause.compareTo("null") == 0 )
691
                {
692
                    cause = "Internal Error: " + e.toString();
693
                }
694
 
695
                try
696
                {
697
                    // notify first
698
                    // many reasons for indefinite pause, including database related, so do database last
699
                    mRecoverable = false;
700
 
701
                    if ( cause.compareTo(Package.mRecoverable) == 0 )
702
                    {
703
                        mRecoverable = true;
704
                    }
705
 
706
                    mPhase.setPhase("Notify indefinitePause");
707
                    notifyIndefinitePause(cause);
708
                    mReleaseManager.indefinitePause(mRecoverable);
709
                    mReleaseManager.updateBuildInstance(mReporting.buildId, 0, BuildResult.SystemError );
710
                }
711
                catch( Exception f )
712
                {
713
                    mLogger.error("run indefinitePause failed");
714
                }
715
            }
716
        }
717
        try {
718
            mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
719
        } catch (Exception e) {
7176 dpurdie 720
            mLogger.error("Exception in clearCurrentPackageBeingBuilt: {}", e.getMessage());
6914 dpurdie 721
        }
722
        mPhase.setPhase("Exit Thread");
723
    }
724
 
725
    /**   Delete a specified version of a package from dpkg_archive
726
     *    Used during error processing to cleanup packages that did not build correctly
727
     *    
728
     *    The package-version is in dpkg_archive. This may be on a remote server
729
     *    Execute the deletion command on the remote server as it will be a lot faster
730
     *    for large packages.
731
     *    
732
     *    Ensure that the file system cache is cleared before we attempt to look
733
     *    for the directory
734
     */
735
    private void deletePackageVersion()
736
    {
737
 
738
        //    Setup a Remote Execution environment
739
        //    The logging interface is is hard part
740
        RemoteExecution mRemoteExecution = new RemoteExecution(new LogOutput(){
741
 
742
            @Override
743
            public void data(String message) {
744
                mLogger.info(message);
745
            }
746
 
747
            @Override
748
            public void fatal(String message) {
7033 dpurdie 749
                mLogger.error(message);
6914 dpurdie 750
            }
751
 
752
            @Override
753
            public void info(String message) {
754
                mLogger.info(message);
755
            }});
756
 
757
 
758
        //    Execute the remote command
759
        //    This is a best effort deletion - can't really handle conditions
760
        //    where the command fails.
761
        CommandBuilder cmd = new CommandBuilder();
762
 
763
        cmd.add("sudo","-n", "-u", "buildadm", "/home/releasem/sbin/jatsTool", "assemble_dpkg");
764
        cmd.add("-DeleteVersion");
765
        cmd.add(!ReleaseManager.getUseMutex(), "-testArchive");
766
        cmd.add("'-pname=" + mReporting.packageName + "'");
767
        cmd.add("'-pversion=" + mReporting.packageVersion + "'");
768
 
7176 dpurdie 769
        mLogger.warn("run remote command to delete {}, {}", mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 770
        int rv = mRemoteExecution.execute(cmd.toString());
7176 dpurdie 771
        mLogger.info("run remote command to delete. Returned {}", rv);
6914 dpurdie 772
 
773
        //    Belt and Braces
774
        //    Ensure that the package-version has been deleted, 
775
        //    and if not then try to delete it the slow way.
776
        //
777
        //    Note: Need to flush NFS cache before we check existence 
778
 
779
        String dpkgArchiveEntry = utilities.catDir(Package.mGbeDpkg, mReporting.packageName, mReporting.packageVersion);
780
        File dpkgArchiveEntryFile = utilities.freshFile(dpkgArchiveEntry);
7176 dpurdie 781
        mLogger.debug("run checking existence of {}",dpkgArchiveEntry);
6914 dpurdie 782
 
783
        if ( dpkgArchiveEntryFile.exists() )
784
        {
785
            if ( dpkgArchiveEntryFile.isDirectory() )
786
            {
7176 dpurdie 787
                mLogger.warn("run calling deleteDirectory on {}", dpkgArchiveEntryFile);                      
6914 dpurdie 788
                deleteDirectory(dpkgArchiveEntryFile);
789
            }
790
        }
791
    }
792
 
793
    /**   Sends email notification and mark the successful completion of a build
794
     *    Used simply to keep an email trail of build operations
795
     */
796
    public void emailPostBuild( RippleEngine rippleEngine, boolean isaError )
797
    {
798
        mLogger.debug("emailPostBuild");
799
        String subject;
800
        String emailTo;
801
        String mailBody = "";
802
 
803
        if (isaError)
804
        {
805
            subject = "BUILD FAILURE on package " + mReporting.packageName + " " + mReporting.packageVersion;
806
            emailTo = mReporting.packageOwners;
807
            mailBody="An error occured within the build system after the package had been built<p><hr>";
808
        }
809
        else
810
        {
811
            subject = "BUILD SUCCESS on package " + mReporting.packageName + " " + mReporting.packageVersion;
812
            emailTo = rippleEngine.getMailSender();
813
        }
814
 
815
        //  Cleanup the dependency string
816
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
817
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
818
        String depends = mReporting.packageDepends.replace("','", " ");
819
        depends = depends.replace("';'",indent);
820
        depends = depends.replace("'","");
821
 
822
        //  Cleanup the build standard string
823
        //      Expecting win32: jats all;linux_i386: jats prod
824
        String buildStandards = mReporting.packageBuildInfo;
825
        buildStandards = buildStandards.replace(";",indent);
826
 
827
        mailBody += "Release      : " + rippleEngine.mBaselineName + "<br>" +
828
                "Package      : " + mReporting.packageName + "<br>" +
829
                "Version      : " + mReporting.packageVersion + "<br>";
830
        if (isaError)
831
        {
832
            mailBody += "Cause        : " + mReporting.errMsg + "<br>";
833
            if (mReporting.errMsgDetail != null && mReporting.errMsgDetail.length() > 0)
834
            {
835
                mailBody += "Detail       : " + mReporting.errMsgDetail + "<br>";
836
            }
837
        }
838
 
839
        mailBody += "RM Link      : " + CreateUrls.generateRmUrl(mRtagId,mReporting.packageVersionId) + "<br>" +
840
                "PVID         : " + mReporting.packageVersionId + "<br>" +
841
                "VcsTag       : " + mReporting.newVcsTag + "<br>" +
842
                "Ripple       : " + (mReporting.isRipple ? "Yes" : "No") + "<br>" +
843
                "Dependencies : " + indent + depends + "<br>" +
844
                "Build Standards : " + indent + buildStandards;
845
 
846
        mailBody += "<p><hr>";
847
        try
848
        {
7155 dpurdie 849
            Smtpsend.send( rippleEngine.getMailServer(),    // mailServer
6914 dpurdie 850
                    rippleEngine.getMailSender(),           // source
7155 dpurdie 851
                    emailTo,                                // target - send to package owners, or myself
6914 dpurdie 852
                    rippleEngine.getMailSender(),           // cc
7155 dpurdie 853
                    null,                                   // bcc
854
                    subject,                                // subject
855
                    mailBody,                               // body
856
                    null                                    // attachment
6914 dpurdie 857
                    );
858
        }
859
        catch( Exception e )
860
        {
861
            mLogger.warn("Email Failure: emailPostBuild:" + e.getMessage());
862
        }
863
        mLogger.debug("emailPostBuild. Returning");
864
    }
7155 dpurdie 865
 
866
    /**
867
     * End of Processing for a Test Build
868
     *     - sends email notification
869
     *     - marks the instruction complete in the database
870
     */
871
    public void completeTestBuild(RippleEngine rippleEngine, boolean success) throws SQLException, Exception
872
    {
873
        mLogger.debug("completeTestBuild");
6914 dpurdie 874
 
7155 dpurdie 875
        if (!mReporting.isaTestBuild)
876
        {
877
            mLogger.info("completeTestBuild. Not Build Instruction");
878
            return;
879
        }
880
 
881
        //  Email Subject
882
        String subject = (success ? "TEST BUILD COMPLETED SUCCESSFULLY" : "TEST BUILD FAILED") 
883
                + " on package "
884
                + mReporting.packageName +  mReporting.packageExtension;
885
 
886
        //  Cleanup the dependency string
887
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
888
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
889
        String depends = mReporting.packageDepends.replace("','", " ");
890
        depends = depends.replace("';'",indent);
891
        depends = depends.replace("'","");
892
 
893
        //  Cleanup the build standard string
894
        //      Expecting win32: jats all;linux_i386: jats prod
895
        String buildStandards = mReporting.packageBuildInfo;
896
        buildStandards = buildStandards.replace(";",indent);
897
 
898
        // Email Body
899
        String mailBody = "";
900
        if ( !success )
901
        {
902
            mailBody += "Test build issues are identified in preceding build failure email.<p>"; 
903
        }
904
        mailBody += "Release: " + rippleEngine.mBaselineName + "<br>" 
905
                  + "Package: " + mReporting.packageName +  mReporting.packageExtension + "<br>" 
906
                  + "Rm Ref: " + CreateUrls.generateRmUrl(mReporting.rtagId, mReporting.packageVersionId) + "<br>" 
907
                  + "VcsTag: " + mReporting.vcsTag + "<br>"
908
                  + "Dependencies : " + indent + depends + "<br>"
909
                  + "Build Standards : " + indent + buildStandards;
910
 
911
        mailBody += "<p><hr>";
912
        try
913
        {
7176 dpurdie 914
            mLogger.info("completeTestBuildEmail Server: {}", rippleEngine.getMailServer());
915
            mLogger.info("completeTestBuildEmail Sender: {}", rippleEngine.getMailSender());
916
            mLogger.info("completeTestBuildEmail Target: {}", mReporting.packageOwners);
7155 dpurdie 917
 
918
            Smtpsend.send(rippleEngine.getMailServer(),     // mailServer
919
                    rippleEngine.getMailSender(),           // source
920
                    mReporting.packageOwners,               // target
921
                    rippleEngine.getMailSender(),           // cc
922
                    null,                                   // bcc
923
                    subject,                                // subject
924
                    mailBody,                               // body
925
                    null                                    // attachment
926
            );
927
        } catch (Exception e)
928
        {
929
            mLogger.warn("Email Failure: completeTestBuild:{}", e.getMessage());
930
        }
931
 
932
        // Update the Release Manager Database
933
        mReleaseManager.markDaemonInstCompleted(mReporting.testBuildId);
7176 dpurdie 934
        mLogger.warn("completeTest. Returning");
7155 dpurdie 935
    }
936
 
937
 
6914 dpurdie 938
    /**returns 'M'
939
     */
940
    protected char getMode()
941
    {
942
        mLogger.debug("getMode");
943
        return 'M';
944
    }
945
 
946
 
947
}