Jenkins 僵尸任务&排队任务清理

通过API清理排队的任务

删除已经开始构建的任务(已有build_number)

1
curl -X POST <jenkins-server>/job/<job-name>/<build-number>/doDelete

对于排队中的任务

注意下面的id 不是build_number

1
curl -X POST 'http://jenkins/queue/cancelItem?id=85'

To find x, you can parse the result of:

1
http://jenkins/queue/api/json?tree=items[id,task[name]]

To cancel a build that is in progress:

1
http://jenkins/job/<jobName>/y/stop

To find y, you can parse the result of:

1
http://jenkins/job/<jobName>/lastBuild/api/json?tree=building,number

脚本处理排队中的任务

获取jenkins所有排队中任务,然后通过jobname过滤,然后想精确到某个任务可以在任务里通过判断任务的参数来确定:比如唯一的ID。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fun JenkinsServer.cancelTaskInQueue(jobName: String, p1: String, p2: String, p3: String){
runScript(runScriptHtml(jobName, URLEncoder.encode("import hudson.model.*\n" +
" \n" +
"def q = Jenkins.instance.queue\n" +
"q.items.findAll { \n" +
" \n" +
" it.task.name.startsWith(\"${jobName}\")\n" +
" \n" +
"}.each { \n" +
" p1=\"\"\n" +
" p2=\"\"\n" +
" p3=\"\"\n" +
" it.params.eachLine{\n" +
" aa = it.split(\"=\")\n" +
" \n" +
" if(aa[0].equals(\"p1\")){\n" +
" if(aa.length == 2){\n" +
" \tp1 = aa[1]\n" +
" }\n" +
" }\n" +
" if(aa[0].equals(\"p2\")){\n" +
" if(aa.length == 2){\n" +
" \tp2 = aa[1]\n" +
" }\n" +
" }\n" +
" if(aa[0].equals(\"p3\")){\n" +
" if(aa.length == 2){\n" +
" \tp3 = aa[1]\n" +
" }\n" +
" }\n" +
" }\n" +
" if(\"${p1}\".equals(p1) && \"${p2}\".equals(p2) && \"${p3}\".equals(p3)){\n" +
" println(\"cancel auto build ${p1}:${p2} is ${p3}\")\n" +
" q.cancel(it);\n" +
" }\n" +
"}\n" +
"\n", "UTF-8")))
}

清除段时间内大量堆积的任务

进入 Manage Jenkins -> Script Console , 然后执行后面的脚本

单条结束任务

查看进程的名字

1
2
3
Thread.getAllStackTraces().keySet().each() {
t -> println("name:"+t.getName())
}

进程名字结果示例:

1
2
3
4
5
6
7
name:Thread-90
name:Scheduler-174573182-1
name:Thread-116
name:Thread-110
name:Thread-83
name:org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution [#52]
name:SCMTrigger [#10]

停止特定进程

1
2
3
Thread.getAllStackTraces().keySet().each() {
t -> if (t.getName()=="刚才查出来的某条进程名字" ) { t.interrupt(); }
}

删掉所有进程

1
2
3
Thread.getAllStackTraces().keySet().each() {
t -> t.interrupt();
}

清掉所有Build Queue

1
Jenkins.instance.queue.clear()