Subversion Repositories DevTools

Rev

Rev 7155 | Rev 7176 | 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
            {
7033 dpurdie 73
                mLogger.error("run calling sleepCheck");
6914 dpurdie 74
                mPhase.setPhase("sleepCheck");
75
                sleepCheck();
76
 
7033 dpurdie 77
                mLogger.error("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
                            //
7033 dpurdie 106
                            mLogger.error("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
                            // 
7033 dpurdie 194
                            mLogger.error("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,
240
                                            mReporting.buildReason );
241
                                    //
242
                                    //  Locate and collect the unit test results
243
                                    //
244
                                    mPhase.setPhase("Parse Unit Test Results");
245
                                    BuildTestResults btr = new BuildTestResults(System.getenv("GBE_DPKG"), mReporting, mLogger);
246
                                    mReleaseManager.insertTestResults(mReporting.buildId, btr);
247
 
248
                                    if ( mReporting.isaTestBuild )
249
                                    {
250
 
251
                                        //    Test Build
252
                                        //    Notify the user requesting the build
253
                                        //        Build Failure emails have already been sent
254
                                        //
255
                                        mLogger.info("run completing test build on " + mReporting.packageName + mReporting.packageExtension);
256
                                        mPhase.setPhase("Report Test Build Complete");
7155 dpurdie 257
                                        completeTestBuild(mRippleEngine, mReporting.isFullyPublished);
6914 dpurdie 258
 
259
                                        //
260
                                        //  Determine the total time taken by the build
261
                                        //      Done as late a possible in the process
262
                                        //      Does not include planning time
263
                                        //      Does not handle case where build cycle is broken
264
                                        //      Only record for successful tests. Don't want to record short build times on failure
265
                                        //      in particular if the package has been released. Would be OK for a WIP, but how to identify these
266
                                        if ( mReporting.isFullyPublished)
267
                                        {
268
                                            int buildDuration = mBuildDuration.toIntSecs();
7033 dpurdie 269
                                            mLogger.error("Build Duration:" + buildDuration);
6914 dpurdie 270
                                            mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
271
                                        }
272
 
273
                                        mPhase.setPhase("Update Build Instance for Test");
274
                                        mReleaseManager.updateBuildInstance(mReporting.buildId, 0, mReporting.isFullyPublished ? BuildResult.Complete :BuildResult.BuildError );
275
 
276
                                        // ... and clean up the mess in the archive
277
                                        publishError = false;
278
                                        throw new Exception();                    
279
                                    }
280
 
281
                                    //    Package not fully published
282
                                    //    An error has occurred in the building of the package
283
                                    if ( !mReporting.isFullyPublished )
284
                                    {
285
                                        mLogger.info("run build error occurred on " + mReporting.packageName + mReporting.packageVersion);
286
 
287
                                        // ... and clean up the mess in the archive
288
                                        publishError = false;
289
                                        throw new Exception();
290
                                    }
291
 
292
                                    //---------------------------------------------------------------
293
                                    //  Package was successfully built and published into dpkg_archive by all daemons
294
                                    //    Update Release Manager - formally release the package
295
                                    //    Insert Package Metrics
296
                                    //    Insert Unit Test Results
297
                                    buildErrorOccurred = false;
298
 
299
                                    //
300
                                    //    Detect Badly formed VCS label returned by the builder
301
                                    //      Have had zero length values returned
302
                                    //      Treat as a publishing error
303
                                    //
304
                                    if ( mReporting.newVcsTag == null || mReporting.newVcsTag.isEmpty() )
305
                                    {
7033 dpurdie 306
                                        mLogger.error("run package not labelled in Version Control on " + mReporting.packageName + mReporting.packageVersion);
6914 dpurdie 307
                                        mReporting.errMsg = "Error publishing to Version Control System";     // Max 50 Characters
308
                                        throw new Exception();
309
                                    }
310
 
311
 
312
                                    // Publish to release manager
313
                                    //    On error mReporting.errMsg will contain error string
314
                                    //    Publishing errors only affect the current package
315
                                    //
7033 dpurdie 316
                                    mLogger.error("run calling mReleaseManager.autoMakeRelease");
6914 dpurdie 317
                                    mPhase.setPhase("autoMakeRelease");
318
                                    publishError =  mReleaseManager.autoMakeRelease(mReporting);
319
                                    if ( publishError )
320
                                    {
7033 dpurdie 321
                                        mLogger.error("autoMakeRelease publishError: " + mReporting.errMsg);
6914 dpurdie 322
                                        throw new Exception();
323
                                    }
324
 
325
                                    //
326
                                    //  Determine the total time taken by the build
327
                                    //      Done as late a possible in the process
328
                                    //      Does not include planning time
329
                                    //      Does not handle case where build cycle is broken
330
                                    //
331
                                    int buildDuration = mBuildDuration.toIntSecs();
7033 dpurdie 332
                                    mLogger.error("Build Duration:" + buildDuration);
6914 dpurdie 333
                                    mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
334
 
335
                                    //
336
                                    //    Update the Build Instance information
337
                                    //    If this has been a ripple then the pv_id of the build needs to be associated with
338
                                    //    the newly created version
339
 
340
                                    mPhase.setPhase("Update Build Instance");
341
                                    mReleaseManager.updateBuildInstance(mReporting.buildId, mReporting.packageVersionId, BuildResult.Complete );
342
 
343
                                    //
344
                                    //    Insert package metrics into Release Manager
345
                                    //        Metrics have been placed in a file in a format suitable for RM
346
                                    //
347
                                    mReporting.errMsg = "Error publishing Package Metrics";     // Max 50 Characters
348
                                    mPhase.setPhase("Insert Metrics");
349
                                    FileInputStream abtmetrics = new FileInputStream( String.valueOf(mRtagId) + "abtmetrics.txt" );
350
                                    DataInputStream din = new DataInputStream( abtmetrics );
351
                                    InputStreamReader isr = new InputStreamReader( din );
352
                                    BufferedReader br = new BufferedReader( isr );
353
                                    String metrics = br.readLine();
354
                                    mLogger.warn( "execute read metrics string " + metrics );
355
                                    br.close();
356
                                    isr.close();
357
                                    din.close();
358
 
7033 dpurdie 359
                                    mLogger.error("run calling mReleaseManager.insertPackageMetrics");                      
6914 dpurdie 360
                                    mReleaseManager.insertPackageMetrics(mRtagId, mReporting.packageName, mReporting.packageExtension, metrics );
361
 
362
                                    //
363
                                    //    Info reporting
364
                                    //    Send an email to track build system usage - may be noise
365
                                    //
366
                                    mReporting.errMsg = null;
7033 dpurdie 367
                                    mLogger.error("run calling emailBuildComplete");
6914 dpurdie 368
                                    mPhase.setPhase("Post Build Email");
369
                                    emailPostBuild(mRippleEngine, false);
370
 
371
                                    //---------------------------------------------------------------
372
                                    //    All done
373
                                    //    The package has been built and released
374
                                    mPhase.setPhase("Build Complete");
375
                                }
376
                                catch( Exception e)
377
                                {
378
                                    // Some form of error has occurred. Types include
379
                                    //    Test build (Treated as an error so that dpkg_archive gets removed)
380
                                    //        buildErrorOccurred - True
381
                                    //        publishError - False    
382
                                    //    Build Error - Package was not fully published to dpkg_archive
383
                                    //        buildErrorOccurred - True
384
                                    //        publishError - False
385
                                    //     
386
                                    //    Badly formed VCS tag (Error Publishing to Version Control)
387
                                    //        buildErrorOccurred - False
388
                                    //        publishError - True    
389
                                    //    Error Publishing to Release Manager
390
                                    //        buildErrorOccurred - False
391
                                    //        publishError - True    
392
                                    //    Error inserting package metrics
393
                                    //        buildErrorOccurred - False
394
                                    //        publishError - True
395
                                    //    Error inserting unit test results
396
                                    //        buildErrorOccurred - False
397
                                    //        publishError - True
398
                                    // 
399
                                    // Uses
400
                                    //    buildErrorOccurred      - Package not in dpkg_archive as expected (or was a test build)
401
                                    //                              Email should have been sent to the user
402
                                    //    publishError            - Could not publish to Release Manager
403
                                    //                              Post build error. Email has not been sent to user
404
                                    //                              Takes precedence over buildErrorOccurred
405
 
406
                                    // Insert generic message if we don't have one
407
                                    //     Should only occur under unexpected conditions
408
                                    if (mReporting.errMsg == null || mReporting.errMsg.isEmpty())
409
                                    {
410
                                        mReporting.errMsg = "Error publishing to Release Manager";
411
                                        mReporting.errMsgDetail = mPhase.sText;
412
                                    }
413
 
414
                                    // Indicate some form of build error
415
                                    if ( ! mReporting.isaTestBuild )
416
                                    {
417
                                        mPhase.setPhase("Update Build Instance");
418
                                        mReleaseManager.updateBuildInstance(mReporting.buildId, 0, publishError ? BuildResult.SystemError :BuildResult.BuildError );
419
                                    }
420
 
421
                                    // 
422
                                    // Delete the dpkg_archive entry - the package is a dud
423
                                    //
424
                                    mPhase.setPhase("Delete package from archive");
7033 dpurdie 425
                                    mLogger.error("Delete package from archive");
6914 dpurdie 426
                                    deletePackageVersion();
427
 
428
                                    //    A publishing error. The error occurred, after the build, in the RM publishing
429
                                    //        We won't have a log file, but we will have a rootCause
430
                                    //    Exclude package from the build
431
                                    //        Unless its a test build (handled within mReleaseManager.excludeFromBuild) 
432
                                    //
433
                                    if ( publishError  )
434
                                    {
7033 dpurdie 435
                                        mLogger.error("an error occurred publishing to Version Control or Release Manager");
6914 dpurdie 436
 
437
                                        //  Post Build Error
438
                                        //  eMails have not been sent by the ABT class as the error has occurred outside of that process
439
                                        mPhase.setPhase("Post Build Failure Email");
440
                                        emailPostBuild(mRippleEngine, true);
441
 
7033 dpurdie 442
                                        mLogger.error("run calling excludeFromBuild");
6914 dpurdie 443
                                        mPhase.setPhase("Excluded from build");
444
                                        mReleaseManager.excludeFromBuild(false, 
445
                                                mReporting.packageVersionId, 
446
                                                null, 
447
                                                mReporting.rtagId, 
448
                                                null, 
449
                                                mReporting.errMsg, 
450
                                                null, 
451
                                                false, mReporting.isaTestBuild);
452
 
453
                                    }
454
                                    else if ( buildErrorOccurred )
455
                                    {
456
                                        //    Build Error Occurred
457
                                        //        Package has not been built on all configured platforms
458
                                        //        Under normal circumstances, this root cause will be masked by a previously reported error
459
                                        //        Under abnormal circumstances amidst build activity such as:
460
                                        //            - slave build machine reboots
461
                                        //            - slave build machines with a read only file system
462
                                        //        The rootCause is required to keep the end user informed
463
                                        //
464
                                        //    Use excludeFromBuild such that this call will not supersede existing entries
465
                                        //    In this manner the log file/cause provided here will only be used if we haven't
466
                                        //    already excluded this package from the build
467
 
468
                                        //    If we have a log file, then provide it to the user, else insert a generic message
469
 
470
                                        mReporting.errMsg = (mReporting.buildFailureLogFile == null) ? "Buildtool env error occurred. Attempt build again" : null;
471
 
7033 dpurdie 472
                                        mLogger.error("run calling excludeFromBuild"); 
6914 dpurdie 473
                                        mPhase.setPhase("Excluded from build");
474
                                        mReleaseManager.excludeFromBuild(false, 
475
                                                mReporting.packageVersionId, 
476
                                                mReporting.packageVersion,
477
                                                mReporting.rtagId, 
478
                                                null, 
479
                                                mReporting.errMsg, 
480
                                                mReporting.buildFailureLogFile, 
481
                                                false, mReporting.isaTestBuild);
482
                                    }
483
                                    else
484
                                    {
485
                                        //  Not a buildError and not a publishing Error
486
                                        //      Don't know how we got here - I don't think we can
487
                                        //      Will cause an indefinite pause !
488
                                        throw new Exception("an error occurred publishing to Version Control or Release Manager");
489
 
490
                                    }
491
                                } // End Catch
492
                            }
493
 
494
                            if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )            
495
                            {
496
                                throw new ExitException();
497
                            }
498
                            mLogger.info("run coordinate slave threads returned");
499
                        }
500
 
501
 
502
                        //---------------------------------------------------------------
503
                        //  Start of a new build cycle
504
                        //      Determine if the daemon has been paused.
505
                        //      Set RunLevel.IDLE (within allowedToProceed)
506
                        //
7033 dpurdie 507
                        mLogger.error("run calling allowedToProceed");
6914 dpurdie 508
                        mPhase.setPhase("allowedToProceed");
509
                        mReleaseManager.discardVersion();
510
                        mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
511
                        allowedToProceed(true);
512
                        mLogger.info("run allowedToProceed returned");
513
 
514
                        if ( mUnitTest.compareTo("unit test allowed to proceed") == 0 )            
515
                        {
516
                            throw new ExitException();
517
                        }
518
 
519
                        //  Set up mReleaseConfigCollection
520
                        //  This will be used when creating a build file
7033 dpurdie 521
                        mLogger.error("Collect fresh MetaData");
6914 dpurdie 522
                        mPhase.setPhase("collectMetaData");
523
                        mRippleEngine.collectMetaData();
524
 
525
                        //---------------------------------------------------------------
526
                        //  Plan the next build
527
                        //      Snap current Release Sequence Number
528
                        //      Determine what is to be built
529
                        //      Generate build files
7033 dpurdie 530
                        mLogger.error("run calling planRelease");
6914 dpurdie 531
                        mPhase.setPhase("Plan Release", 600);
7169 dpurdie 532
                        mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_PLANNING);
6914 dpurdie 533
                        mReleaseSeqNum =  mReleaseManager.queryReleaseSeqNum(mRtagId, mRconId, BuildDaemon.mHostname); 
534
                        mRippleEngine.planRelease(!mLastBuildWasBenign);
535
 
536
                        // get the build file from the ripple engine
537
                        mPhase.setPhase("Get Build File", 10);
538
                        mMasterBuildFile = mRippleEngine.getFirstBuildFileContent();
539
 
540
                    }
541
                }
542
 
543
                //---------------------------------------------------------------
544
                //  Check that we are good to proceed with the build
545
                //      Check environment
546
                //      Ensure we have enough disk space
547
                //     
7033 dpurdie 548
                mLogger.error("run calling checkEnvironment"); 
6914 dpurdie 549
                mPhase.setPhase("checkEnvironment");
550
                checkEnvironment();
551
                mLogger.info("run checkEnvironment returned");
552
 
553
                if ( mUnitTest.startsWith("unit test check environment") ) 
554
                {
555
                    throw new ExitException();
556
                }
557
 
558
                mLogger.info("run generated build files");
559
                // Start of a build cycle. Set new log file to capture entire build log
560
                mPhase.setPhase("Start Build Cycle");
561
                flagStartBuildCycle();
562
                mBuildDuration.reset();
563
                mReporting.resetData();
564
                mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_ACTIVE);
565
                mReleaseManager.setCurrentPackageBeingBuilt(mRconId, mMasterBuildFile.mPkgId, mMasterBuildFile.mPvId);
566
 
567
                // Save the buildfile
7033 dpurdie 568
                mLogger.error("Save buildfile");
6914 dpurdie 569
                mPhase.setPhase("Save buildfile");
570
                saveBuildFile(mMasterBuildFile.content);
571
 
572
                // Quick Test to validate the provided Version Control tag/label
573
                mPhase.setPhase("Validate Version Tag");
574
                if ( deliverChange("AbtTestPath", true, false) )
575
                {
576
 
577
                    //---------------------------------------------------------------
578
                    //    Notify all slaves that there is work to be done
579
                    //      This is done by publishing a buildfile for them to consume
580
                    //      A NonGeneric build will be done with a real build file on all machines
581
                    //      Otherwise do a Dummy build on all Machines
582
                    //
583
                    mPhase.setPhase("Notify slaves of work", 10);
584
                    if ( mMasterBuildFile.state != BuildFileState.NonGeneric)
585
                    {
586
                        // publish a dummy build file for either generic or dummy cases
587
                        // this results in the slave not running ant
7033 dpurdie 588
                        mLogger.error("run calling publishBuildFile on dummy");
6914 dpurdie 589
                        mMasterBuildFile.content = mDummyBuildFileContent;
590
                    }
591
                    else
592
                    {
593
                     // publish the build file
7033 dpurdie 594
                        mLogger.error("run calling publishBuildFile");    
6914 dpurdie 595
                    }
596
                    mReleaseManager.publishBuildFile(mRtagId, mMasterBuildFile);                    
597
 
598
 
599
                    if ( mUnitTest.compareTo("unit test generate build files") == 0 )
600
                    {
601
                        throw new ExitException();
602
                    }
603
 
604
                    mLogger.info("run changed run levels");
605
 
606
                    //---------------------------------------------------------------
607
                    //  Build the package
608
                    //      Setup the workspace
609
                    //      Build the package - deliver change to product baseline
610
                    //
7033 dpurdie 611
                    mLogger.error("Build Package "  + mReporting.packageName + "_" + mReporting.packageVersion);
6914 dpurdie 612
 
613
                    mLogger.info("run calling setViewUp");
614
                    mPhase.setPhase("Setup View for build");
615
                    deliverChange("AbtSetUp", true, false);
616
 
617
                    mLogger.info("run calling deliverChange - the actual build");
618
                    mPhase.setPhase("Build Package");
619
                    deliverChange(null, true, false);
620
                    mLogger.info("run deliverChange returned");
621
                }
622
 
623
                mLastBuildWasBenign = false;
624
                if ( mMasterBuildFile.state == BuildFileState.Dummy)
625
                {
626
                    // no build requirement, so let things settle
627
                    mLogger.warn("run no build requirement, so let things settle");
628
                    mLastBuildWasBenign = true;
629
                }        
630
            }
631
            //---------------------------------------------------------------
632
            //    Build loop exception handling (only)
633
            //
634
            catch( SQLException e )
635
            {
636
                //  Oracle connection issues
637
                //  Request a prolonged sleep at the start of the build loop
7033 dpurdie 638
                mLogger.error("run oracle connection issues");
6914 dpurdie 639
                mException = true;
640
            }
641
            catch( ExitException e )
642
            {
643
                mLogger.warn("run ExitException");
644
                exit = true;
645
            }
646
            catch( InterruptedException e )
647
            {
648
                mLogger.warn("run InterruptedException");
649
                Thread.currentThread().interrupt();
650
            }
651
            catch (BuildSystemException e) {
652
                // BuildSystem exception - a (possibly) correctable error
653
                // Flag as recoverable
654
                //    - Can't create XML build file
655
                //    - 
656
                // 
7033 dpurdie 657
                mLogger.error("run BuildSystemException");
6914 dpurdie 658
                mPhase.setPhase("BuildSystemException indefinitePause");
659
                notifyIndefinitePause(e.getMessage());
660
                mReleaseManager.indefinitePause(false);
661
                mException = true;
662
                mRecoverable = true;
663
 
664
            }
665
            catch( BuildToolException e)
666
            {
667
                // Buildtool exception - an uncorrectable error
668
                //    - Can't parse XML build file
669
                // 
7033 dpurdie 670
                mLogger.error("run BuildToolException");
6914 dpurdie 671
                mPhase.setPhase("BuildToolException indefinitePause");
672
                notifyIndefinitePause(e.getMessage());
673
                mReleaseManager.indefinitePause(false);
674
                mException = true;
675
            }
676
            catch( Exception e )
677
            {
678
                //  Uncaptured exception
679
                //  These are not good. Current mechanism to handle this condition is:
680
                //      1) Email build system administrator
681
                //      2) Pause the build system
682
                //  
683
                mLogger.error("run indefinitePause " + e.toString());
684
 
685
                // DEVI 51366 force sleep at beginning of while loop
686
                mException = true;
687
 
688
                String cause = e.getMessage();
689
                if ( cause == null || cause.compareTo("null") == 0 )
690
                {
691
                    cause = "Internal Error: " + e.toString();
692
                }
693
 
694
                try
695
                {
696
                    // notify first
697
                    // many reasons for indefinite pause, including database related, so do database last
698
                    mRecoverable = false;
699
 
700
                    if ( cause.compareTo(Package.mRecoverable) == 0 )
701
                    {
702
                        mRecoverable = true;
703
                    }
704
 
705
                    mPhase.setPhase("Notify indefinitePause");
706
                    notifyIndefinitePause(cause);
707
                    mReleaseManager.indefinitePause(mRecoverable);
708
                    mReleaseManager.updateBuildInstance(mReporting.buildId, 0, BuildResult.SystemError );
709
                }
710
                catch( Exception f )
711
                {
712
                    mLogger.error("run indefinitePause failed");
713
                }
714
            }
715
        }
716
        try {
717
            mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
718
        } catch (Exception e) {
719
            mLogger.error("Exception in clearCurrentPackageBeingBuilt:" + e.getMessage());
720
        }
721
        mPhase.setPhase("Exit Thread");
722
    }
723
 
724
    /**   Delete a specified version of a package from dpkg_archive
725
     *    Used during error processing to cleanup packages that did not build correctly
726
     *    
727
     *    The package-version is in dpkg_archive. This may be on a remote server
728
     *    Execute the deletion command on the remote server as it will be a lot faster
729
     *    for large packages.
730
     *    
731
     *    Ensure that the file system cache is cleared before we attempt to look
732
     *    for the directory
733
     */
734
    private void deletePackageVersion()
735
    {
736
 
737
        //    Setup a Remote Execution environment
738
        //    The logging interface is is hard part
739
        RemoteExecution mRemoteExecution = new RemoteExecution(new LogOutput(){
740
 
741
            @Override
742
            public void data(String message) {
743
                mLogger.info(message);
744
            }
745
 
746
            @Override
747
            public void fatal(String message) {
7033 dpurdie 748
                mLogger.error(message);
6914 dpurdie 749
            }
750
 
751
            @Override
752
            public void info(String message) {
753
                mLogger.info(message);
754
            }});
755
 
756
 
757
        //    Execute the remote command
758
        //    This is a best effort deletion - can't really handle conditions
759
        //    where the command fails.
760
        CommandBuilder cmd = new CommandBuilder();
761
 
762
        cmd.add("sudo","-n", "-u", "buildadm", "/home/releasem/sbin/jatsTool", "assemble_dpkg");
763
        cmd.add("-DeleteVersion");
764
        cmd.add(!ReleaseManager.getUseMutex(), "-testArchive");
765
        cmd.add("'-pname=" + mReporting.packageName + "'");
766
        cmd.add("'-pversion=" + mReporting.packageVersion + "'");
767
 
7033 dpurdie 768
        mLogger.error("run remote command to delete " + mReporting.packageName +", "+ mReporting.packageVersion);
6914 dpurdie 769
        int rv = mRemoteExecution.execute(cmd.toString());
7033 dpurdie 770
        mLogger.error("run remote command to delete. Returned " + rv);
6914 dpurdie 771
 
772
        //    Belt and Braces
773
        //    Ensure that the package-version has been deleted, 
774
        //    and if not then try to delete it the slow way.
775
        //
776
        //    Note: Need to flush NFS cache before we check existence 
777
 
778
        String dpkgArchiveEntry = utilities.catDir(Package.mGbeDpkg, mReporting.packageName, mReporting.packageVersion);
779
        File dpkgArchiveEntryFile = utilities.freshFile(dpkgArchiveEntry);
780
        mLogger.info("run checking existence of " + dpkgArchiveEntry);
781
 
782
        if ( dpkgArchiveEntryFile.exists() )
783
        {
784
            if ( dpkgArchiveEntryFile.isDirectory() )
785
            {
7033 dpurdie 786
                mLogger.error("run calling deleteDirectory on " + dpkgArchiveEntryFile);                      
6914 dpurdie 787
                deleteDirectory(dpkgArchiveEntryFile);
788
            }
789
        }
790
    }
791
 
792
    /**   Sends email notification and mark the successful completion of a build
793
     *    Used simply to keep an email trail of build operations
794
     */
795
    public void emailPostBuild( RippleEngine rippleEngine, boolean isaError )
796
    {
797
        mLogger.debug("emailPostBuild");
798
        String subject;
799
        String emailTo;
800
        String mailBody = "";
801
 
802
        if (isaError)
803
        {
804
            subject = "BUILD FAILURE on package " + mReporting.packageName + " " + mReporting.packageVersion;
805
            emailTo = mReporting.packageOwners;
806
            mailBody="An error occured within the build system after the package had been built<p><hr>";
807
        }
808
        else
809
        {
810
            subject = "BUILD SUCCESS on package " + mReporting.packageName + " " + mReporting.packageVersion;
811
            emailTo = rippleEngine.getMailSender();
812
        }
813
 
814
        //  Cleanup the dependency string
815
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
816
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
817
        String depends = mReporting.packageDepends.replace("','", " ");
818
        depends = depends.replace("';'",indent);
819
        depends = depends.replace("'","");
820
 
821
        //  Cleanup the build standard string
822
        //      Expecting win32: jats all;linux_i386: jats prod
823
        String buildStandards = mReporting.packageBuildInfo;
824
        buildStandards = buildStandards.replace(";",indent);
825
 
826
        mailBody += "Release      : " + rippleEngine.mBaselineName + "<br>" +
827
                "Package      : " + mReporting.packageName + "<br>" +
828
                "Version      : " + mReporting.packageVersion + "<br>";
829
        if (isaError)
830
        {
831
            mailBody += "Cause        : " + mReporting.errMsg + "<br>";
832
            if (mReporting.errMsgDetail != null && mReporting.errMsgDetail.length() > 0)
833
            {
834
                mailBody += "Detail       : " + mReporting.errMsgDetail + "<br>";
835
            }
836
        }
837
 
838
        mailBody += "RM Link      : " + CreateUrls.generateRmUrl(mRtagId,mReporting.packageVersionId) + "<br>" +
839
                "PVID         : " + mReporting.packageVersionId + "<br>" +
840
                "VcsTag       : " + mReporting.newVcsTag + "<br>" +
841
                "Ripple       : " + (mReporting.isRipple ? "Yes" : "No") + "<br>" +
842
                "Dependencies : " + indent + depends + "<br>" +
843
                "Build Standards : " + indent + buildStandards;
844
 
845
        mailBody += "<p><hr>";
846
        try
847
        {
7155 dpurdie 848
            Smtpsend.send( rippleEngine.getMailServer(),    // mailServer
6914 dpurdie 849
                    rippleEngine.getMailSender(),           // source
7155 dpurdie 850
                    emailTo,                                // target - send to package owners, or myself
6914 dpurdie 851
                    rippleEngine.getMailSender(),           // cc
7155 dpurdie 852
                    null,                                   // bcc
853
                    subject,                                // subject
854
                    mailBody,                               // body
855
                    null                                    // attachment
6914 dpurdie 856
                    );
857
        }
858
        catch( Exception e )
859
        {
860
            mLogger.warn("Email Failure: emailPostBuild:" + e.getMessage());
861
        }
862
        mLogger.debug("emailPostBuild. Returning");
863
    }
7155 dpurdie 864
 
865
    /**
866
     * End of Processing for a Test Build
867
     *     - sends email notification
868
     *     - marks the instruction complete in the database
869
     */
870
    public void completeTestBuild(RippleEngine rippleEngine, boolean success) throws SQLException, Exception
871
    {
872
        mLogger.debug("completeTestBuild");
6914 dpurdie 873
 
7155 dpurdie 874
        if (!mReporting.isaTestBuild)
875
        {
876
            mLogger.info("completeTestBuild. Not Build Instruction");
877
            return;
878
        }
879
 
880
        //  Email Subject
881
        String subject = (success ? "TEST BUILD COMPLETED SUCCESSFULLY" : "TEST BUILD FAILED") 
882
                + " on package "
883
                + mReporting.packageName +  mReporting.packageExtension;
884
 
885
        //  Cleanup the dependency string
886
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
887
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
888
        String depends = mReporting.packageDepends.replace("','", " ");
889
        depends = depends.replace("';'",indent);
890
        depends = depends.replace("'","");
891
 
892
        //  Cleanup the build standard string
893
        //      Expecting win32: jats all;linux_i386: jats prod
894
        String buildStandards = mReporting.packageBuildInfo;
895
        buildStandards = buildStandards.replace(";",indent);
896
 
897
        // Email Body
898
        String mailBody = "";
899
        if ( !success )
900
        {
901
            mailBody += "Test build issues are identified in preceding build failure email.<p>"; 
902
        }
903
        mailBody += "Release: " + rippleEngine.mBaselineName + "<br>" 
904
                  + "Package: " + mReporting.packageName +  mReporting.packageExtension + "<br>" 
905
                  + "Rm Ref: " + CreateUrls.generateRmUrl(mReporting.rtagId, mReporting.packageVersionId) + "<br>" 
906
                  + "VcsTag: " + mReporting.vcsTag + "<br>"
907
                  + "Dependencies : " + indent + depends + "<br>"
908
                  + "Build Standards : " + indent + buildStandards;
909
 
910
        mailBody += "<p><hr>";
911
        try
912
        {
913
            mLogger.error("completeTestBuildEmail Server: {}", rippleEngine.getMailServer());
914
            mLogger.error("completeTestBuildEmail Sender: {}", rippleEngine.getMailSender());
915
            mLogger.error("completeTestBuildEmail Target: {}", mReporting.packageOwners);
916
 
917
            Smtpsend.send(rippleEngine.getMailServer(),     // mailServer
918
                    rippleEngine.getMailSender(),           // source
919
                    mReporting.packageOwners,               // target
920
                    rippleEngine.getMailSender(),           // cc
921
                    null,                                   // bcc
922
                    subject,                                // subject
923
                    mailBody,                               // body
924
                    null                                    // attachment
925
            );
926
        } catch (Exception e)
927
        {
928
            mLogger.warn("Email Failure: completeTestBuild:{}", e.getMessage());
929
        }
930
 
931
        // Update the Release Manager Database
932
        mReleaseManager.markDaemonInstCompleted(mReporting.testBuildId);
933
        mLogger.error("completeTest. Returning");
934
    }
935
 
936
 
6914 dpurdie 937
    /**returns 'M'
938
     */
939
    protected char getMode()
940
    {
941
        mLogger.debug("getMode");
942
        return 'M';
943
    }
944
 
945
 
946
}