Subversion Repositories DevTools

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
814 mhunt 1
package com.erggroup.buildtool.daemon;
2
 
3
import com.erggroup.buildtool.daemon.ResumeTimerTask;
4
import com.erggroup.buildtool.ripple.Package;
5
import com.erggroup.buildtool.ripple.ReleaseManager;
6
 
7
import java.io.BufferedReader;
8
import java.io.File;
9
import java.io.FileNotFoundException;
10
import java.io.FileOutputStream;
11
import java.io.FileWriter;
12
import java.io.FilenameFilter;
13
 
14
import java.io.IOException;
15
import java.io.PrintStream;
16
import java.io.StringReader;
17
 
18
import java.sql.SQLException;
19
 
20
import java.util.Date;
21
import java.util.Timer;
22
 
23
import org.apache.log4j.Logger;
24
import org.apache.tools.ant.BuildException;
25
import org.apache.tools.ant.DefaultLogger;
26
import org.apache.tools.ant.Project;
27
import org.apache.tools.ant.ProjectHelper;
28
 
29
/**Build Thread sub component
30
 */
31
public abstract class BuildThread
32
  extends Thread
33
{
34
  /**baseline identifier (which release manager release this BuildThread is dealing with)
35
   * @attribute
36
   */
37
  protected int mRtagId = 0;
38
 
39
  /**unique identifier of this BuildThread
40
   * @attribute
41
   */
42
  protected int mRconId = 0;
43
 
44
  /**
45
   * @aggregation composite
46
   */
47
  protected RunLevel mRunLevel;
48
 
49
  /**
50
   * @aggregation composite
51
   */
52
  protected ReleaseManager mReleaseManager;
53
 
54
  /**configured GBEBUILDFILTER for this BuildThread
55
   * @attribute
56
   */
57
  protected String mGbebuildfilter = "";
58
 
59
  /**
60
   * @aggregation composite
61
   */
62
  protected static ResumeTimerTask mResumeTimerTask;
63
 
64
  /**
65
   * @aggregation composite
66
   */
67
  private static Timer mTimer;
68
 
69
  /**Synchroniser object
70
   * Use to Synchronize on by multiple threads
71
   * @attribute
72
   */
73
  static final Object mSynchroniser = new Object();
74
 
75
  /**BuildThread group
76
   * @attribute
77
   */
78
  public static final ThreadGroup mThreadGroup = new ThreadGroup("BuildThread");
79
 
80
  /**the advertised build file content when either
81
   * a) no package in the baseline has a build requirement
82
   * b) the next package in the baseline with a build requirement is generic
83
   * @attribute
84
   */
85
  protected static final String mDummyBuildFileContent = new String("<dummy/>");
86
 
87
  /**Set true when last build cycle was benign.
88
   * @attribute
89
   */
90
  protected boolean mSleep;
91
 
92
  /**Logger
93
   * @attribute
94
   */
95
  private static final Logger mLogger = Logger.getLogger(BuildThread.class);
96
 
97
  /**constructor
98
   */
99
  BuildThread()
100
  {
101
    super(mThreadGroup, "");
102
    mLogger.debug("BuildThread");
103
    mSleep = false;
104
    mReleaseManager = new ReleaseManager();
105
 
106
    // no need to be synchronized - BuildThreads are instantiated in a single thread
107
    if ( mResumeTimerTask == null )
108
    {
109
      mResumeTimerTask = new ResumeTimerTask();
110
      mTimer = new Timer();
111
      mResumeTimerTask.setTimer(mTimer);
112
    }
113
  }
114
 
115
  /**initially changes the run level to IDLE
116
   * determines if the BuildThread is still configured
117
   * a) determines if the BuildThread is running in scheduled downtime
118
   * b) determines if the BuildThread is directed to pause
119
   * changes the run level to PAUSED if a) or b) are true
120
   * throws ExitException when not configured
121
   * otherwise changes the run level to WAITING and returns when allowed to proceed
122
   * implements the sequence diagrams allowed to proceed, not allowed to proceed, exit
123
   */
124
  protected void allowedToProceed() throws ExitException, SQLException, Exception
125
  {
126
    mLogger.debug("allowedToProceed");
127
 
128
    if (mSleep)
129
    {
130
      try
131
      {
818 mhunt 132
        mRunLevel = RunLevel.IDLE;
133
        mLogger.warn("allowedToProceed changing run level to IDLE for rcon_id " + mRconId);
134
        mRunLevel.persist(mReleaseManager, mRconId);
135
        mReleaseManager.clearCurrentPackageBeingBuilt(mRconId);
136
 
814 mhunt 137
        mLogger.warn("allowedToProceed sleep 5 mins no build requirement");
138
        Thread.sleep(300000);
139
        mLogger.info("allowedToProceed sleep returned");
140
      }
818 mhunt 141
      catch(SQLException e)
142
      {
143
        mLogger.warn("allowedToProceed caught SQLException");
144
      }
814 mhunt 145
      catch(InterruptedException e)
146
      {
147
        mLogger.warn("allowedToProceed sleep caught InterruptedException");
148
      }
149
    }
150
 
151
    // IMPORTANT - this is done AFTER a Thread.sleep by design
152
    // In the case of an SQLException (signifying a database access issue)
153
    // avoid accessing the database immediately
154
    mRunLevel = RunLevel.IDLE;
816 mhunt 155
    mLogger.warn("allowedToProceed changing run level to IDLE for rcon_id " + mRconId);
814 mhunt 156
    mRunLevel.persist(mReleaseManager, mRconId);
157
    boolean proceed = false;
158
 
159
    while ( !proceed )
160
    {
161
      mReleaseManager.connect();
162
      if ( !mReleaseManager.queryReleaseConfig(mRtagId, mRconId, BuildDaemon.mHostname, getMode(), mGbebuildfilter) )
163
      {
164
        mReleaseManager.disconnect();
165
        mLogger.fatal("allowedToProceed queryReleaseConfig failed");
166
        throw new ExitException();
167
      }
168
 
169
      Date resumeTime = new Date( 0 );
170
      if ( !mReleaseManager.queryRunLevelSchedule(resumeTime) )
171
      {
172
        mLogger.info("allowedToProceed scheduled downtime");
173
        mReleaseManager.disconnect();
174
        mRunLevel = RunLevel.PAUSED;
816 mhunt 175
        mLogger.warn("allowedToProceed changing run level to PAUSED for rcon_id " + mRconId);
814 mhunt 176
        mRunLevel.persist(mReleaseManager, mRconId);
177
 
178
        synchronized(mSynchroniser)
179
        {
180
          // contain the schedule and wait in the same synchronized block to prevent a deadlock
181
          // eg this thread calls schedule, timer thread calls notifyall, this thread calls wait (forever)
182
          try
183
          {
184
            if (mResumeTimerTask.isCancelled())
185
            {
186
              mResumeTimerTask = new ResumeTimerTask();
187
              mTimer = new Timer();
188
              mResumeTimerTask.setTimer(mTimer);
189
            }
190
            mLogger.warn("allowedToProceed schedule passed " + resumeTime.getTime());
191
            mTimer.schedule(mResumeTimerTask, resumeTime);
192
          }
193
          catch( IllegalStateException e )
194
          {
195
            // this may be thrown by schedule if already scheduled
196
            // it signifies another BuildThread has already scheduled the ResumeTimerTask
197
             mLogger.warn("allowedToProceed already scheduled");
198
          }
199
 
200
          try
201
          {
202
            mLogger.warn("allowedToProceed wait");
203
            mSynchroniser.wait();
204
            mLogger.warn("allowedToProceed wait returned");
205
 
206
            if ( mGbebuildfilter.compareTo("unit test not allowed to proceed") == 0 )
207
            {
208
              throw new ExitException();
209
            }
210
          }
211
          catch( InterruptedException e )
212
          {
213
            mLogger.warn("allowedToProceed caught InterruptedException");
214
          }
215
        }
216
 
217
      }
218
      else
219
      {
220
        if ( !mReleaseManager.queryDirectedRunLevel(mRconId) )
221
        {
222
          mLogger.info("allowedToProceed downtime");
223
          mReleaseManager.disconnect();
224
          try
225
          {
226
            // to do, sleep for periodicMs
227
            mLogger.warn("allowedToProceed sleep 5 mins directed downtime");
228
            Thread.sleep(300000);
229
            mLogger.info("allowedToProceed sleep returned");
230
          }
231
          catch (InterruptedException e)
232
          {
233
            mLogger.warn("allowedToProceed caught InterruptedException");
234
          }
235
        }
236
        else
237
        {
238
          mReleaseManager.disconnect();
239
          proceed = true;
240
        }
241
      }
242
    }
243
 
244
    mRunLevel = RunLevel.WAITING;
816 mhunt 245
    mLogger.warn("allowedToProceed changing run level to WAITING for rcon_id " + mRconId);
814 mhunt 246
    mRunLevel.persist(mReleaseManager, mRconId);
247
 
248
  }
249
 
250
  /**periodically 
251
   * a) performs disk housekeeping
252
   * b) determines if a minimum threshold of disk space is available
253
   * changes the run level to CANNOT_CONTINUE if insufficient disk space
254
   * otherwise changes the run level to ACTIVE and returns
255
   * implements the sequence diagram check environment
256
   */
257
  protected void checkEnvironment() throws Exception
258
  {
259
    mLogger.debug("checkEnvironment");
260
    boolean exit = false;
261
 
262
    while( !exit )
263
    {
264
      housekeep();
265
 
266
      // attempt to exit
267
      exit = true;
268
 
269
      if ( !hasSufficientDiskSpace() )
270
      {
271
        mLogger.warn("checkEnvironment below disk free threshold");
272
        exit = false;
273
        mRunLevel = RunLevel.CANNOT_CONTINUE;
816 mhunt 274
        mLogger.warn("checkEnvironment changing run level to CANNOT_CONTINUE for rcon_id " + mRconId);
814 mhunt 275
        mRunLevel.persist(mReleaseManager, mRconId);
276
        try
277
        {
278
          // to do, sleep for periodicMs
279
          if ( mGbebuildfilter.compareTo("unit test check environment") != 0 )
280
          {
281
            mLogger.warn("checkEnvironment sleep 5 mins below disk free threshold");
282
            Thread.sleep(300000);
283
            mLogger.info("checkEnvironment sleep returned");
284
          }
285
        }
286
        catch (InterruptedException e)
287
        {
288
          mLogger.warn("checkEnvironment caught InterruptedException");
289
        }
290
      }
291
    }
292
 
293
    mRunLevel = RunLevel.ACTIVE;    
816 mhunt 294
    mLogger.warn("checkEnvironment changing run level to ACTIVE for rcon_id " + mRconId);
814 mhunt 295
    mRunLevel.persist(mReleaseManager, mRconId);
296
  }
297
 
298
  /**performs disk housekeeping which involves deleting build directories > 5 days old
299
   * refer to the sequence diagram check environment
300
   */
301
  private void housekeep()
302
  {
303
    mLogger.debug("housekeep");
304
    FilenameFilter filter = new FilenameFilter()
305
    {
306
      public boolean accept(File file, String name)
307
      {
308
        mLogger.debug("accept " + name);
309
        boolean retVal = false;
310
 
311
        if ( file.isDirectory() && !name.startsWith( "." ) )
312
        {
313
          retVal = true;
314
        }
315
 
316
        mLogger.info("accept returned " + retVal);
317
        return retVal;
318
      }
319
    };
320
 
321
    try
322
    {
323
      File cwd = new File( "." );
324
 
325
      File[] children = cwd.listFiles( filter );
326
 
327
      if ( children != null )
328
      {
329
        for ( int child=0; child < children.length; child++ )
330
        {
331
          // child is named uniquely after an rtag_id
332
          File[] grandchildren = children[ child ].listFiles( filter );
333
 
334
          if ( grandchildren != null )
335
          {
336
            for ( int grandchild=0; grandchild < grandchildren.length; grandchild++ )
337
            {
338
              // child is named uniquely to encapsulate a build
339
              // 5 days = 432,000,000 milliseconds
340
              if ( ( System.currentTimeMillis() - grandchildren[ grandchild ].lastModified() ) > 432000000 )
341
              {
342
                // the directory is over 5 days old
343
                mLogger.warn("housekeep deleting directory " + grandchildren[ grandchild ].getName());
344
                if ( mGbebuildfilter.compareTo("unit test check environment") != 0 )
345
                {
346
                  deleteDirectory( grandchildren[ grandchild ] );
347
                }
348
              }
349
            }
350
          }
351
        }
352
      }
353
    }
354
    catch( SecurityException e )
355
    {
356
      // this can be thrown by lastModified
357
       mLogger.warn("housekeep caught SecurityException");
358
    }
359
 
360
  }
361
 
362
  /**returns true if free disk space > 10G
363
   * this may become configurable if the need arises
364
   * refer to the sequence diagram check environment
365
   */
366
  private boolean hasSufficientDiskSpace()
367
  {
368
    mLogger.debug("hasSufficientDiskSpace");
369
    boolean retVal = true;
370
    long freeSpace = 0;
371
 
372
    try
373
    {
374
      File cwd = new File( "." );
375
 
376
      // 5G = 5368709120 bytes
377
      if ( mGbebuildfilter.compareTo("unit test check environment") == 0 )
378
      {
379
        if ( mReleaseManager.mPersistedRunLevelCollection.size() == 0 )
380
        {
381
          retVal = false;
382
        }
383
        else
384
        {
385
          retVal = true;
386
        }
387
      }
388
      else
389
      {
816 mhunt 390
        freeSpace = cwd.getUsableSpace();
814 mhunt 391
 
392
        if ( freeSpace < 5368709120L )
393
        {
816 mhunt 394
          mLogger.warn("hasSufficientDiskSpace on " + cwd.getAbsolutePath() + " freeSpace " + freeSpace);
814 mhunt 395
          retVal = false;
396
        }
397
      }
398
    }
399
    catch( SecurityException e )
400
    {
401
      // this can be thrown by getFreeSpace
402
       mLogger.warn("hasSufficientDiskSpace caught SecurityException");
403
    }
404
 
405
    mLogger.info("hasSufficientDiskSpace returned " + retVal + " " + freeSpace);
406
    return retVal;
407
  }
408
 
409
  /**abstract method
410
   */
411
  public abstract void run();
412
 
413
  /**deletes directory and all its files
414
   */
415
  protected void deleteDirectory(File directory)
416
  {
417
    mLogger.debug("deleteDirectory " + directory.getName());
418
    try
419
    {
420
      if ( directory.exists() )
421
      {
422
        FilenameFilter filter = new FilenameFilter()
423
        {
424
          public boolean accept(File file, String name)
425
          {
426
            mLogger.debug("accept " + name);
427
            boolean retVal = false;
428
 
429
            if ( !name.startsWith( "." ) )
430
            {
431
              retVal = true;
432
            }
433
 
434
            mLogger.info("accept returned " + retVal);
435
            return retVal;
436
          }
437
        };
438
 
439
        File[] children = directory.listFiles( filter );
440
 
441
        if ( children != null )
442
        {
443
          for ( int child=0; child < children.length; child++ )
444
          {
445
            if ( children[ child ].isDirectory() )
446
            {
447
              deleteDirectory( children[ child ] );
448
            }
449
            else
450
            {
451
              children[ child ].delete();
452
            }
453
          }
454
        }
455
        directory.delete();
456
      }
457
    }
458
    catch( SecurityException e )
459
    {
460
      // this can be thrown by exists and delete
461
       mLogger.warn("deleteDirectory caught SecurityException");
462
    }
463
  }
464
 
465
  /**abstract method
466
   */
467
  protected abstract char getMode();
468
 
469
  /**injects GBE_BUILDFILTER into the passed buildFileContent
470
   * builds a buildFile from the buildFileContent
471
   * triggers ant to operate on the buildFile
472
   */
473
  protected void deliverChange(String buildFileContent, String target, boolean master)
474
  {
475
    mLogger.debug("deliverChange");
476
    File buildFile = new File(mRtagId + "build.xml");
477
 
478
    try
479
    {
480
      // clear the file contents
481
      if ( buildFileContent != null && target != null && target.compareTo("AbtSetUp") == 0 )
482
      {
483
        FileOutputStream buildFileOutputStream = new FileOutputStream(buildFile, false);
484
        buildFileOutputStream.close();
485
 
486
        StringReader buildFileContentStringReader = new StringReader(buildFileContent);
487
        BufferedReader buildFileBufferedReader = new BufferedReader(buildFileContentStringReader);
488
 
489
        // sanitise the buildFileContent
490
        // it may contain line.separators of "\n", "\r", or "\r\n" variety, depending on the location of the ripple engine
491
        String sanitisedBFC = new String();
492
        String lf = new String( System.getProperty("line.separator") );
493
        int lineCount = 0;
494
        String line = new String();
495
 
496
        while( ( line = buildFileBufferedReader.readLine() ) != null)
497
        {
498
          sanitisedBFC += line + lf;
499
          lineCount++;
500
 
501
          if ( lineCount == 2 )
502
          {
503
            // have read the first two lines
504
            String inject = "<property name=\"MASTER\" value=\"";
505
 
506
            if ( master )
507
            {
508
              inject += "yes\"/>" + lf;
509
            }
510
            else
511
            {
512
              inject += "no\"/>" + lf;
513
            }
514
 
515
            // insert a GBE_BUILDFILTER property if necessary
516
            if ( mGbebuildfilter.length() > 0 )
517
            {
518
              inject += "<property name=\"GBE_BUILDFILTER\" value=\"" + mGbebuildfilter + "\"/>" + lf;
519
            }
520
 
521
            mLogger.info("deliverChange injecting " + inject);
522
            sanitisedBFC += inject;
523
          }
524
        }
525
        buildFileBufferedReader.close();
526
        FileWriter buildFileWriter = new FileWriter(buildFile);
527
        buildFileWriter.write(sanitisedBFC);
528
        buildFileWriter.close();
529
      }
530
 
531
      Project p = new Project();
532
      p.setProperty("ant.file", buildFile.getAbsolutePath());
533
      DefaultLogger dl = new DefaultLogger();
534
      PrintStream ps = new PrintStream(mRtagId + ".log");
535
      dl.setOutputPrintStream(ps);
536
      dl.setMessageOutputLevel(Project.MSG_INFO);
537
      p.addBuildListener(dl);
538
      p.init();
539
      ProjectHelper pH = ProjectHelper.getProjectHelper();
540
      p.addReference("ant.projectHelper", pH);
541
      pH.parse(p, buildFile);
542
      mLogger.warn("deliverChange ant launched on " + buildFile.getAbsolutePath());
543
 
544
      if ( target == null )
545
      {
546
        target = p.getDefaultTarget();
547
      }
548
      mLogger.warn("deliverChange ant launched against target " + target);
549
      p.executeTarget(target);
550
      mLogger.warn("deliverChange ant returned");
551
    }
552
    catch( BuildException e )
553
    {
554
      mLogger.debug("deliverChange caught BuildException, big deal, the build failed " + e.getMessage());
555
    }
556
    catch( FileNotFoundException e )
557
    {
558
      mLogger.error("deliverChange caught FileNotFoundException");
559
    }
560
    catch( IOException e )
561
    {
562
      mLogger.error("deliverChange caught IOException");
563
    }
564
 
565
  }
566
 
567
  /**sets up a ClearCase static view
568
   */
569
  protected void setViewUp(String content, boolean master)
570
  {
571
    mLogger.debug("setViewUp");
572
    // run ant on the AbtSetUp target
573
    deliverChange(content, "AbtSetUp", master);
574
  }
575
 
576
  /**tears down a ClearCase static view
577
  */
578
  protected void tearViewDown()
579
  {
580
    mLogger.debug("tearViewDown");
581
    // to do run ant on the AbtTearDown target
582
    deliverChange(null, "AbtTearDown", false);
583
  }
584
 
585
  /**Checks the archive for the <packageName>/<packageVersion>/built.<machtype> existence
586
   */
587
  protected boolean published(String archive, String packageName, 
588
                            String packageVersion, String machtype,
589
                            String generic)
590
  {
591
    mLogger.debug("published");
592
    boolean retVal = false;
593
 
594
    String fs = System.getProperty( "file.separator" );
595
    String destination = archive + fs + packageName + fs + packageVersion;
596
 
597
    mLogger.debug("published " + destination);
598
    String filename = "built.";
599
 
600
    if ( generic.compareTo("generic") == 0 )
601
    {
602
      filename += "generic";
603
    }
604
    else
605
    {
606
      filename += machtype;
607
    }
608
 
609
    mLogger.debug("published " + filename);
610
    File flag = new File( destination, filename );
611
 
612
    if ( flag.exists() )
613
    {
614
      retVal = true;
615
    }
616
    mLogger.debug("published returned " + retVal);
617
    return retVal;
618
  }
619
}