Groovy script to cancle jobs from queue

565 views
Skip to first unread message

Paweł Wiśniewski

unread,
May 23, 2016, 7:27:25 AM5/23/16
to Jenkins Users
Hi,

I'm currently working on script which will cancel jobs from queue that have value of one parameter set to specific value.

Current code is this:
#!/usr/bin/groovy
import jenkins.model.*
import hudson.model.*

def config = new HashMap()
def bindings = getBinding()
config
.putAll(bindings.getVariables())

out = config['out']
def queue = Jenkins.instance.queue
def track_param = build.buildVariables.get('track_param')
def track_reg = /(?ms).*track_param=${track_param}.*?/
def track_reg_running = /.*track_param='${track_param}'$/
def job_regex = /^FTWCOMMON_(?!Selective).*/

while (!(queue.items.findAll { it.task.name ==~ job_regex && it.params ==~ track_reg}.empty)) {
// For some reason it cancells wrong task if more than one are cached by condition
    item
= queue.items.findAll { it.task.name ==~ job_regex && it.params ==~ track_reg}[0]
   
print item
   
out.println "##################"
   
out.println "Working on task"
   
out.println "Task name:"
   
out.println item.task.name
   
out.println "Task params"
   
out.println item.params
   
out.println "Cancelling task"
    queue
.cancel(item.task)
   
out.println "Task cancelled"
   
out.println "##################"
}
   

The problem I'm facing is like this:
I start my test job that needs to be canceled 5 times, I have throtling set so only 1 will be building and the other 4 are in queue. The track params are:
queue:
job#5 track_param=3
job#4 track_param=1
job#3 track_param=2
job#2 track_param=1

building:
job#1 track_param=1

And when I try to delete jobs with track_param=1 it deletes them all.

I've added printing content of items and from what I see there the problem looks like it:
Items are colection o 2 items. Job#4 is assinged to item, but it cancels job#5, then it cancels #4, then I items have only one element, but same thing happens again, it cancels job #3 instead of #2.


Any idea why this happens and how to fix it? Perhaps different approach should be applied to this problem?

Br,
Pawel

George Abraham

unread,
Apr 27, 2020, 6:00:33 PM4/27/20
to Jenkins Users
Were you able to find a solution for this.
I encountered something similar where 
I have many jobs in queue with different parameter values and I wanted to cancel the job where the job name and parameter value matches.

def q = Jenkins.instance.queue

q.items.each {
  if((it.task.name == job_name_to_delete) && (it.params == paramDelete)){
       logger(it.task.name)
       logger(it.params)
       q.cancel(it.task)
  }


Noticed that the condition is getting satisfied but the job cancelled in the first job in the queue, not the job where the params match.

Any ideas what went wrong. Any help would be appreciated.

Thanks,
George
Reply all
Reply to author
Forward
0 new messages