问题
In my code I have a method that parse log file and return list of results. Without NonCPS it works perfect and return correct values. This method is called from pipeline stages and I got java.io.NotSerializableException: java.util.regex.Matcher that's why I put @NonCPS annotation. Exception is not thrown anymore but log_parser method doesnt work well. Now it always return whole file - even if remove return result_list. The result of calling this method is always file.
@NonCPS
def log_parser(String filename){
def result_list = []
def match_f, match_s
def lines = readFile(filename).readLines()
for( line in lines ) {
match_f = (line =~ /(?<=Failures: )[^ ]+/ )
match_s = (line =~ /(?<=Skips: )[^ ]+/ )
if( match_f ) {
result_list[1] = (match_f[0]).replace(",", "") }
if( match_s ) {
result_list[2] = (match_s[0]).replace(",", "") }
}
return result_list
}
回答1:
Because pipeline will serialize all variables (includes local variable inside function) as default behaviour, but java.util.regex.Matcher
is not serializable, that's why you get the error.
Option 1) release not serializable variable immediately once you complete using it.
def log_parser(String filename){
def result_list = []
def match_f, match_s
def lines = readFile(filename).readLines()
for( line in lines ) {
match_f = (line =~ /(?<=Failures: )[^ ]+/ )
match_s = (line =~ /(?<=Skips: )[^ ]+/ )
if( match_f ) {
result_list[1] = (match_f[0]).replace(",", "")
match_f = null
}
if( match_s ) {
result_list[2] = (match_s[0]).replace(",", "")
match_s = null
}
}
return result_list
}
Option 2) move not serializable variables into function with annotation: @NonCPS
, inside @NonCPS function, we can't call any other pipeline step, therefor you should move readFile
out of log_pareser()
log_parser(readFile(<log file path>))
@NonCPS
def log_parser(String fileContent){
def result_list = []
def match_f, match_s
def lines = fileContent.readLines()
for( line in lines ) {
match_f = (line =~ /(?<=Failures: )[^ ]+/ )
match_s = (line =~ /(?<=Skips: )[^ ]+/ )
if( match_f ) {
result_list[1] = (match_f[0]).replace(",", "") }
if( match_s ) {
result_list[2] = (match_s[0]).replace(",", "") }
}
return result_list
}
来源:https://stackoverflow.com/questions/55684174/groovy-jenkins-pipeline-noncpsreturn-not-expected-results