脚本jenkinsfile并行阶段

时间:2017-10-19 16:49:42

标签: jenkins jenkins-pipeline

我正在尝试使用groovy DSL编写一个脚本化的Jenkins文件,它将在一组阶段中具有并行步骤。

这是我的jenkinsfile:

node {   
stage('Build') {
    sh 'echo "Build stage"'
}

stage('API Integration Tests') {
    parallel Database1APIIntegrationTest: {
        try {
            sh 'echo "Build Database1APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }               

    }, Database2APIIntegrationTest: {
        try {
            sh 'echo "Build Database2APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }

    }, Database3APIIntegrationTest: {
        try {
            sh 'echo "Build Database3APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }
    }
}

stage('System Tests') {
    parallel Database1APIIntegrationTest: {
        try {
            sh 'echo "Build Database1APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }               

    }, Database2APIIntegrationTest: {
        try {
            sh 'echo "Build Database2APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }

    }, Database3APIIntegrationTest: {
        try {
            sh 'echo "Build Database3APIIntegrationTest parallel stage"'
        }
        finally {
            sh 'echo "Finished this stage"'
        }
    }
}
}

我想要有3个阶段:构建;集成测试和系统测试。 在两个测试阶段中,我希望并行执行3组测试,每组测试针对不同的数据库。

我有3个可用的执行者。一个在master和2个代理上,我希望每个并行步骤在任何可用的执行程序上运行。

我注意到的是,在运行我的管道后,我只看到3个阶段,每个阶段都标记为绿色。我不想查看该阶段的日志,以确定该阶段中的任何并行步骤是否成功/不稳定/失败。

我希望看到我的测试阶段中的3个步骤 - 标记为绿色,黄色或红色(成功,不稳定或失败)。

我已经考虑将测试扩展到他们自己的阶段,但已经意识到并不支持并行阶段(有谁知道这是否会得到支持?),所以我不能这样做,因为管道也需要很长时间很难完成。

非常感谢任何见解,谢谢

7 个答案:

答案 0 :(得分:15)

在Jenkins脚本化管道中,parallel(...)接受一个Map,描述要构建的每个阶段。因此,您可以以编程方式预先构建构建阶段,该模式可实现灵活的串行/并行切换。
我使用了与此类似的代码,其中prepareBuildStages返回一个Map列表,每个List元素是按顺序执行的,而Map在那一点描述了并行阶段。

// main script block
// could use eg. params.parallel build parameter to choose parallel/serial 
def runParallel = true
def buildStages

node('master') {
  stage('Initialise') {
    // Set up List<Map<String,Closure>> describing the builds
    buildStages = prepareBuildStages()
    println("Initialised pipeline.")
  }

  for (builds in buildStages) {
    if (runParallel) {
      parallel(builds)
    } else {
      // run serially (nb. Map is unordered! )
      for (build in builds.values()) {
        build.call()
      }
    }
  }

  stage('Finish') {
      println('Build complete.')
  }
}

// Create List of build stages to suit
def prepareBuildStages() {
  def buildList = []

  for (i=1; i<5; i++) {
    def buildStages = [:]
    for (name in [ 'one', 'two', 'three' ] ) {
      def n = "${name} ${i}"
      buildStages.put(n, prepareOneBuildStage(n))
    }
    buildList.add(buildStages)
  }
  return buildList
}

def prepareOneBuildStage(String name) {
  return {
    stage("Build stage:${name}") {
      println("Building ${name}")
      sh(script:'sleep 5', returnStatus:true)
    }
  }
}

生成的管道显示为: Jenkins Blue Ocean parallel pipeline

并行块中嵌套的内容有某些限制,有关详细信息,请参考the pipeline documentation。不幸的是,尽管它的灵活性不如脚本化(IMHO),但很多参考似乎偏向于声明式管道。 pipeline examples页是最有用的。

答案 1 :(得分:9)

以下是docs

的示例
  

并行执行

     

上一节中的示例在线性系列中跨两个不同平台运行测试。实际上,如果make check执行需要30分钟才能完成,那么“Test”阶段现在需要60分钟才能完成!

     

幸运的是,Pipeline具有并行执行Scripted Pipeline部分的内置功能,在适当命名的并行步骤中实现。

     

重构上面的示例以使用并行步骤:

// Jenkinsfile (Scripted Pipeline)


stage('Build') {
    /* .. snip .. */
}

stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    },
    windows: {
        node('windows') {
            /* .. snip .. */
        }
    }
}

答案 2 :(得分:6)

这是一个基于@Ed Randall帖子的无循环或函数的简单示例:

node('docker') {
    stage('unit test') {
        parallel([
            hello: {
                echo "hello"
            },
            world: {
                echo "world"
            }
        ])
    }

    stage('build') {
        def stages = [:]

        stages["mac"] = {
            echo "build for mac"
        }
        stages["linux"] = {
            echo "build for linux"
        }

        parallel(stages)
    }
}

...这将产生以下结果:

blue-ocean-view

请注意,地图的值不必是阶段。您可以直接进行操作。

答案 3 :(得分:1)

此处简化@Ed Randall的回答。 请记住,这是Jenkinsfile脚本(不是声明性的)

stage("Some Stage") {
    // Stuff ...
}


stage("Parallel Work Stage") {

    // Prealocate dict/map of branchstages
    def branchedStages = [:]

    // Loop through all parallel branched stage names
    for (STAGE_NAME in ["Branch_1", "Branch_2", "Branch_3"]) {

        // Define and add to stages dict/map of parallel branch stages
        branchedStages["${STAGE_NAME}"] = {
            stage("Parallel Branch Stage: ${STAGE_NAME}") {
                // Parallel stage work here
                sh "sleep 10"
            }
        }

    }

    // Execute the stages in parallel
    parallel branchedStages
}


stage("Some Other Stage") {
    // Other stuff ...
}

请注意花括号。 这将产生以下结果(使用BlueOcean Jenkins插件):

Scripted Jenkinsfile Result Link

答案 4 :(得分:0)

我也在尝试类似的步骤来执行并行阶段并在阶段视图中显示所有这些阶段。您应该在并行步骤内编写一个阶段,如下面的代码块所示。

// Jenkinsfile (Scripted Pipeline)

stage('Build') {
    /* .. Your code/scripts .. */
}

stage('Test') {
    parallel 'linux': {
        stage('Linux') {
            /* .. Your code/scripts .. */
        }
    }, 'windows': {
        stage('Windows') {
            /* .. Your code/scripts .. */
        }
    }
}

答案 5 :(得分:0)

上面带有 FOR 的例子是错误的,因为变量 STAGE_NAME 每次都会被覆盖,我和黄伟遇到了同样的问题。

在这里找到解决方案:

https://www.convalesco.org/notes/2020/05/26/parallel-stages-in-jenkins-scripted-pipelines.html

def branchedStages = [:]
def STAGE_NAMES =  ["Branch_1", "Branch_2", "Branch_3"]
STAGE_NAMES.each { STAGE_NAME ->
 // Define and add to stages dict/map of parallel branch stages
    branchedStages["${STAGE_NAME}"] = {
        stage("Parallel Branch Stage: ${STAGE_NAME}") {
        // Parallel stage work here
            sh "sleep 10"
        }
    }
  }
parallel branchedStages

答案 6 :(得分:-1)

我在并行块中多次使用stage{}。然后每个阶段都显示在舞台视图中。包含parallel的父阶段不包括所有并行阶段的时间,但每个并行阶段都显示在阶段视图中。

在蓝色海洋中,平行阶段分别出现而不是显示的阶段。如果存在父级,则它显示为并行阶段的父级。

如果您没有相同的体验,可能需要进行插件升级。

相关问题