How to read the error code in console output from Jenkins pipeline script

Originally posted by tvklovesu on February 24, 2023

Hello,

I have configured my jenkins pipeline with Declarative pipeline script as shown below. Currently I am able to send the emails when the build is unstable. But there are some other situations where the build fails due to testExecute launch error on the remote machine. And even for that failure it is sending emails to everyone in the recipient list. I want to check if the error code is -1 then send the email only to selected emails list else send to everyone.

pipeline{
agent {label “windows”}
stages {
stage(‘Test complete’){

steps {
Step1

}
}
}

post{
unstable {
// echo “This will run when test unstable”
emailext (
subject: “EA smoke test results in Prod”,
body: “Please click below to access the test results \n” + env.BUILD_URL+“TestComplete/”,
to: “[email protected]”,
from: “[email protected]”)
}
}

}

console output with the error exit code to read in the above pipeline script and if that’s true then send the emails to only selected people.

[TestComplete] Test runner exit code: -1.
[TestComplete] [WARNING] Error: The user did not log in using the SmartBear account or did not pass the accesskey in the command-line arguments. TestComplete will be closed.The user did not log in using the SmartBear account or did not pass the accesskey in the command-line arguments. TestComplete will be closed..
[TestComplete] [WARNING] Unable to find the log file "1677263408853.tclogx".
[TestComplete] [WARNING] Unable to find the log file "1677263408853.htmlx".
[TestComplete] [WARNING] Unable to find the log file "1677263408853.mht".
[TestComplete] [WARNING] Errors occurred during the test execution.
[TestComplete] Marking the build as UNSTABLE.
[TestComplete] [WARNING] Unable to publish test results (xml data is empty).
[TestComplete] The test execution finished (Prod_SmokeTest/CORE_Prod_Smoke). 

Originally posted by Bonibom on February 25, 2023

Try global variable currentBuild, E.G. currentBuild.rawBuild.getLog(100) get last 100 line of the log

Originally posted by tvklovesu on February 26, 2023

Bonibom Is that something I can enter in my pipeline script? but how to know if error code is -1.

I want this log to verify the error code before sending the emails.

Originally posted by Bonibom on February 27, 2023

Yes, it is global variable and you can use that within the script. Another way you can get the log from a particular build that your pipeline starts

bRun = build job: 'SomeJobStartingTestComplete', parameters: [ .....
bRun.getRawBuild().getLog(100)

Then you can read the log line by line, E.G.

List<String> log = bRun.getRawBuild().getLog(100)
for (String line : log) 
{
    if (line.contains("Test runner exit code: -1") 
    {
         // Any action if exit code is -1
         ....
    }
}


Originally posted by tvklovesu on February 27, 2023

Thanks Bonibom, for your reply. I have updated my script but still I am getting the following error.

Script in pipeline:

pipeline{
agent {label “windows”}
stages {
stage(‘Test complete’){

steps {
git credentialsId: ‘GitHub-RAVEn’, url: ‘https://github.com/smoke-tests.git’, branch: ‘master’
withVault(configuration: [timeout: 60, vaultUrl: ‘https://vault.com’],
vaultSecrets: [[engineVersion: 1, path: ‘secret//testing’,
secretValues: [[envVar: ‘USERNAME’, vaultKey: ‘username’], [envVar: ‘PASSWORD’, vaultKey: ‘password’]]]]) {
testcompletetest commandLineArguments: “/run /SilentMode /psv:env=prod /psv:ADFSusername=${USERNAME} /psv:ADFSpassword=${PASSWORD}”, generateMHT: true, launchType: ‘lcProject’, project: ‘CORE_Prod_Smoke’, suite: ‘Prod_SmokeTest.pjs’
}
}
}
stage(‘Checking log’){
steps{
script{
List log= currentBuild.rawBuild.getLog(100).contains(“exit code: 0”)
for (String line : log)
{
if (line.contains(“Test runner exit code: 0”))
{
echo ‘aborted’
emailext (
subject: “Core application Failed to login in Prod”,
body: “Core application seems to be failed to login in Prod. Please click the link to access the test results for more details \n” + env.BUILD_URL+“TestComplete/”,
to: '[email protected]’,
from: “[email protected]”)
}
}
}
}
}
}

Error in console

[GitHub Checks] GitHub check (name: Jenkins, status: COMPLETED) has been published.
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method hudson.model.Run getLog int
	at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:265)
	at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:161)
	at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
	at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
	at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
	at WorkflowScript.run(WorkflowScript:18 

Originally posted by Bonibom on February 27, 2023

You may need to add or approve your signatures in Manage Jenkins → In-process Script Approval

Originally posted by tvklovesu on February 27, 2023

I think I don’t have permission to do that as I am not admin. Is there any other way to achieve this without requesting my admin to approve this? Because I need to reuse the same method in multiple pipelines.

Originally posted by Bonibom on February 27, 2023

Try to disable “Use Groovy Sandbox” option in your pipeline if it is enabled. If this does not work, you need to be an admin or ask your Jenkins admin to add signatures or disable script security completely.

Originally posted by tvklovesu on February 27, 2023

If I uncheck that box then I am getting a message for approving the script

tvklovesu_0-1677513852404.png

So don’t we have any other way to read the console output?

Originally posted by Bonibom on February 27, 2023

You can try

  1. currentBuild.rawBuild.log (this might be deprecated but let’s try)

  2. global variable manager using manager.logContains(text) (never tried that )

Anyway, the best way is using Jenkins API methods in your scripts as you may need various methods in the future.

Originally posted by tvklovesu on February 27, 2023

For manager I got the following

[GitHub Checks] GitHub check (name: Jenkins, status: COMPLETED) has been published.
hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: manager for class: WorkflowScript
	at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
	at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)

Originally posted by tvklovesu on February 28, 2023

Bonibom, So, even after I fix the permission issue, how do I use the email functionality that was in the post method of the pipeline script.

Originally posted by Bonibom on February 28, 2023

You can modify variables in the condition block (where you check exit code contains -1) and use those variables in the body, subject in the emailext or everywhere you need in the pipeline. If you meant that. But this does not relate to topic the current thread and more relate to general programming.

Originally posted by tvklovesu on March 20, 2023

Thanks for your help. Finally, I am able to read the exit code and send the emails only when the exit code is -1. Here is my script for anyone else need it later.

stage(‘Checking log’){
steps{
script{
//List log= currentBuild.rawBuild.getLog(100)
boolean Pass= currentBuild.rawBuild.getLog(100).contains(“[TestComplete] Test runner exit code: 0.”)
boolean Fail= currentBuild.rawBuild.getLog(100).contains(“[TestComplete] Test runner exit code: 2.”)
boolean error= currentBuild.rawBuild.getLog(100).contains(“[TestComplete] Test runner exit code: 3.”)
boolean license= currentBuild.rawBuild.getLog(100).contains(“[TestComplete] Test runner exit code: -1.”)

if (Pass)
{
echo ‘Passed’
}else if (Fail){
echo “Failed.”
emailext (
subject: “Core application Failed to login in Prod”,
body: “Core application seems to be failed to login in Prod. Please click the link to access the test results for more details \n” + env.BUILD_URL+“TestComplete/”,
to: '[email protected], [email protected], [email protected]’
from: “[email protected]”)
}
else if (error || license){
echo “Error or License”
emailext (
subject: “TestComplete has error to run in jenkins”,
body: “TestComplete failed to run in Jenkins. Please click the link to access the test results for more details \n” + env.BUILD_URL+“TestComplete/”,
to: '[email protected]’
from: “[email protected]”)
}
}
}
}