Search code examples
multithreadingjenkinsjenkins-pipelinejenkins-blueocean

Is there a way to dynamically rename a stage in a Jenkinsfile while running?


My software has currently 6 modules which have several stages they run through: compile, unit tests, integration tests, sonarqube analysis, war file creation. To improve the performance and limit the concurrent threads I put those stages in instances of my class Step which holds minimal information about it dependents and if it's done.

To run the exact number of threads I created workers which pull new work until everything is done.

def parallelWorkers = [:]
Data.maxConcurrentBuilds.times {
  parallelWorkers["Worker#${it}"] = {
    Step work = getWork()
    if (work == null) {
      echo "Could not get initial work"
      return null
    }

    waitUntil {
      stage(work.name) {
        work.run()
      }
      work = getWork()
      return work == null
    }
    echo "No remaining work. Shutting down worker ${it}"
  }
}
try {
  stage('Parallel workers for module building') {
    gitlabCommitStatus('modules') {
      parallel parallelWorkers
    }
  }
} catch (e) {
  throw e
}

But the issue is, that the steps are not shown in the BlueOcean UI. OceanView

Now I wonder if there is a way to dynamically rename those stages? From what I've read BlueOcean doesn't support such nesting so my idea is to just change the stage name of the worker it is running in.


Solution

  • You have to invoke the name using "${}", I have done this a lot of times and it works perfectly:

    String test = 'my_stage_name'
    stage("${test}") {
    }
    

    I don't know if "${work.name}" will work, if not, you can use an intermediate String to storage the work.name value and invoke him after with "${}".

    UPDATED:

    This have worked for me:

    def workerNames = ['one','two','three']
    def builds = [:]
    
    workerNames.each {
    
        builds[it] = {
    
            stage("Worker#${it}") {
                println(it)    
            }
        }   
    }
    
    stage ('test') {
    
        parallel builds
    }
    

    result:

    enter image description here

    enter image description here