-1

Am looking for any Plugin from which I can pull the data which contains total number of jenkins jobs, total number of build failure happened periodically.

Edit 1: Getting below error referring this method List Jenkins job build detials for last one year along with the user who triggered the build

error:

Building on the built-in node in workspace /data-1/ondotapps/jenkins/workspace/Finding overall build details
Job Name: ( # builds: last 365 days / overall )  Last Status
   Number | Trigger | Status | Date | Duration

ERROR: Build step failed with exception
groovy.lang.MissingPropertyException: No such property: Jenkins for class: Script1
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:66)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:310)
    at Script1.run(Script1.groovy:7)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:574)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:612)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:583)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:440)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:377)
    at hudson.plugins.groovy.SystemGroovy.run(SystemGroovy.java:95)
    at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:59)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:816)
    at hudson.model.Build$BuildExecution.build(Build.java:199)
    at hudson.model.Build$BuildExecution.doRun(Build.java:164)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:524)
    at hudson.model.Run.execute(Run.java:1897)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:44)
    at hudson.model.ResourceController.execute(ResourceController.java:101)
    at hudson.model.Executor.run(Executor.java:442)
Build step 'Execute system Groovy script' marked build as failure
Started calculate disk usage of build
Finished Calculation of disk usage of build in 0 seconds
Started calculate disk usage of workspace
Finished Calculation of disk usage of workspace in 0 seconds
Finished: FAILURE

edit 2:

Am running the script as "Execute system Groovy Step" in build section of freestyle job.

Below image for your reference.

enter image description here

and at the same time I have tried running the same script at manage jenkins-> script console part as well.

Still getting below error.

error:

Job Name: ( # builds: last 365 days / overall )  Last Status
   Number | Trigger | Status | Date | Duration

groovy.lang.MissingPropertyException: No such property: instance for class: Script1
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:66)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:310)
    at Script1$_run_closure1.doCall(Script1.groovy:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:41)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)

Please let me know if am missing something here.

ramesh
  • 9
  • 4
  • 1
    [Solved previously](https://stackoverflow.com/a/64509896/598141) and more generally. Consider upvoting. – Ian W Aug 03 '22 at 06:33
  • Hi @IanW, Thanks for your response. I just need the numbers. If I pass the start and end time it should show the total number of jobs created, build succeeded, and failed in between that time span. – ramesh Aug 03 '22 at 07:14
  • getting aboe error – ramesh Aug 03 '22 at 08:03
  • I updated the script to find Job (Freestyle+Workflow), but your error is `"No such property: Jenkins"`, which means it can't find "Jenkins", which means you are not running from the script console ( `$JENKINS_URL/script` ) or from a System Groovy step, which is necessary to to access the Jenkins internals. It was in the first sentence of the prior answer. – Ian W Aug 03 '22 at 09:14
  • @IanW, edited the latest comments under Edit 2. – ramesh Aug 03 '22 at 09:56
  • "it instanceof Job", not "it instance of Job" – Ian W Aug 03 '22 at 10:13
  • it is listing every job name, but I need just the numbers, like total number of new jobs created= 200, number of builds failures = 23 and number of success builds=500 between the time spanc we are passing. – ramesh Aug 03 '22 at 10:27
  • This is not a coding service.. – Ian W Aug 03 '22 at 15:56

1 Answers1

0

I made a code to obtain a "Resume" of all Jobs with FAILURES, SUCCESSES AND UNSTABLES, each Job and Total of all Jobs. Also you can insert number of days, by default will get all Jobs in 1 day and check numbers of FAILURES, SUCCESSES AND UNSTABLES.

This is a pipeline.

properties([disableConcurrentBuilds(),buildDiscarder(logRotator(artifactDaysToKeepStr: '1', artifactNumToKeepStr: '', daysToKeepStr: '1', numToKeepStr: '')),pipelineTriggers([cron('H 1 * * *')]),parameters([string(defaultValue: 'NO', name: 'SHOW_LIST'),string(defaultValue: '1', name: 'DAYS'),string(defaultValue: '.*', name: 'FILTER',description:'''Use ".*" for all jobs 

''')])])


@NonCPS
def Funcion(){
    
    int value = env.DAYS as Integer    
    def jobNamePattern =env.FILTER   
    def daysBack = value  
    def timeToDays = 24*60*60*1000 
    def myList= ""
    def C_Fail_T=0
    def C_Unst_T=0
    def C_Succ_T=0 
    
    // Bash colors:
    def RED='\033[1;31m'
    def BLUE='\033[1;34m'
    def GREEN='\033[1;32m'
    def YELLOW='\033[1;33m'
    def ORANGE='\033[0;33m'
    def MAGENTA='\033[1;35m'
    def PURPLE='\033[1;35m'
    def CIAN='\033[1;36m'
    def NC='\033[0m' 

    
    def TOTAL= Jenkins.instance.allItems.findAll() {
        
      it instanceof Job && it.fullName.matches(jobNamePattern) 

    }.each {job ->
    
      def builds = job.getBuilds().byTimestamp(System.currentTimeMillis() - daysBack*timeToDays, System.currentTimeMillis())

      
      // individual build details
      def C_Fail=0
      def C_Unst=0
      def C_Succ=0
      
      //if(job.fullName.equals(excluid.findAll { it > job.fullName.toString() }) )
      //{
      //}
      
      builds.each {def build ->
        if(build.result == hudson.model.Result.FAILURE) { C_Fail=C_Fail+1} 
        if(build.result == hudson.model.Result.UNSTABLE){ C_Unst=C_Unst+1}
        if(build.result == hudson.model.Result.SUCCESS) { C_Succ=C_Succ+1}
      }
     C_Fail_T = C_Fail_T + C_Fail
     C_Unst_T = C_Unst_T + C_Unst
     C_Succ_T = C_Succ_T + C_Succ
      myList= myList+ "\n" + (job.fullName + ' ( ' + builds.size() + ' / ' + job.builds.size() + ' )  ' + "in " + daysBack + " day/s " + "LAST STATUS: "+job.getLastBuild()?.result +" | "+RED+ "FAILURE: "+C_Fail +ORANGE+ " UNSTABLE: " + C_Unst +GREEN+ " SUCCESS: " + C_Succ+NC) 
      // individual build details
      //builds.each { build ->
      //  println '   ' + build.number + ' | ' + build.getCauses()[0].getShortDescription() + ' | ' + build.result + ' | ' + build.getTimestampString2() + ' | ' + build.getDurationString()
      //}
    }
    job=null
    build=null
    builds=null
    jobNamePattern=null
    if(env.SHOW_LIST=="YES"){
        println(myList)
    }
    println("RESUME Jobs in "+DAYS+" day/s "+GREEN+": SUCCESS " +C_Succ_T +NC+RED+ "  FAILED "+C_Fail_T+NC+ORANGE+"  UNSTABLE " +C_Unst_T +NC)
    
    if(C_Succ_T==0 && C_Unst_T==0 && C_Fail_T==0)
    {
        println("FILTER input wrong")
        currentBuild.result('FAILURE')
    }
}

timestamps {
withCredentials([usernamePassword(credentialsId: '501b9ef0-5c12-4b19-9cd1-1fcd87e37aec', passwordVariable: 'OS_PASSWORD', usernameVariable: 'OS_USERNAME')]) {
ansiColor('xterm') {

    String repoUrl = "YOUR_REPO_IF_NEED"
    
node{

    echo 'Clearing workspace before cloning: '
    cleanWs()
    // Clones the repository from the current branch name
    git credentialsId: 'credentialsId', url: repoUrl
    Funcion()

    }


} //USER
} //XTERM

} //TIMESTAMP

I use XTERM to add color to your Terminal, if you dont use it, please delete that "{}" brackets and delete "// Bash colors:" part.

Hope you understand me.

Franco

EDIT: You will have to give some permission in "<URL_OF_YOUR_JENKINS>/jenkins/scriptApproval/"

FrankieGG
  • 21
  • 4