Setting Jenkins multijob build result with Groovy script based on % pass/fail child jobs

时间:2018-03-13 15:09:43

标签: java jenkins groovy testng

I have a Jenkins Multijob project with a very simple structure:

  • Multijob
    • childjob 1
    • childjob 2
    • childjob 3
    • childjob 4 etc...

I want to set the Multijob status as follows:

  • I want a green ball if all child jobs pass
  • I want a yellow ball if any are skipped OR < 25% fail
  • I want a red ball if >= 25% fail

I know I can use a Groovy post build action with a script such as that below, but I don't know how to set the required threshold levels:

void log(msg) {
manager.listener.logger.println(msg)
}

threshold = Result.SUCCESS

void aggregate_results() {
    failed = false

    mainJob = manager.build.getProject().getName()
    job = hudson.model.Hudson.instance.getItem(mainJob)

    log '-------------------------------------------------------------------------------------'
    log 'Aggregated status report'
    log '-------------------------------------------------------------------------------------'

log('${mainJob}    #${manager.build.getNumber()} - ${manager.build.getResult()}')

job.getLastBuild().getSubBuilds().each { subBuild->
  subJob = subBuild.getJobName() 
  subJobNumber = subBuild.getBuildNumber()
  job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
  log '${subJob}   #${subJobNumber} - ${job.getLastCompletedBuild().getResult()}'
  log job.getLastCompletedBuild().getLog()

  //println subBuild
  dePhaseJob = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
  dePhaseJobBuild = dePhaseJob.getBuildByNumber(subBuild.getBuildNumber())
  dePhaseJobBuild.getSubBuilds().each { childSubBuild ->
    try {
        log '   ${childSubBuild.jobName}'

        job = hudson.model.Hudson.instance.getItem(childSubBuild.getJobName())
        build = job.getBuildByNumber(childSubBuild.getBuildNumber())

        indent = '  '    
        log '${indent} #${build.getNumber()}  - ${build.getResult()}' 
        log build.getLog()

        if(!failed && build.getResult().isWorseThan(threshold) ) {
          failed = true
        }
    } catch (Exception e) {    
        log('ERROR: ${e.getMessage()}')
        failed = true
    }
  }
}

if(failed) {manager.build.setResult(hudson.model.Result.FAILURE)}
}

try {
  aggregate_results()
} catch(Exception e) {
  log('ERROR: ${e.message}')
  log('ERROR: Failed Status report aggregation')
  manager.build.setResult(hudson.model.Result.FAILURE)
}

Can anyone help tweak the script to achieve what I need?

1 个答案:

答案 0 :(得分:0)

不确定这是否真的可以作为答案。可能更多的是注释,但是注释并不能真正使它们适合长代码片段,因此可以使用。

为了使您的代码更易读和易于理解,我执行了以下操作:

  • 用常规属性访问替换了getXX和setYY的所有实例,例如build.getResult()变为build.result
  • 消除了在函数调用中不必要使用括号的情况,例如log('ERROR: ${e.getMessage()}')成为log 'ERROR: ${e.getMessage()}'
  • 在单引号和双引号中替换了字符串插值,因为字符串插值在单引号中不起作用。例如。 log 'ERROR: ${e.message}'成为log "ERROR: ${e.message}"
  • 从声明脚本全局绑定范围中的所有变量切换为本地,例如subJob = ...成为def subJob = ...。声明全局范围内的所有内容都会导致难以发现的问题,尤其是如果您正在重新使用诸如job之类的变量名。

我还清理了一些冗余,例如:

job.getLastBuild().getSubBuilds().each { subBuild->
  subJob = subBuild.getJobName() 
  subJobNumber = subBuild.getBuildNumber()
  job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())  // <---
  ...
  //println subBuild
  dePhaseJob = hudson.model.Hudson.instance.getItem(subBuild.getJobName()) // <---
  dePhaseJobBuild = dePhaseJob.getBuildByNumber(subBuild.getBuildNumber())

所以在这里我们将jobdePhaseJob设置为相同的值。像这样将相同的值分配给两个单独的变量是多余的,只会使代码更难阅读。

此外(而且我对jenkins内部api并不十分熟悉,所以我在这里可能是错的)上述代码中的以下流程似乎已关闭:

  • 我们有subBuild实例
  • 然后我们将相应的作业实例检索到jobdePhaseJob
  • 然后我们使用dePhaseJobBuild将内容恢复到dePHaseJob.getBuildByNumber(subBuild.buildNumer)

但是这不就给我们留下subBuild == dePhaseJobBuild吗?即我们花了所有这些代码只是为了检索我们已经拥有的值。我们从构建到工作再到构建。除非我在詹金斯api中缺少一些深奥的东西,否则这似乎也是多余的。

在完成所有这些更改以及其他一些较小的更改后,我们使用以下代码进行了合并:

def job(name) {
  hudson.model.Hudson.instance.getItem(name) 
}

def aggregateResults() {
  def mainJobName = manager.build.project.name
  log '-------------------------------------------------------------------------------------'
  log 'Aggregated status report'
  log '-------------------------------------------------------------------------------------'
  log "${mainJobName}    #${manager.build.number} - ${manager.build.result}"

  def failed = false
  job(mainJobName).lastBuild.subBuilds.each { subBuild ->
    log "${subBuild.jobName}   #${subBuild.buildNumber} - ${subBuild.result}"
    log subBuild.log

    subBuild.subBuilds.each { subSubBuild ->
      try {
        log "   ${subSubBuild.jobName}   #${subSubBuild.buildNumber} - ${subSubBuild.result}"
        log "   " + subSubBuild.getLog(Integer.MAX_VALUE).join("\n   ") //indent the log lines

        if(!failed && subSubBuild.result.isWorseThan(threshold)) {
          failed = true
        }
      } catch (Exception e) {
        log "ERROR: ${e.message}"
        failed = true
      }
    }
  }

  if(failed) {
    manager.build.result = hudson.model.Result.FAILURE
  }
}

再说一次,我没有jenkins实例可以对此进行测试,因此我在黑暗中飞来飞去,并为错误拼写,语法错误或其他滥用代码和jenkins api的行为道歉。

您的代码中的问题(例如我无法看到的字符串内插问题)使我认为原始代码不起作用,而只是一个示例模式。

这使我进一步怀疑您是否真的需要在此处进行两个级别的嵌套,即以下内容:

job(mainJobName).lastBuild.subBuilds.each { subBuild ->
  subBuild.subBuilds.each { subSubBuild ->
    ...
  }
}

真的有必要还是一个级别就足够了?从您问题中的快速图表看来,我们似乎只需要关心主要工作及其子工作,而不必关心子工作。

在这种情况下,您可以遵循以下逻辑:

def aggregateResults() {
  def mainJob = job(manager.build.project.name)
  def subs    = mainJob.lastBuild.subBuilds
  def total   = subs.size()
  def failed  = subs.findAll { sub -> sub.result.isWorseThan(threshold) }.size()

  if(failed > 0) {
    manager.build.result = hudson.model.Result.FAILURE
  }

  failed == 0 ? "green" : (failed/total < 0.25 ? "yellow" : "red")
}