Tuesday, August 18, 2015

Jenkins - groovy and programmatic job dependency

I really like Jenkins but it certainly isn't a full fledged general job scheduler.  One aspect of various commercial / general schedulers that I miss is the ability to chain jobs together based upon job status.  A scheduler like CA Autosys handles this pretty well.

I can't really justify the cost of a commercial scheduler and we use Jenkins so what can be done?

We'll I ran into a need and decided to find out.  I need to verify the status of an Apache ServiceMix system.  On occasion (still trying to determine root cause), the connectivity with an ERP drops and isn't reacquired.  When that happens, the only solution that worked so far was to restart the ServiceMix process.

What I did is define a Jenkins job which watches the queue of input data for failures.  When a failure occurs I wanted to restart ServiceMix. It took a bit of searching but I found a way to run a second job on identifying our failure condition.  This second job is responsible for performing the restart and the job is initiated programmatically from the first job.  Below is a chunk of code to get, execute and wait for a job to complete.  Not a lot of error handling here but it hopefully provides enough of an example to successfully copy and reuse. 


   def restartWsiServer()  
   {  
    def job = Hudson.instance.getJob('SM RESTART')  
    def anotherBuild  
    try{  
     def future = job.scheduleBuild2(0, new Cause.UpstreamCause(build))  
     out.println "Waiting for the completion of " + HyperlinkNote.encodeTo('/' + job.url, job.fullDisplayName)  
     anotherBuild = future.get()  
    } catch(CancellationException e)  
    {throw new AbortException("${job.fullDisplayName} aborted.")}  
    out.println HyperlinkNote.encodeTo('/' + anotherBuild.url, anotherBuild.fullDisplayName) + " completed."  
   }  


Hope someone finds this useful.

No comments:

Post a Comment