Subversion Repositories DevTools

Rev

Rev 7502 | Rev 7514 | 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;
7506 dpurdie 20
import java.io.FileNotFoundException;
7489 dpurdie 21
import java.io.IOException;
6914 dpurdie 22
import java.io.InputStreamReader;
23
import java.sql.SQLException;
24
import java.util.Iterator;
25
 
7033 dpurdie 26
import org.slf4j.Logger;
27
import org.slf4j.LoggerFactory;
6914 dpurdie 28
 
29
/**Master Thread sub component
30
 */
31
public class MasterThread extends BuildThread
32
{
33
 
34
    /**Logger
35
     * @attribute
36
     */
7033 dpurdie 37
    private static final Logger mLogger = LoggerFactory.getLogger(MasterThread.class);
6914 dpurdie 38
 
39
    /** Current BuildFile
40
     * 
41
     */
42
    private BuildFile mMasterBuildFile = new BuildFile();
43
 
44
    /** Measure the duration of the current build
45
     * 
46
     */
47
    private ElapseTime mBuildDuration = new ElapseTime();
48
 
49
    /**constructor
50
     * @param rtagId          - Identifies the Release
51
     * @param rconId          - Identifies the Controlling entry
52
     * @param releaseManager  - A ReleaseManager entry to use
53
     * @param unitTest        - Unit Test data 
54
     */
55
    public MasterThread(int rtagId, int rconId, ReleaseManager releaseManager, String unitTest)
56
    {
57
        super(rtagId, rconId, releaseManager, unitTest);
58
        mLogger.warn("MasterThread rtag_id " + rtagId + " rcon_id " + rconId);
59
    }
60
 
61
    /**implements the sequence diagrams coordinate slave threads, generate build files, allowed to proceed, check environment
62
     */
63
    public void run()
64
    {
65
        Integer id = Integer.valueOf(mRtagId);
66
        setName(id.toString());
67
        mLogger.warn("Master Thread run");
68
        boolean exit = false;
69
        mRippleEngine = new RippleEngine(mReleaseManager, mRtagId, true);
70
 
71
        while(!exit)
72
        {
73
            try
74
            {
7176 dpurdie 75
                mLogger.warn("run calling sleepCheck");
6914 dpurdie 76
                mPhase.setPhase("sleepCheck");
77
                sleepCheck();
78
 
7176 dpurdie 79
                mLogger.warn("run calling rippleEngine.collectMetaData");
6914 dpurdie 80
                mPhase.setPhase("collectMetaData", 600);
81
                mRippleEngine.collectMetaData();
82
 
83
                if ( Thread.currentThread().isInterrupted() )
84
                {
85
                    mLogger.warn("run is interrupted");
86
                    // unit test technique
87
                    throw new ExitException();
88
                }
89
 
90
                if ( mUnitTest.compareTo("unit test spawn thread") == 0)
91
                {
92
                    throw new Exception();
93
                }
94
 
95
                if ( !mUnitTest.startsWith("unit test check environment"))
96
                {
97
                    if ( mUnitTest.compareTo("unit test generate build files") != 0)
98
                    {
99
                        if ((mUnitTest.compareTo("unit test allowed to proceed") != 0) &&
100
                                (mUnitTest.compareTo("unit test not allowed to proceed") != 0) &&
101
                                (mUnitTest.compareTo("unit test exit") != 0))
102
                        {
103
                            //---------------------------------------------------------------
104
                            //  Wait for all Slaves to enter waiting or paused state
105
                            //      They may be building
106
                            //      They may be starting up
107
                            //
7176 dpurdie 108
                            mLogger.warn("run changing run level to WAITING (New) for rcon_id {}", mRconId);
6914 dpurdie 109
                            mPhase.setPhase("Wait for Slave Threads");
110
                            mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_WAITING);
111
 
112
                            while (true) 
113
                            {
114
                                StringBuilder waitList = new StringBuilder();
115
                                mLogger.info("run calling mReleaseManager.queryRunLevel");
116
                                mReleaseManager.queryRunLevel(mRtagId);
117
 
118
                                //	Process all run entries
119
 
120
                                for (Iterator<RunLevelData> it = mReleaseManager.mRunLevelCollection.iterator(); it.hasNext(); )
121
                                {
122
                                    RunLevelData rl = it.next();
123
 
124
                                    //
125
                                    // Only examine Slaves.
126
                                    // This is being run on a Master and at this point the Master is not waiting
127
                                    // If there are multiple (misconfigured) Masters, then we can get confused
128
                                    //
129
                                    // If I am no longer a Master we will process till the end of the build cycle
130
                                    // at which point it will be detected.
131
                                    //
132
                                    // If there are other Masters, then we assume that they are not waiting
133
                                    //
134
 
135
                                    // Ignore myself. I am not waiting. I am asking the questions
136
                                    if ( rl.get_rcon_id() == mRconId) {
137
                                        continue;
138
                                    }
139
 
140
                                    // Ignore other Master. They should not be waiting.
141
                                    if ( rl.isMaster()) {
142
                                        continue;
143
                                    }
144
 
145
                                    //
146
                                    // A slave that is 'Paused' is not processing a package
147
                                    //      It will have been included in the build-set, so we must wait for
148
                                    //      the pause to be removed.
149
                                    //
150
                                    // A slave that is 'Waiting' must also have no BuildFile present
151
                                    //      This signals that the buildfile has been taken by the slave
152
                                    // 
153
                                    if (! (rl.isAt(BuildState.DB_WAITING) && !rl.hasBuildFile() )  )
154
                                    {
155
                                        // A non-waiting slave has been found
156
                                        waitList.append(" ");
157
                                        waitList.append(rl.get_rcon_id());
158
                                    }
159
                                }
160
 
161
 
162
                                if ( waitList.length() > 0 )
163
                                {
164
                                    // One or more slaves still processing ...
165
                                    if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )
166
                                    {
167
                                        Thread.currentThread().interrupt();
168
                                    }
169
                                    else
170
                                    {
171
 
172
                                        mLogger.warn("Waiting 3 seconds for slaves:" + waitList.toString() );
173
                                        Thread.sleep(3000);
174
                                        mLogger.info("run sleep returned");
175
                                    }
176
                                    continue;
177
                                }
178
                                else
179
                                {
180
                                    // All slaves have completed there tasks
181
                                    break;
182
                                }
183
                            }
184
 
185
                            if ( mUnitTest.compareTo("unit test coordinate slave threads") == 0 )
186
                            {
187
                                throw new ExitException();
188
                            }
189
 
190
                            //---------------------------------------------------------------
191
                            //    Publish Package Build Results
192
                            //        Indicate to RM that we are publishing
193
                            //        Ensure that all build machines have placed a marker in dpkg_archive
194
                            //        Save updated build files into VCS
195
                            // 
7176 dpurdie 196
                            mLogger.warn("run changing run level to PUBLISHING for rcon_id {}", mRconId);
6914 dpurdie 197
                            mPhase.setPhase("Publishing");
198
                            mRunLevel.persist(mReleaseManager, mRconId, BuildState.DB_PUBLISHING);
199
 
200
                            mLogger.info("run calling deliverChange on AbtPublish");
201
                            deliverChange("AbtPublish", true, false);
202
 
203
                            //---------------------------------------------------------------
204
                            //    TearDown the build workspace
205
                            //        Remove the build workspace
206
                            //        Save build log files
207
                            //        Don't update the Reporting Information as it will null out
208
                            //        some essential information that has been collected.
209
                            //
210
                            mLogger.info("run calling deliverChange on AbtTearDown");
211
                            mPhase.setPhase("AbtTearDown");
212
                            deliverChange("AbtTearDown", false, true);
213
 
214
                            // Delete the build file now
215
                            //  This will prevent any chance of multiply publishing a package version
216
                            deleteBuildFile();
217
 
218
 
219
                            //---------------------------------------------------------------
220
                            //    Update Release Manager (publish to Release Manager)
221
                            //
222
                            mPhase.setPhase("Update Release Manager");
223
                            if ( mReporting.packageName != null )
224
                            {
225
                                // A dummy build file did not apply
226
                                // Publishing is done outside ant by design
227
                                //      Do ALL Release Manager work outside ant (and JATS)
228
 
229
                                boolean buildErrorOccurred = true;
230
                                boolean publishError = true;
231
 
232
                                try
233
                                {
234
                                    //  Create a build instance entry in the Release Manager database
235
                                    //        Create one per build
236
                                    //        mReporting.packageVersionId will have been updated if this is a new package-version
237
                                    //        Save the build id
238
                                    mPhase.setPhase("Create Build Instance");
239
                                    mReporting.buildId = mReleaseManager.createBuildInstance(
240
                                            mRtagId, 
241
                                            mReporting.packageVersionId,
7253 dpurdie 242
                                            mReporting.buildReason,
243
                                            mReporting.buildRef);
6914 dpurdie 244
                                    //
245
                                    //  Locate and collect the unit test results
246
                                    //
247
                                    mPhase.setPhase("Parse Unit Test Results");
248
                                    BuildTestResults btr = new BuildTestResults(System.getenv("GBE_DPKG"), mReporting, mLogger);
249
                                    mReleaseManager.insertTestResults(mReporting.buildId, btr);
250
 
251
                                    if ( mReporting.isaTestBuild )
252
                                    {
253
 
254
                                        //    Test Build
255
                                        //    Notify the user requesting the build
256
                                        //        Build Failure emails have already been sent
257
                                        //
258
                                        mLogger.info("run completing test build on " + mReporting.packageName + mReporting.packageExtension);
259
                                        mPhase.setPhase("Report Test Build Complete");
7155 dpurdie 260
                                        completeTestBuild(mRippleEngine, mReporting.isFullyPublished);
6914 dpurdie 261
 
262
                                        //
263
                                        //  Determine the total time taken by the build
264
                                        //      Done as late a possible in the process
265
                                        //      Does not include planning time
266
                                        //      Does not handle case where build cycle is broken
267
                                        //      Only record for successful tests. Don't want to record short build times on failure
268
                                        //      in particular if the package has been released. Would be OK for a WIP, but how to identify these
269
                                        if ( mReporting.isFullyPublished)
270
                                        {
271
                                            int buildDuration = mBuildDuration.toIntSecs();
7176 dpurdie 272
                                            mLogger.warn("Build Duration:{}", buildDuration);
6914 dpurdie 273
                                            mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
274
                                        }
275
 
276
                                        mPhase.setPhase("Update Build Instance for Test");
277
                                        mReleaseManager.updateBuildInstance(mReporting.buildId, 0, mReporting.isFullyPublished ? BuildResult.Complete :BuildResult.BuildError );
7333 dpurdie 278
 
279
                                        mPhase.setPhase("Insert BuildInfo for Test");
280
                                        insertBuildInfo(true);
6914 dpurdie 281
 
282
                                        // ... and clean up the mess in the archive
283
                                        publishError = false;
284
                                        throw new Exception();                    
285
                                    }
286
 
287
                                    //    Package not fully published
288
                                    //    An error has occurred in the building of the package
289
                                    if ( !mReporting.isFullyPublished )
290
                                    {
291
                                        mLogger.info("run build error occurred on " + mReporting.packageName + mReporting.packageVersion);
292
 
293
                                        // ... and clean up the mess in the archive
294
                                        publishError = false;
295
                                        throw new Exception();
296
                                    }
297
 
298
                                    //---------------------------------------------------------------
299
                                    //  Package was successfully built and published into dpkg_archive by all daemons
300
                                    //    Update Release Manager - formally release the package
301
                                    //    Insert Package Metrics
302
                                    //    Insert Unit Test Results
303
                                    buildErrorOccurred = false;
304
 
305
                                    //
306
                                    //    Detect Badly formed VCS label returned by the builder
307
                                    //      Have had zero length values returned
308
                                    //      Treat as a publishing error
309
                                    //
310
                                    if ( mReporting.newVcsTag == null || mReporting.newVcsTag.isEmpty() )
311
                                    {
7176 dpurdie 312
                                        mLogger.error("run package not labelled in Version Control on {}{}",mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 313
                                        mReporting.errMsg = "Error publishing to Version Control System";     // Max 50 Characters
314
                                        throw new Exception();
315
                                    }
316
 
317
 
318
                                    // Publish to release manager
319
                                    //    On error mReporting.errMsg will contain error string
320
                                    //    Publishing errors only affect the current package
321
                                    //
7176 dpurdie 322
                                    mLogger.warn("run calling mReleaseManager.autoMakeRelease");
6914 dpurdie 323
                                    mPhase.setPhase("autoMakeRelease");
324
                                    publishError =  mReleaseManager.autoMakeRelease(mReporting);
325
                                    if ( publishError )
326
                                    {
7176 dpurdie 327
                                        mLogger.error("autoMakeRelease publishError: {}", mReporting.errMsg);
6914 dpurdie 328
                                        throw new Exception();
329
                                    }
330
 
331
                                    //
332
                                    //  Determine the total time taken by the build
333
                                    //      Done as late a possible in the process
334
                                    //      Does not include planning time
335
                                    //      Does not handle case where build cycle is broken
336
                                    //
337
                                    int buildDuration = mBuildDuration.toIntSecs();
7176 dpurdie 338
                                    mLogger.warn("Build Duration:{}", buildDuration);
6914 dpurdie 339
                                    mReleaseManager.updateBuildDuration(mReporting.packageVersionId, buildDuration);
340
 
341
                                    //
342
                                    //    Update the Build Instance information
343
                                    //    If this has been a ripple then the pv_id of the build needs to be associated with
344
                                    //    the newly created version
345
 
346
                                    mPhase.setPhase("Update Build Instance");
347
                                    mReleaseManager.updateBuildInstance(mReporting.buildId, mReporting.packageVersionId, BuildResult.Complete );
348
 
349
                                    //
350
                                    //    Insert package metrics into Release Manager
351
                                    //        Metrics have been placed in a file in a format suitable for RM
352
                                    //
353
                                    mReporting.errMsg = "Error publishing Package Metrics";     // Max 50 Characters
354
                                    mPhase.setPhase("Insert Metrics");
7506 dpurdie 355
                                    insertBuildMetrics();
7333 dpurdie 356
 
357
                                    //  Insert BuildInfo
358
                                    //      New package PVID has been updated
7506 dpurdie 359
                                    mReporting.errMsg = "Error inserting BuildInfo";            // Max 50 Characters
7333 dpurdie 360
                                    mPhase.setPhase("Insert BuildInfo");
361
                                    insertBuildInfo(false);
6914 dpurdie 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
                {
7489 dpurdie 577
                    // Master will extract the package and determine the buildInfo before
578
                    // starting up slaves
579
                    //
7502 dpurdie 580
                    mLogger.warn("Setup Package {}_{}", mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 581
 
7489 dpurdie 582
                    mPhase.setPhase("Setup View for build");
583
                    deliverChange("AbtSetUp", true, false);
584
 
585
                    if ( !mMasterBuildFile.isaDummy() ) {
586
                        mPhase.setPhase("Generate buildInfo");
587
                        deliverChange("AbtBuildInfo", false, false);
588
                        processBuildInfo();
589
                    }
590
 
6914 dpurdie 591
                    //---------------------------------------------------------------
592
                    //    Notify all slaves that there is work to be done
593
                    //      This is done by publishing a buildfile for them to consume
594
                    //      A NonGeneric build will be done with a real build file on all machines
595
                    //      Otherwise do a Dummy build on all Machines
596
                    //
597
                    mPhase.setPhase("Notify slaves of work", 10);
598
                    if ( mMasterBuildFile.state != BuildFileState.NonGeneric)
599
                    {
600
                        // publish a dummy build file for either generic or dummy cases
601
                        // this results in the slave not running ant
7176 dpurdie 602
                        mLogger.warn("run calling publishBuildFile on dummy");
6914 dpurdie 603
                        mMasterBuildFile.content = mDummyBuildFileContent;
604
                    }
605
                    else
606
                    {
607
                     // publish the build file
7176 dpurdie 608
                        mLogger.warn("run calling publishBuildFile");    
6914 dpurdie 609
                    }
610
                    mReleaseManager.publishBuildFile(mRtagId, mMasterBuildFile);                    
611
 
612
                    if ( mUnitTest.compareTo("unit test generate build files") == 0 )
613
                    {
614
                        throw new ExitException();
615
                    }
616
 
617
                    //---------------------------------------------------------------
618
                    //  Build the package
619
                    //      Build the package - deliver change to product baseline
620
                    //
7176 dpurdie 621
                    mLogger.warn("Build Package {}_{}", mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 622
 
623
                    mLogger.info("run calling deliverChange - the actual build");
624
                    mPhase.setPhase("Build Package");
625
                    deliverChange(null, true, false);
626
                    mLogger.info("run deliverChange returned");
627
                }
628
 
629
                mLastBuildWasBenign = false;
630
                if ( mMasterBuildFile.state == BuildFileState.Dummy)
631
                {
632
                    // no build requirement, so let things settle
633
                    mLogger.warn("run no build requirement, so let things settle");
634
                    mLastBuildWasBenign = true;
7489 dpurdie 635
 
636
                    // If there are are no packages that are in error, then we can snapshot the
637
                    // Release as all packages will be built against each other
638
                    mReleaseManager.takeSnapshot( mRtagId );
6914 dpurdie 639
                }        
640
            }
641
            //---------------------------------------------------------------
642
            //    Build loop exception handling (only)
643
            //
644
            catch( SQLException e )
645
            {
646
                //  Oracle connection issues
647
                //  Request a prolonged sleep at the start of the build loop
7033 dpurdie 648
                mLogger.error("run oracle connection issues");
6914 dpurdie 649
                mException = true;
650
            }
651
            catch( ExitException e )
652
            {
653
                mLogger.warn("run ExitException");
654
                exit = true;
655
            }
656
            catch( InterruptedException e )
657
            {
658
                mLogger.warn("run InterruptedException");
659
                Thread.currentThread().interrupt();
660
            }
661
            catch (BuildSystemException e) {
662
                // BuildSystem exception - a (possibly) correctable error
663
                // Flag as recoverable
664
                //    - Can't create XML build file
665
                //    - 
666
                // 
7033 dpurdie 667
                mLogger.error("run BuildSystemException");
6914 dpurdie 668
                mPhase.setPhase("BuildSystemException indefinitePause");
669
                notifyIndefinitePause(e.getMessage());
670
                mReleaseManager.indefinitePause(false);
671
                mException = true;
672
                mRecoverable = true;
673
 
674
            }
675
            catch( BuildToolException e)
676
            {
677
                // Buildtool exception - an uncorrectable error
678
                //    - Can't parse XML build file
679
                // 
7033 dpurdie 680
                mLogger.error("run BuildToolException");
6914 dpurdie 681
                mPhase.setPhase("BuildToolException indefinitePause");
682
                notifyIndefinitePause(e.getMessage());
683
                mReleaseManager.indefinitePause(false);
684
                mException = true;
685
            }
686
            catch( Exception e )
687
            {
688
                //  Uncaptured exception
689
                //  These are not good. Current mechanism to handle this condition is:
690
                //      1) Email build system administrator
691
                //      2) Pause the build system
692
                //  
7176 dpurdie 693
                mLogger.error("run indefinitePause {}", e);
6914 dpurdie 694
 
695
                // DEVI 51366 force sleep at beginning of while loop
696
                mException = true;
697
 
698
                String cause = e.getMessage();
699
                if ( cause == null || cause.compareTo("null") == 0 )
700
                {
701
                    cause = "Internal Error: " + e.toString();
702
                }
703
 
704
                try
705
                {
706
                    // notify first
707
                    // many reasons for indefinite pause, including database related, so do database last
708
                    mRecoverable = false;
709
 
710
                    if ( cause.compareTo(Package.mRecoverable) == 0 )
711
                    {
712
                        mRecoverable = true;
713
                    }
714
 
715
                    mPhase.setPhase("Notify indefinitePause");
716
                    notifyIndefinitePause(cause);
717
                    mReleaseManager.indefinitePause(mRecoverable);
718
                    mReleaseManager.updateBuildInstance(mReporting.buildId, 0, BuildResult.SystemError );
719
                }
720
                catch( Exception f )
721
                {
722
                    mLogger.error("run indefinitePause failed");
723
                }
724
            }
725
        }
726
        try {
727
            mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
728
        } catch (Exception e) {
7176 dpurdie 729
            mLogger.error("Exception in clearCurrentPackageBeingBuilt: {}", e.getMessage());
6914 dpurdie 730
        }
731
        mPhase.setPhase("Exit Thread");
732
    }
733
 
7506 dpurdie 734
    /** Insert the build metrics into the Release Manager database
735
     *  Metrics have been generated by the build system ( master only )
736
     * @throws SQLException
737
     * @throws Exception
738
     */
739
    private void insertBuildMetrics() throws SQLException, Exception {
740
 
741
        try {
742
            mAbtMetricsFile = new File( String.valueOf(mRtagId) + "abtmetrics.txt");
743
            FileInputStream abtmetrics = new FileInputStream( mAbtMetricsFile);
744
            DataInputStream din = new DataInputStream( abtmetrics );
745
            InputStreamReader isr = new InputStreamReader( din );
746
            BufferedReader br = new BufferedReader( isr );
747
            String metrics = br.readLine();
748
            mLogger.warn( "execute read metrics string {}", metrics );
749
            br.close();
750
            isr.close();
751
            din.close();
752
 
753
            mLogger.warn("run calling mReleaseManager.insertPackageMetrics");                      
754
            mReleaseManager.insertPackageMetrics(mRtagId, mReporting.packageName, mReporting.packageExtension, metrics );
755
 
756
        } catch ( FileNotFoundException e) {
757
            mLogger.error("insertBuildMetrics: File not found {}", mAbtMetricsFile);
758
        } catch (IOException e) {
759
            mLogger.error("insertBuildMetrics: IOException {}", e);
760
        }
761
    }
762
 
7489 dpurdie 763
    /** Process the generated buildInfo and determine which build machines need to be used
764
     *  in the current build.
765
     *  
766
     *  ***********************************************************************
767
     *  This work has been interrupted
768
     *  It is incomplete
769
     *  Need to determine the machines that we NEED to build the package on
770
     *  Only activate those machines, not all of the slaves
771
     *  This is only a first step. The next step is to allocate a slave from a pool of
772
     *  suitable machines.
773
     *  ***********************************************************************
774
     *  
775
     *  
776
     * @throws IOException 
777
     */
778
    private void processBuildInfo() throws IOException {
779
        mBuildInfoFile = new File (mRtagId + "abtBuildInfo.properties");
780
        if ( mBuildInfoFile.exists() )
781
        {
782
            BuildInfo bi = new BuildInfo(mBuildInfoFile);
783
            mLogger.warn("Can build for: {}", bi.mPlatforms);
784
            mLogger.warn("Built for: {}", bi.mBuildPlatforms);
785
        }
786
        else
787
        {
788
            mLogger.error("No BuildInfo file. {}", mBuildInfoFile);
789
            mErrorReported = true;
790
        }
791
    }
792
 
7333 dpurdie 793
    /**
794
     * Locate the <rtagId>abtBuildInfo.properties file and insert data into Release Manager
795
     * Insert mPlatforms and mBuildPlatforms
7489 dpurdie 796
     * We can only do this after a new package version has been created.
7333 dpurdie 797
     * @param bIsaTestBuild - True. Is a test build
798
     * @throws Exception 
799
     */
800
    private void insertBuildInfo(boolean bIsaTestBuild) throws Exception {
801
 
7489 dpurdie 802
        mBuildInfoFile = new File (mRtagId + "abtBuildInfo.properties");
803
        if ( mBuildInfoFile.exists() )
7333 dpurdie 804
        {
7489 dpurdie 805
            BuildInfo bi = new BuildInfo(mBuildInfoFile);
7333 dpurdie 806
            mLogger.warn("Can build for: {}", bi.mPlatforms);
807
            mLogger.warn("Built for: {}", bi.mBuildPlatforms);
808
            mReleaseManager.insertBuildInfo(bIsaTestBuild, mReporting, bi);
809
        }
810
        else
811
        {
7489 dpurdie 812
            mLogger.warn("No BuildInfo file. {}", mBuildInfoFile);
7333 dpurdie 813
        }
814
    }
815
 
6914 dpurdie 816
    /**   Delete a specified version of a package from dpkg_archive
817
     *    Used during error processing to cleanup packages that did not build correctly
818
     *    
819
     *    The package-version is in dpkg_archive. This may be on a remote server
820
     *    Execute the deletion command on the remote server as it will be a lot faster
821
     *    for large packages.
822
     *    
823
     *    Ensure that the file system cache is cleared before we attempt to look
824
     *    for the directory
825
     */
826
    private void deletePackageVersion()
827
    {
828
 
829
        //    Setup a Remote Execution environment
830
        //    The logging interface is is hard part
831
        RemoteExecution mRemoteExecution = new RemoteExecution(new LogOutput(){
832
 
833
            @Override
834
            public void data(String message) {
835
                mLogger.info(message);
836
            }
837
 
838
            @Override
839
            public void fatal(String message) {
7033 dpurdie 840
                mLogger.error(message);
6914 dpurdie 841
            }
842
 
843
            @Override
844
            public void info(String message) {
845
                mLogger.info(message);
846
            }});
847
 
848
 
849
        //    Execute the remote command
850
        //    This is a best effort deletion - can't really handle conditions
851
        //    where the command fails.
852
        CommandBuilder cmd = new CommandBuilder();
853
 
7358 dpurdie 854
        cmd.add("sudo","-n", "-u", "pkgadm", "/home/releasem/sbin/jatsTool", "assemble_dpkg");
6914 dpurdie 855
        cmd.add("-DeleteVersion");
856
        cmd.add(!ReleaseManager.getUseMutex(), "-testArchive");
857
        cmd.add("'-pname=" + mReporting.packageName + "'");
858
        cmd.add("'-pversion=" + mReporting.packageVersion + "'");
859
 
7176 dpurdie 860
        mLogger.warn("run remote command to delete {}, {}", mReporting.packageName, mReporting.packageVersion);
6914 dpurdie 861
        int rv = mRemoteExecution.execute(cmd.toString());
7176 dpurdie 862
        mLogger.info("run remote command to delete. Returned {}", rv);
6914 dpurdie 863
 
864
        //    Belt and Braces
865
        //    Ensure that the package-version has been deleted, 
866
        //    and if not then try to delete it the slow way.
867
        //
868
        //    Note: Need to flush NFS cache before we check existence 
869
 
870
        String dpkgArchiveEntry = utilities.catDir(Package.mGbeDpkg, mReporting.packageName, mReporting.packageVersion);
871
        File dpkgArchiveEntryFile = utilities.freshFile(dpkgArchiveEntry);
7176 dpurdie 872
        mLogger.debug("run checking existence of {}",dpkgArchiveEntry);
6914 dpurdie 873
 
874
        if ( dpkgArchiveEntryFile.exists() )
875
        {
876
            if ( dpkgArchiveEntryFile.isDirectory() )
877
            {
7176 dpurdie 878
                mLogger.warn("run calling deleteDirectory on {}", dpkgArchiveEntryFile);                      
6914 dpurdie 879
                deleteDirectory(dpkgArchiveEntryFile);
880
            }
881
        }
882
    }
883
 
884
    /**   Sends email notification and mark the successful completion of a build
885
     *    Used simply to keep an email trail of build operations
886
     */
887
    public void emailPostBuild( RippleEngine rippleEngine, boolean isaError )
888
    {
889
        mLogger.debug("emailPostBuild");
890
        String subject;
891
        String emailTo;
892
        String mailBody = "";
893
 
894
        if (isaError)
895
        {
896
            subject = "BUILD FAILURE on package " + mReporting.packageName + " " + mReporting.packageVersion;
897
            emailTo = mReporting.packageOwners;
898
            mailBody="An error occured within the build system after the package had been built<p><hr>";
899
        }
900
        else
901
        {
902
            subject = "BUILD SUCCESS on package " + mReporting.packageName + " " + mReporting.packageVersion;
903
            emailTo = rippleEngine.getMailSender();
904
        }
905
 
906
        //  Cleanup the dependency string
907
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
908
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
909
        String depends = mReporting.packageDepends.replace("','", " ");
910
        depends = depends.replace("';'",indent);
911
        depends = depends.replace("'","");
912
 
913
        //  Cleanup the build standard string
914
        //      Expecting win32: jats all;linux_i386: jats prod
915
        String buildStandards = mReporting.packageBuildInfo;
916
        buildStandards = buildStandards.replace(";",indent);
917
 
918
        mailBody += "Release      : " + rippleEngine.mBaselineName + "<br>" +
919
                "Package      : " + mReporting.packageName + "<br>" +
920
                "Version      : " + mReporting.packageVersion + "<br>";
921
        if (isaError)
922
        {
923
            mailBody += "Cause        : " + mReporting.errMsg + "<br>";
924
            if (mReporting.errMsgDetail != null && mReporting.errMsgDetail.length() > 0)
925
            {
926
                mailBody += "Detail       : " + mReporting.errMsgDetail + "<br>";
927
            }
928
        }
929
 
930
        mailBody += "RM Link      : " + CreateUrls.generateRmUrl(mRtagId,mReporting.packageVersionId) + "<br>" +
931
                "PVID         : " + mReporting.packageVersionId + "<br>" +
932
                "VcsTag       : " + mReporting.newVcsTag + "<br>" +
933
                "Ripple       : " + (mReporting.isRipple ? "Yes" : "No") + "<br>" +
934
                "Dependencies : " + indent + depends + "<br>" +
935
                "Build Standards : " + indent + buildStandards;
936
 
937
        mailBody += "<p><hr>";
938
        try
939
        {
7155 dpurdie 940
            Smtpsend.send( rippleEngine.getMailServer(),    // mailServer
6914 dpurdie 941
                    rippleEngine.getMailSender(),           // source
7155 dpurdie 942
                    emailTo,                                // target - send to package owners, or myself
6914 dpurdie 943
                    rippleEngine.getMailSender(),           // cc
7155 dpurdie 944
                    null,                                   // bcc
945
                    subject,                                // subject
946
                    mailBody,                               // body
947
                    null                                    // attachment
6914 dpurdie 948
                    );
949
        }
950
        catch( Exception e )
951
        {
952
            mLogger.warn("Email Failure: emailPostBuild:" + e.getMessage());
953
        }
954
        mLogger.debug("emailPostBuild. Returning");
955
    }
7155 dpurdie 956
 
957
    /**
958
     * End of Processing for a Test Build
959
     *     - sends email notification
960
     *     - marks the instruction complete in the database
961
     */
962
    public void completeTestBuild(RippleEngine rippleEngine, boolean success) throws SQLException, Exception
963
    {
964
        mLogger.debug("completeTestBuild");
6914 dpurdie 965
 
7155 dpurdie 966
        if (!mReporting.isaTestBuild)
967
        {
968
            mLogger.info("completeTestBuild. Not Build Instruction");
969
            return;
970
        }
971
 
972
        //  Email Subject
973
        String subject = (success ? "TEST BUILD COMPLETED SUCCESSFULLY" : "TEST BUILD FAILED") 
974
                + " on package "
975
                + mReporting.packageName +  mReporting.packageExtension;
976
 
977
        //  Cleanup the dependency string
978
        //      Expecting: 'junit','3.7.0.cots';'ant-ejbdoclet','1.0000.cr'
979
        String indent = "<br>&nbsp;&nbsp;&nbsp;&nbsp;";
980
        String depends = mReporting.packageDepends.replace("','", " ");
981
        depends = depends.replace("';'",indent);
982
        depends = depends.replace("'","");
983
 
984
        //  Cleanup the build standard string
985
        //      Expecting win32: jats all;linux_i386: jats prod
986
        String buildStandards = mReporting.packageBuildInfo;
987
        buildStandards = buildStandards.replace(";",indent);
988
 
989
        // Email Body
990
        String mailBody = "";
991
        if ( !success )
992
        {
993
            mailBody += "Test build issues are identified in preceding build failure email.<p>"; 
994
        }
995
        mailBody += "Release: " + rippleEngine.mBaselineName + "<br>" 
996
                  + "Package: " + mReporting.packageName +  mReporting.packageExtension + "<br>" 
997
                  + "Rm Ref: " + CreateUrls.generateRmUrl(mReporting.rtagId, mReporting.packageVersionId) + "<br>" 
998
                  + "VcsTag: " + mReporting.vcsTag + "<br>"
999
                  + "Dependencies : " + indent + depends + "<br>"
1000
                  + "Build Standards : " + indent + buildStandards;
1001
 
1002
        mailBody += "<p><hr>";
1003
        try
1004
        {
7176 dpurdie 1005
            mLogger.info("completeTestBuildEmail Server: {}", rippleEngine.getMailServer());
1006
            mLogger.info("completeTestBuildEmail Sender: {}", rippleEngine.getMailSender());
1007
            mLogger.info("completeTestBuildEmail Target: {}", mReporting.packageOwners);
7155 dpurdie 1008
 
1009
            Smtpsend.send(rippleEngine.getMailServer(),     // mailServer
1010
                    rippleEngine.getMailSender(),           // source
1011
                    mReporting.packageOwners,               // target
1012
                    rippleEngine.getMailSender(),           // cc
1013
                    null,                                   // bcc
1014
                    subject,                                // subject
1015
                    mailBody,                               // body
1016
                    null                                    // attachment
1017
            );
1018
        } catch (Exception e)
1019
        {
1020
            mLogger.warn("Email Failure: completeTestBuild:{}", e.getMessage());
1021
        }
1022
 
1023
        // Update the Release Manager Database
1024
        mReleaseManager.markDaemonInstCompleted(mReporting.testBuildId);
7176 dpurdie 1025
        mLogger.warn("completeTest. Returning");
7155 dpurdie 1026
    }
1027
 
1028
 
6914 dpurdie 1029
    /**returns 'M'
1030
     */
1031
    protected char getMode()
1032
    {
1033
        mLogger.debug("getMode");
1034
        return 'M';
1035
    }
1036
 
1037
 
1038
}