Jenkins管道脚本中@NonCPS的作用是什么 [英] What is the effect of @NonCPS in a Jenkins pipeline script

查看:695
本文介绍了Jenkins管道脚本中@NonCPS的作用是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Jenkins中有一个管道脚本.

I have a pipeline script in Jenkins.

我曾经遇到这个异常:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: 脚本不允许使用groovy.json.JsonSlurperClassic方法 parseText java.lang.String

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.json.JsonSlurperClassic parseText java.lang.String

我查找了异常,发现一些迹象表明我应该注释使用@NonCPS发生异常的方法.我这样做的时候并没有真正理解它的作用.

I looked the exception up and I found some indications that I should annotate the method where theexception occurs with @NonCPS. I did this, without really understanding what this does.

但是,此后,我在该方法中引发的异常不再被try子句捕获.

After that however, an Exception that I was throwing in that method was no longer caught by a try clause.

那么@NonCPS背后的想法是什么?使用它有什么作用?

So what's the idea behind @NonCPS? What are the effects of using it?

推荐答案

您看到的异常是由于

The exception that you are seeing is due to script security and sandboxing. Basically, by default, when you run a pipeline script, it runs in a sandbox which only allow usage of certain methods and classes. There are ways to whitelist operations, check the link above.

当您使用的方法使用无法序列化的对象时,@NonCPS注释将非常有用.通常,您在管道脚本中创建的所有对象都必须可序列化(原因是Jenkins必须能够序列化脚本的状态,以便可以将其暂停并存储在磁盘上).

The @NonCPS annotation is useful when you have methods which use objects which aren't serializable. Normally, all objects that you create in your pipeline script must be serializable (the reason for this is that Jenkins must be able to serialize the state of the script so that it can be paused and stored on disk).

@NonCPS放在方法上时,Jenkins将一次性执行整个方法,而不会暂停.同样,您不允许从@NonCPS带注释的方法中引用任何管道步骤或CPS转换的方法. 有关此的更多信息,请点击此处.

When you put @NonCPS on a method, Jenkins will execute the entire method in one go without the ability to pause. Also, you're not allowed to reference any pipeline steps or CPS transformed methods from within an @NonCPS annotated method. More information about this can be found here.

关于异常处理:不100%地确定您正在经历什么;我已经尝试了以下方法,并且可以按预期工作:

As for the exception handling: Not 100% sure what you are experiencing; I've tried the following and it works as expected:

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

try {
    myFunction();
} catch (Exception e) {
    echo "Caught";
}

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

def mySecondFunction() {
    try {
        myFunction();
    } catch (Exception e) {
        echo "Caught";
    }
}

mySecondFunction();

最后:

@NonCPS
def myFunction() {
    throw new RuntimeException();
}

@NonCPS
def mySecondFunction() {
    try {
        myFunction();
    } catch (Exception e) {
        echo "Caught";
    }
}

mySecondFunction();

所有打印均按预期捕获".

All print "Caught" as expected.

这篇关于Jenkins管道脚本中@NonCPS的作用是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆