On my Jenkins machine I'm able to reset the excutor node when it hits the suspend state with the following Groovy command:
import jenkins.model.Jenkins
Jenkins.instance.getNode('nodeName').toComputer().setAcceptingTasks(true)
I was wondering if there is a similar way in Groovy to bring a node back online when it hits a offline state. Maybe the "hudson.model.Husdon.instance" has an option to set: computer.connect(true) to trigger a restart of the node.
Something in the likes of:
Jenkins.instance.getNode('').toComputer().setComputerConnect(true)
This is the Groovy script that I have set up op to this point:
import java.util.regex.Matcher
import java.util.regex.Pattern
int exitcode = 0
println("Looking for Offline Slaves:");
for (slave in hudson.model.Hudson.instance.slaves) {
if (slave.getComputer().isOffline().toString() == "true"){
println(' * Slave ' + slave.name + " is offline!");
if (slave.name == “<nodeName>”) {
println('This is <nodeName>.');
exitcode++;
} // if slave.name
} // if slave offline
} // for slave in slaves
println "<nodeName> is offline: " + hudson.model.Hudson.instance.getNode("<nodeName>").getComputer().isOffline().toString()
With this I'm able to report that the node is offline.
I would like to find the Jenkin jobs in the master and client running more than 5 hours and kill it.
I tried multiple options using Thread.getAllStackTraces() and list all the jobs it was not helpful. Your help is much appreciated.
Use timeout
pipeline {
options {
timeout(time: 5, unit: 'HOURS')
}
stages {
steps {
sh '...'
}
}
}
Get all Jenkins jobs and their builds. Go through the list and check if there are builds running. If you find a build that is running, you can retrieve its time/timestamp/duration. Based on that time you could determine does that build is already running longer than X hours.
jenkins.model.Jenkins.instance.getAllItems(AbstractItem.class). each {
println "Job: " + it.fullName + " - " + it.class + " is running: " + it.isBuilding()
if(it.isBuilding()) {
def builds = it.getBuilds().each {
if(it.isBuilding()) {
println it.getTime() //getTimestamp(), getTimeInMillis(), getDuration() ...
}
}
}
}
WorkflowJob Docu
WorkflowRun Docu
Jenkins Core API
due to config errors or other problems sometimes I just want to abort ALL jobs of a single multibranch pipeline.
How can I do this from the script console?
I can call doKill() on a job object but how do I iterate over a list of all jobs of a multibranch pipeline and kill all of them?
Here is the script I use to abort all running builds. You could adapt it to check the name of the build before canceling it with some condition like job.name ==~ /myjob/
import jenkins.model.*
// remove jobs in queu
def queue = Jenkins.instance.queue
println "Queue contains ${queue.items.length} items"
queue.clear()
println 'Queue cleared.'
// Cancel running builds
def numCancels = 0
for (job in Jenkins.instance.items) {
if (job.hasProperty('builds')) {
for (build in job.builds) {
if (build.isBuilding()) {
println "Stopping ${build.toString()}"
build.doStop();
println "${build.toString()} stopped."
numCancels++
}
}
}
}
println "${numCancels} Jobs canceled."
Is there any workaround that I can retrieve the Build Environment settings for every job in a groovy script ?
For example I installed the 'Scriptler plugin' and the 'EnvInject plugin' and I want to find out for every job that I have if "manage exclusion" is ticked or not :
what I did is:
println String.format( "<b>List of JOBS :</b>" )`
println ''
for(item in jenkins.model.Jenkins.instance.getAllItems(hudson.model.Job.class))
{
if(item instanceof hudson.model.ExternalJob)
continue
println''
for (env in item.builders)
println env
}
I just found out how to do it...
println ''
println String.format( "<b> List all JOBS having exclusions defined :</b>" )
println ''
for(item in jenkins.model.Jenkins.instance.getAllItems(hudson.model.Job.class))
{
if(item instanceof hudson.model.ExternalJob)
continue
for(wrapper in item.getBuildWrappersList())
if (wrapper instanceof org.jvnet.hudson.plugins.exclusion.IdAllocator)
println item.name
}
To sum up......the changes that I did,I called the getBuildWrappersList to retrieve the Build Environment parameters.For my case,I was trying to find out which jobs were using the ArchiveArtifact plugin and display them for the user...
Build Environment capture
Cheers :)
I delete old jenkins builds with rm where job is hosted:
my_job/builds/$ rm -rf [1-9]*
These old builds are still visible in job page.
How to remove them with command line?
(without the delete button in each build user interface)
Here is another option: delete the builds remotely with cURL. (Replace the beginning of the URLs with whatever you use to access Jenkins with your browser.)
$ curl -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll
The above deletes build #1 to #56 for job myJob.
If authentication is enabled on the Jenkins instance, a user name and API token must be provided like this:
$ curl -u userName:apiToken -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll
The API token must be fetched from the /me/configure page in Jenkins. Just click on the "Show API Token..." button to display both the user name and the API token.
Edit: As pointed out by yegeniy in a comment below, one might have to replace doDeleteAll by doDelete in the URLs above to make this work, depending on the configuration.
It looks like this has been added to the CLI, or is at least being worked on: http://jenkins.361315.n4.nabble.com/How-to-purge-old-builds-td385290.html
Syntax would be something like this: java -jar jenkins-cli.jar -s http://my.jenkins.host delete-builds myproject '1-7499' --username $user --password $password
Check your home jenkins directory:
"Manage Jenkins" ==> "Configure System"
Check field "Home directory" (usually it is /var/lib/jenkins)
Command for delete all jenkins job builds
/jenkins_home/jobs> rm -rf */builds/*
After delete should reload config:
"Manage Jenkins" ==> "Reload Configuration from Disk"
You can do it by Groovy Scripts using Hudson API.. Access your jenkins instalation
http://localhost:38080/script.
For Example, for deleting all old builds of all projects using the follow script:
Note: Take care if you use Finger Prints , you will lose all history.
import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
// check that job is not building
if(!item.isBuilding()) {
System.out.println("Deleting all builds of job "+item.name)
for(build in item.getBuilds()){
build.delete()
}
}
else {
System.out.println("Skipping job "+item.name+", currently building")
}
}
Or for cleaning all workspaces :
import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
// check that job is not building
if(!item.isBuilding()) {
println("Wiping out workspace of job "+item.name)
item.doDoWipeOutWorkspace()
}
else {
println("Skipping job "+item.name+", currently building")
}
}
There are a lot of examples on the Jenkins wiki
Is there a reason you need to do this manually instead of letting Jenkins delete old builds for you?
You can change your job configuration to automatically delete old builds, based either on number of days or number of builds. No more worrying about it or having to keep track, Jenkins just does it for you.
The following script cleans old builds of jobs. You should reload config from disk if you delete build manually:
import hudson.model.*
for(item in Hudson.instance.items) {
if (!item.isBuilding()) {
println("Deleting old builds of job " + item.name)
for (build in item.getBuilds()) {
//delete all except the last
if (build.getNumber() < item.getLastBuild().getNumber()) {
println "delete " + build
try {
build.delete()
} catch (Exception e) {
println e
}
}
}
} else {
println("Skipping job " + item.name + ", currently building")
}
}
From Script Console Run this, but you need to change the job name:
def jobName = "name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()
From Jenkins Scriptler console run the following Groovy script to delete all the builds of jobs listed under a view:
import jenkins.model.Jenkins
hudson.model.Hudson.instance.getView('<ViewName>').items.each() {
println it.fullDisplayName
def jobname = it.fullDisplayName
def item = hudson.model.Hudson.instance.getItem(jobname)
def build = item.getLastBuild()
if (item.getLastBuild() != null) {
Jenkins.instance.getItemByFullName(jobname).builds.findAll {
it.number <= build.getNumber()
}.each {
it.delete()
}
}
}
def jobName = "MY_JOB_NAME"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().findAll { it.number < 10 }.each { it.delete() }
if you had 12 builds this would clear out builds 0-9 and you'd have 12,11,10 remaining. Just drop in the script console
This script will configure the build retention settings of all of the Jenkins jobs.
Change the values from 30 and 200 to suite you needs, run the script, then restart the Jenkins service.
#!/bin/bash
cd $HOME
for xml in $(find jobs -name config.xml)
do
sed -i 's#<daysToKeep>.*#<daysToKeep>30</daysToKeep>#' $xml
sed -i 's#<numToKeep>.*#<numToKeep>200</numToKeep>#' $xml
done
The script below works well with Folders and Multibranch Pipelines. It preserves only 10 last builds for each job. That could be adjusted or removed (proper if) if needed. Run that from web script console (example URL: https://jenkins.company.com/script)
def jobs = Hudson.instance.getAllItems(hudson.model.Job.class)
for (job in jobs){
println(job)
def recent = job.builds.limit(10)
for(build in job.builds){
if(!recent.contains(build)){
println("\t Deleting build: " + build)
build.delete()
}
}
}
From my opinion all those answers are not sufficient, you have to do:
echo "Cleaning:"
echo "${params.PL_JOB_NAME}"
echo "${params.PL_BUILD_NUMBER}"
build_number = params.PL_BUILD_NUMBER as Integer
sleep time: 5, unit: 'SECONDS'
wfjob = Jenkins.instance.getItemByFullName(params.PL_JOB_NAME)
wfjob.getBuilds().findAll { it.number >= build_number }.each { it.delete() }
wfjob.save()
wfjob.nextBuildNumber = build_number
wfjob.save()
wfjob.updateNextBuildNumber(build_number)
wfjob.save()
wfjob.doReload()
Or the job will not be correctly reset and you have to hit build until you reach next free number in the meanwhile the jenkins log will show:
java.lang.IllegalStateException: JENKINS-23152: ****/<BUILD_NUMBER> already existed;