Jenkins Groovy how to call methods from @NonCPS method without ending pipeline

馋奶兔 提交于 2019-12-31 22:43:20

问题


I need to parse some JSON in a Jenkins Pipeline and call some regular methods in a loop, however the script always exits after the first function call. How to do this?

import groovy.json.JsonSlurper
import com.cloudbees.groovy.cps.NonCPS

@NonCPS
def myMethod(String json) {
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper(json)
    jsonObject.each {
        obj ->
            switch(obj.name) {
                case "foo":
                    doAThing(obj)
                    break
                case "bar":
                    doAnotherThing(obj)
                    break
            }
    }
}

In the above example, even with a json object like:

[{
    "name": "foo"
}, {
    "name": "bar"
}]

...the pipeline always exits after the first iteration. This is presumably due to mixing sync and async functions. Is there any way to do this?


回答1:


I've resolved this issue essentially by doing the following:

import groovy.json.JsonSlurper

def myMethod(String json) {
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper(json)
    jsonSlurper = null
    for(int i = 0; i < jsonObject.size(); i++) {
        switch(jsonObject[i].name) {
            case "foo":
                doAThing(jsonObject[i])
                break
            case "bar":
                doAnotherThing(jsonObject[i])
                break
        }
    }
}

Immediately destroy the JsonSlurper instance after it's used, remove @NonCPS annotation, switch to a c-style for loop instead of each.




回答2:


Just to clarify, this is documented as an unsupported feature - https://github.com/jenkinsci/workflow-cps-plugin/#technical-design

You may not call regular (CPS-transformed) methods, or Pipeline steps, from a @NonCPS method, so they are best used for performing some calculations before passing a summary back to the main script.



来源:https://stackoverflow.com/questions/36636017/jenkins-groovy-how-to-call-methods-from-noncps-method-without-ending-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!