Jenkins Groovy Remote Control Plugin - example - groovy

I can't connect to Jenkins and execute script via Groovy Remote Plugin.
I found only this documentation: https://wiki.jenkins-ci.org/display/JENKINS/Groovy+Remote+Control+Plugin
My example:
class GroovyDemo {
static void main(def args) {
def transport = new HttpTransport("http://my-jenkins/plugin/groovy-remote/")
def remote = new RemoteControl(transport)
//1
def result1 = remote {
return jenkins.version.value
}
println "Jenkins version was ${result1}."
//2
def result2 = remote {
return Jenkins.getInstance().getItems().size()
}
println "Jobs count: ${result2}."
}
}
I get the result:
Jenkins version was 1.580.3.
0
Why I get zero as number of jobs despite I have many jobs on my Jenkins?
Thanks

You used different variable names for the Jenkins instance - lower case "jenkins" for the successful call and upper case "Jenkins" for the unsuccessful one.

Related

How to get session data in jenkins delarative piepline

I dont want to used from CurrentBuild or CurrentUser because this return the user information that who build the job , but i wnat to get the user information that login to jenkins.
for example the job X run by timer and the one user will aborted this , i want to found that which user aborted this job .
you can use the below code. pay attention when you want to execute this code you have to permit to run these methods by go to " manage Jenkins/in process script Approval" and approve them to be executable. by using this code you can get whom aborted Jenkins pipeline not only in manually running job also in running by timer.
pipeline {
agent any
triggers{cron("*/1 * * * *")}
stages {
stage('Hello') {
steps {
sleep(20000)
echo 'Hello World'
}
}
}
post{
aborted{
script{
def causee = ''
def actions = currentBuild.getRawBuild().getActions(jenkins.model.InterruptedBuildAction)
for (action in actions) {
def causes = action.getCauses()
// on cancellation, report who cancelled the build
for (cause in causes) {
causee = cause.getUser().getDisplayName()
cause = null
}
causes = null
action = null
}
actions = null
echo causee
}
}
}
}

functions implementation

I have implemented multiple groovy methods for sending different notifications, but the code breaks-off the functions concept. So i want to rewrite/combine all groovy methods in one single methods so that i can call that one method wherever i need.
Doesn't matter success or failure and i need to pass message as parameter.
static void sendSuccessApplicationNotification(p1,p2,p3,p4) {
def x = Notify(this)
x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p3}")
x.triggerBuild("SUCCESSFUL, application ${p1}:${p2} started properly", "${p4")
}
Finally above above should be converted to one method.Checked many articles not getting an exact example.
you can use groovy template engine in your generalized function:
import groovy.text.SimpleTemplateEngine
void triggerBuild(a,b){
println "${a} >>>> ${b}"
}
void sendNotification(code, Map parms, List nodes) {
def templates = [
'appY': 'SUCCESSFUL, application ${app}:${ver} started properly',
'appN': 'FAILED, application ${app}:${ver} failed to start properly',
'depY': 'SUCCESSFUL deployment of ${app}:${ver} to ${node}<br>Executed by ${user}',
'depN': 'FAILED deployment of ${app}:${ver} to ${node}<br>Executed by ${user}'
]
def template = templates[code]
assert template
def message = new SimpleTemplateEngine().createTemplate(template).make(parms).toString()
nodes.each{node->
triggerBuild(message, node)
}
}
sendNotification('appY',[app:'myapp', ver:'v123'],['n1','n2'])
the code above will output:
SUCCESSFUL, application myapp:v123 started properly >>>> n1
SUCCESSFUL, application myapp:v123 started properly >>>> n2

How can I call Shell Script on remote machine from Browser or Azure Functions

I have a shell file on the remote machine which will perform certain required actions. Can I call this shell from outside of the VM.
Like by using Azure functions or browser itself.
Here is the Snapshot for shell.
According your needs,I suggest you connecting to a remote server using SSH and execute commands.
I'm not sure which language you are using. So,I just offer java sample code for you here.
You could use SSH component JCraft for remote connection and shell commands invocations.
JSch jsch = new JSch();
String command = "/tmp/myscript.sh";
Session session = jsch.getSession(user, host, 22);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (channel.getExitStatus() == 0) {
System.out.println("Command executed successully.");
}
break;
}
}
channel.disconnect();
session.disconnect();
Also,you could refer to this thread How do I run SSH commands on remote system using Java?.
Hope it helps you. Any concern,please feel free to let me kown.

How to make capturing output from an external process thread-safe?

I've written a small method to execute the git command line tool and capture its output:
def git(String command) {
command = "git ${command}"
def outputStream = new StringBuilder()
def errorStream = new StringBuilder()
def process = command.execute()
process.waitForProcessOutput(outputStream, errorStream)
return [process.exitValue(), outputStream, errorStream, command]
}
I'm using it with GPars to clone multiple repositories simultaneously like
GParsPool.withPool(10) {
repos.eachParallel { cloneUrl, cloneDir->
(exit, out, err, cmd) = git("clone ${cloneUrl} ${cloneDir}")
if (exit != 0) {
println "Error: ${cmd} failed with '${errorStream}'."
}
}
}
However, I believe my git method it not thread-safe: For example, a second thread could modify command in the first line of the method before the first thread reached command.execute() in the fifth line of the method.
I could solve this by making the whole git method synchronized, but that would defeat the purpose of running it in different threads as I want clones to happen in parallel.
So I was thinking to do partial synchronization like
def git(String command) {
def outputStream
def errorStream
def process
synchronized {
command = "git ${command}"
outputStream = new StringBuilder()
errorStream = new StringBuilder()
process = command.execute()
}
process.waitForProcessOutput(outputStream, errorStream)
return [process.exitValue(), outputStream, errorStream, command]
}
But I guess that also is not safe as in thread two waitForProcessOutput() might return earlier than in thread one, screwing up the outputStream / errorStream variables.
What is the correct way to get this thread-safe?
Change the assignment statement inside the eachParallel closure argument as follows:
def (exit, out, err, cmd) = git("clone ${cloneUrl} ${cloneDir}")
This will make the variables local to the closure, which in turn will make them thread-safe. The git() method is fine as is.

How to run testcase and testsuite using Groovy in soapui?

i have some projects in soapui.
i want to execute testsuites and testcases of these projects.
i tried with this groovy code:
//get test case from other project or from the same one
project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName("Project1")
testSuite = project.getTestSuiteByName("TestSuite 1 - Login");
testCase = testSuite.getTestCaseByName("TestCase 1-Login");
Thread.sleep(3000)
testSuite2 = project.getTestSuiteByName("TestSuite3 - Report");
testCase2 = testSuite.getTestCaseByName("TestCase1 - Report");
// run test case
runner = testCase.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);
Thread.sleep(3000)
runner2 = testCase2.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);
When i run this groovy code, i have the following error message:
java.lang.NullPointer.Exception
cannot invoke method run() on null object for the last line
runner2 = testCase2.run(new com.eviware.soapui.support.types.StringToObjectMap(), false);
If i remove the last line it's working well.
Any help please.
Thank you
I know this is super late to answer this question, but i will answer this so that it can help help seeking for help.
instead of Thread.sleep(3000), just use:
runner.waitUntilFinished()
Now it will wait until execution of step 1 get finished. Then it will start executing Step 2.
The only thing I can think of is that you're calling the wrong testcase on the step2, I tested the same with other test cases I have and it's happening the same If I put a wrong name for the test case I want to execute.
// TO RUN A TEST SUITEs ALL get APIs, getting testSuite handle from current //test_Case
// TO POST COMMENT I HAVE ADDED underscore char BELOW
// u need to import here
def my_TestSuite = testRunner.testCase.testSuite
log.info(my_TestSuite.name)
for (my_TestCase in my_TestSuite.get_TestCaseList())
{
for (testStep in myTestCase.get_TestStepList())
{
if( testStep instanceof WsdlTestRequestStep || testStep instanceof RestTestRequestStep ) {
def http_Verb = (testStep.getTestRequest().getMethod())
String apiType = http_Verb.toString()
if (apiType == "GET"){
log.info(myTestCase.name)
}
}
}
}

Resources