In Jenkins I have a system groovy script build step. Is there any way to cancel a long running script, or to have some code within the system groovy script which can tell whether its build has been cancelled?
Jenkins will interrupt the thread which is running the script when you cancel the build.
So you can either manually check the thread's interrupt status and abort your script at certain points, e.g.
if (Thread.currentThread().interrupted()) {
throw new InterruptedException()
}
Or you can let Groovy do that for you by including the ThreadInterrupt annotation in your script, e.g.
#groovy.transform.ThreadInterrupt
Also make sure that none of your catch blocks will swallow an InterruptedException.
Related
Is it possible to / how do you run a groovy script from a SoapUI assertion without copy/pasting the script into all of your test steps where you need the same script executed? Is it possible to write a script outside of the assertion and run the script like you are calling a method? So that you can reuse the assertion script in multiple test steps.
So far, I've tried to call a groovy test step from within the assertion, but the run() method requires a testRunner variable which is unavailable from within the assertion. I've also tried to write a groovy script as a subsequent test step (not an assertion) that calls another groovy test step script, but I was unable to transfer the response from one test step to the next (Honestly, I'd rather not create test steps that are really just assertions).
Note: this is not a duplicate of How to create variables in soapui test case that can be accessed across all test steps - groovy test step & script assertion test step? because that question pertains to storing properties, not reusing scripts.
I was able to finally figure out my 2nd approach: add another groovy script as a subsequent test step that has assertions and passes the response. The script is:
context.response = context.expand('${MyTestStep#Response}') // store response to context variable
Object result = testRunner.testCase.testSuite.testCases['Validate Response'].testSteps['Validate Response'].run(testRunner, context)
if(result.getError() != null) {
log.error("error", result.getError())
assert false
}
assert true
MyTestStep is the test step before the groovy script. Validate Response is the name of the test case of the groovy script which is also called Validate Response and is executed via the run method.
I am trying to understand how exactly is the following Gradle script executed:
task loadTestData(dependsOn: ['fakeTask', createSchema])
I assume that:
loadTestData is a method call
dependsOn is a named argument
But on which object is the method called?
Actually a Task is being executed as part of gradle build workflow. Tasks in gradle get no parameters but can operate on the system/environment/build variables.
Then dependsOn which is a property of the Task gets the tasks the declared defined task is dependent on.
In this case you declare that task loadTestData is dependent on tasks fakeTask and createSchema.
I was thinking of using a Groovy script for my build job in Jenkins because I have some conditions to check for that might need access to Jenkins API.
Is it possible to find out who or what triggered the build from a Groovy script? Either an SCM change, another project or user. I have just begun reading a little about Groovy and the Jenkins API.
I want to check for the following conditions and build accordingly. Some Pseudocode:
def buildTrigger JenkinsAPI.thisBuild.Trigger
if (buildTrigger == scm) {
execute build_with_automake
def new_version = check_git_and_look_up_tag_for_version
if (new_version) {
execute git tag new_release_candidate
publish release_candidate
}
} else if (buildTrigger == "Build other projects") {
execute build_with_automake
}
The project should build on every SCM change, but only tag and publish if version has been increased. It should also build when a build has been triggered by another project.
I have something similar - I wanted to get the user who triggered the build, this is my code:
for (cause in bld.getCauses()) {
if (cause instanceof Cause.UserIdCause) {
return cause.getUserName()
}
}
(bld is subtype of Run)
So, you can get the causes for your build, and check for their type.
See the different types at Cause javadoc http://javadoc.jenkins-ci.org/hudson/model/Cause.html
i have two dependent jobs. i need help for groovy script in jenkins, for writing pre send script for email-ext plugin.
i want to check whether buid reason is upstream cause, then set cancel variable=true
But i don't know how to write if condition in groovy for jenkins..For seperate jobs, will there be any seperate classes in jenkins(so i can create instance and call upstream cause)
is there any way to check build cause of downstream job is due to upstream..
Please help me on this code snippet..
Use Build.getCauses() method. It will return a list of causes for the build. Loop over it and check if there is an object of hudson.model.Cause.UpstreamCause among them.
To get the build object, use the following code snippet:
def thr = Thread.currentThread()
def build = thr?.executable
FYI, here is a link to the complete Jenkins Module API.
How can I stop a Gradle build after detecting a problem? I can use an assert, throw an exception, do a System.exit (bad idea), or use a dedicated function in Gradle (but I could not find one). What is the best way for Gradle (and why?).
I usually throw the relevant exception from the org.gradle.api package, for example InvalidUserDataException for when someone has entered something invalid, or GradleScriptException for more general errors.
If you want to stop the current task or action, and move on to the next, you can also throw a StopActionException
If you want to stop the build, throw:
throw new GradleException('error occurred')
or throw the subclasses for the above exception. Some of the subclass exceptions actually only fail the current task but continue with the build.
There is currently no dedicated method, although there have been discussions to add one.
The recommended way to stop a Gradle build is to throw an exception. Since Groovy doesn't have checked exceptions, and Gradle by default does not print the exception type, it's not that critical which exception is thrown. In build scripts, GradleException is often used, but a Groovy assertion also seems reasonable (depending on the circumstances and audience). What's important is to provide a clear message. Adding a cause (if available) helps for debugging (--stacktrace).
Gradle provides dedicated exception types StopExecutionException/StopActionException for stopping the current task/task action but continuing the build.
Another option if you don't have any desire to be able to catch the exception later on is to call the ant fail task. It's slightly easier to read in my opinion and you can give a nice message to the user without use of --stacktrace.
task (tarball, dependsOn: warAdmin) << {
ant.fail('The sky is falling!!')
}
Gives you a message like:
* What went wrong:
Execution failed for task ':tarball'.
> The sky is falling!!
Probably you can catch this (perhaps it throws ant's BuildException?) but if that's a goal then I wouldn't use ant.fail. I'd just make it easy to see what exception to catch by throwing standard gradle exception as tim_yates suggested.
Throwing a simple GradleException works in stopping the build script. This works great for
checking required environment setup.
GradleException('your message, why the script is stopped.')
Example:
if(null == System.getenv()['GRADLE_USER_HOME']) {
throw new GradleException('Required GRADLE_USER_HOME environment variable not set.')
}
Here is a code fragment that tries to emulate how the Gradle javac task throws errors:
task myCommand(type:Exec) {
... normal task setup ....
ignoreExitValue true
standardOutput = new ByteArrayOutputStream()
ext.output = { standardOutput.toString() }
doLast {
if (execResult.exitValue) {
logger.error(output())
throw new TaskExecutionException( it,
new Exception( "Command '${commandLine.join(' ')}' failed; "
+ "see task output for details." )
)
}
}
}
When the command returns 0 there is no output. Any other value will print the standardOutput and halt the build.
NOTE: If your command writes to errorOutput as well, you may need to include that in the error log.