How to Run a JMeter Script as a Windows Cron Job - cron

I am in need of scheduling my test such that my JMeter script automatically runs without I having to manually execute it daily. This can be accomplished via a Windows cron job but I do not know how to configure the JMeter script to run as a Windows cron job. Normally I use the command "jmeter -n -t path\filename.jmx -l path\log.csv" to execute my JMeter script via the command line so I assume if I can make this command run as a cron job it should solve the problem theoretically. So I sincerely appreciate if someone could provide the steps and details to accomplish this, thanks.

You can do it using Windows Task Scheduler like
Open Task Scheduler
Click Action -> Create Task
On "General" tab provide name
On "Triggers" tab provide when you would like to run it
On "Actions" tab create a new action like:
Program: c:\windows\system32\cmd.exe
Arguments: /c c:\jmeter\bin\jmeter.bat -n -t c:\jmeter\extras\Test.jmx -l c:\jmeter\bin\Test_%date:~10,4%%date:~4,2%%date:~7,2%.jtl
Change JMeter and .jmx script location to match your details.
Each time your task runs the file with current date should appear in "bin" folder of your JMeter installation like Test_20180514.jtl for today
Just in case here is exported task:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2018-05-14T07:50:02.7061254</Date>
<Author>aldan\anonymous</Author>
<URI>\JMeter</URI>
</RegistrationInfo>
<Triggers />
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-2873627350-121124179-3591956082-1001</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>c:\windows\system32\cmd.exe</Command>
<Arguments>/c c:\jmeter\bin\jmeter.bat -n -t c:\jmeter\extras\Test.jmx -l c:\jmeter\bin\Test_%date:~10,4%%date:~4,2%%date:~7,2%.jtl</Arguments>
</Exec>
</Actions>
</Task>
Be aware that easier option could be using Jenkins to orchestrate your builds, this way you will have history, metrics, conditional failure criteria and performance trend charts.
See Continuous Integration 101: How to Run JMeter With Jenkins article for more information regarding adding performance tests under Jenkins control

Related

Ansible: setup a cron job on one host

I'm deploying a 2-hosts service that also needs to setup a cron job. This job should only be run on one of the two machines (I dont care which). what's the easiest way to do so?
I know that the shell module in Ansible supports "run_once", but the cron module does not.
I could setup the cron job on both machines and then use the command "crontab -r" to remove all the jobs (provided no other jobs are needed there) on one machine. this is dirty, but very easy.
any better ideas?
I know that the shell module in Ansible supports "run_once", but the cron module does not.
Wrong. run_once is a property of a task, not of action modules.
Use cron module and set run_once for the task (mind the indentation level), for example:
- cron:
name: "check dirs"
minute: "0"
hour: "5,2"
job: "ls -alh > /dev/null"
run_once: true

How can I disable security checks for Jenkins pipeline builds

I'm running Jenkins in a local trusted environment where I'm trying to run this pipeline. This Jenkinsfile is checked into git.
#!groovy
node('master') {
def ver = pomVersion()
echo "Building version $ver"
}
def pomVersion(){
def pomtext = readFile('pom.xml')
def pomx = new XmlParser().parseText(pomtext)
pomx.version.text()
}
The first few times I ran the build, I needed to manually approve changes (Jenkins->Mange Jenkins-> In-process Script Approval). Now I get this Exception and there is nothing to approve. All I want to do is parse an XML file. Can these security checks be bypassed completely for pipeline builds?
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field groovy.util.Node version
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:367)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:363)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:23)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:17)
at WorkflowScript.pomVersion(WorkflowScript:10)
at WorkflowScript.run(WorkflowScript:3)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:62)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:54)
at sun.reflect.GeneratedMethodAccessor479.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:32)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:29)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:29)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:276)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:78)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:185)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:183)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Finished: FAILURE
Currently it is not possible. There is an open ticket for this problem https://issues.jenkins-ci.org/browse/JENKINS-28178
You can solve the problem by following steps:
install Permissive Script Security plugin (version 0.3 or newer)
If you are using a pipeline script, make sure Use Groovy Sandbox is checked. This can be done in the configuration of the job.
add permissive-script-security.enabled command line parameter to Jenkins master with value:
true if you want to disable the need to approve scripts, but potentially dangerous signatures will be logged:
-Dpermissive-script-security.enabled=true
no_security if you want to disable the need to approve scripts and disable also logging of the potentially dangerous signatures:
-Dpermissive-script-security.enabled=no_security
Try the following jenkins plugin: https://wiki.jenkins-ci.org/display/JENKINS/Permissive+Script+Security+Plugin
It disables the sandbox. Works for me.
As answered above: in the newer Jenkins versions Script Security has been tightened. However for the specific use case of reading a version from Maven's pom.xml one could use readMavenPom from the Pipeline Utility Steps Plugin:
pom = readMavenPom file: 'pom.xml'
pom.version
With some other solutions in this StackOverflow question as well.
I'd like to offer up a hack that I ended up implementing after scouring the interwebs for a solution and trying some of the solutions proposed here.
A little background on my setup:
Jenkins master (no slaves)
Dockerized Jenkins instance with a persistent volume for the jenkins_home directory
Jenkins jobs are delivered via the Jenkins Job DSL plugin with jobs written in .groovy
My scenario:
Anytime someone modified an existing Jenkins pipeline (via groovy) and introduced new functionality that used some custom groovy, Jenkins would fail the job and flag the code snippet for approval. Approval was manual and tedious.
I have tried the solutions posted above and they did not work for me. So my hack was to create a Jenkins job that runs a shell job that takes the list of signatures that need approved and then adds them to the /var/jenkins_home/scriptApproval.xml file.
Some gotchas:
The offending job still has to fail once for me to find/copy the offending code/signature
To get the change to take effect, you cant "reload from disk" for the file to get picked up. You have to restart the Jenkins process (in our case delete the container and bring it back up). This was not a big pain for me since Jenkins is restarted every morning.
In our world, we trust the devs who modify our Jenkins jobs so they are free to add signatures that need approval as needed. Plus the job is in source control so we can see who added what.
My Jenkins container also has xmlstarlet baked in so my shell job uses that for the updating of the file
Example of my Jenkins job's shell command:
#!/bin/bash
echo ""
#default location of the Jenkins approval file
APPROVE_FILE=/var/jenkins_home/scriptApproval.xml
#creating an array of the signatures that need approved
SIGS=(
'method hudson.model.ItemGroup getItem java.lang.String'
'staticMethod jenkins.model.Jenkins getInstance'
)
#stepping through the array
for i in "${SIGS[#]}"; do
echo "Adding :"
echo "$i"
echo "to $APPROVE_FILE"
echo ""
#checking the xml file to see if it has already been added, then deleting. this is a trick to keep xmlstarlet from creatine duplicates
xmlstarlet -q ed --inplace -d "/scriptApproval/approvedSignatures/string[text()=\"$i\"]" $APPROVE_FILE
#adding the entry
xmlstarlet -q ed --inplace -s /scriptApproval/approvedSignatures -t elem -n string -v "$i" $APPROVE_FILE
echo ""
done
echo "##### Completed updating "$APPROVE_FILE", displaying file: #####"
cat "$APPROVE_FILE"

What are the success exit codes from tSQLt

I am trying to integrate tSQLt / SQLTest with CruiseControl.NET
My tests are running and I've written xsl files to display the results but I need to know how to mark the build as failed if any tests fail.
My CCNet exec is:
<exec executable="$(sqlCmdPath)">
<description>Run Unit Tests</description>
<buildArgs>-E -d MyDatabase
-i "\CruiseControlProjects\Configuration\CI_SQL\RunTests.sql"
</buildArgs>
<baseDirectory>\Artifacts\MyDatabase</baseDirectory>
<successExitCodes>0,63</successExitCodes>
</exec>
RunTests.sql:
IF EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[tSQLt].[RunAll]')
AND TYPE IN (N'P',N'PC'))
BEGIN
EXECUTE [tSQLt].[RunAll]
END
The tests are run and I have a subsequent task which produces the results in xml that are then merged into the build log:
<exec executable="$(sqlCmdPath)">
<description>Get Unit Tests</description>
<buildArgs>-E -b -d MyDatabase -h-1 -y0 -I
-i "\CruiseControlProjects\Configuration\CI_SQL\GetTestResults.sql"
-o "\CruiseControlProjects\Configuration\CI_SQL\Results\TestResults.xml"
</buildArgs>
<baseDirectory>\Artifacts\MDatabase</baseDirectory>
<successExitCodes>0,63</successExitCodes>
</exec>
So how do I get the overall build to fail?
If you use the -b parameter to sqlcmd, you should find that it will throw an error with a non-zero code when the batch fails (which will happen if tSQLt fails at least one test).
However, I have one potential suggestion to explore. If you can load the XML file within Cruise Control, then the tests can be loaded in as the XML file is in the same format as an nUnit test output file. (Note - I've used this method on TeamCity and Jenkins, but not tried with Cruise Control). This will treat the tests as tests rather than an 'all-or-nothing' approach, and enabling you to track which tests fail repeatedly.
Hope that helps,
Dave.

Cruisecontrol task with can execute even if Soursecontrol is not accessible

I have deployed CruiseControl.Net (Version 1.6.7981.1) server and it does the following tasks:
Build trigger
Labeller
VSTS Soursecontrol block (Get the soursecode from TFS 2010 server)
Build the code in Debug mode
Run NUnit test using Nanat task
Merge NUnit-Result.xml (Publisher task)
As I need to clear NUnit-Result.xml file every time before running the NUnit task, I have added a delete task in Nant.build file which deletes NUnit-results.xml before NUnit task run.
Now my problem is when my build get triggers and if my TFS server is not accessible, build get failed and only publisher task runs so Old Nunit result file merge in the failed build.
I Tried running "Prebuild" task but it works only if TFS server is accessible.
Now What I want is a task to delete Nunit-result.xml which can run even if my TFS is not accessible (either before soursecontrol block or within/after publisher block)
Thanks in advance
You can add an exec task to delete the file in the publisers setion just before the file merge
Like this:
<publishers>
<xmllogger />
<statistics />
<buildpublisher>
<sourceDir>$(buildDir)\_PublishedWebsites\$(projectName)</sourceDir>
<publishDir>$(webDir)</publishDir>
<useLabelSubDirectory>false</useLabelSubDirectory>
<alwaysPublish>false</alwaysPublish>
</buildpublisher>
<exec>
<executable>$(workingDir)\deleteNunitResultxml.cmd</executable>
</exec>
...
</publishers>
Have a publisher at the end which moves the nunit result file or deletes it. Then it won't be there for the next build.
Another option is to create a task to run before the nunit task runs, which deletes the nunit-result.xml file.
E.g. execute
cmd /c "del NUnit-Result.xml"

TortoiseProc CruiseControl.NET: Unable to execute file problem

I am new to CruiseControl and automated build. My problem is that the ccnet service always promt me "unable to execute file TortoiseProc.exe /command ...". My config file looks like this
TortoiseProc.exe /command:update /path:C:\Work\global.ad.lib.objectmanagement /closeonend:1
This command(tortoiseProc....) works well in a CMD window. The Ccnet service is execute with an Admin account. "C:\Program Files\TortoiseSVN\bin" is in the environnement variables and can be executed from anywhere. If i force a build from the Dashboard, it builds perfectly. I have the feeling this is just a simple stupid thing...
Tks
You will need to specify TortoiseProc.exe parameters separately from the executable name, inside "buildArgs" element. Here is the right ccnet.config fragment for your situation:
<exec>
<description>Execute TortoiseProc.exe</description>
<baseDirectory>c:\path\to\tortoiseproc\folder</baseDirectory>
<executable>TortoiseProc.exe</executable>
<buildArgs>/command:update /path:C:\Work\global.ad.lib.objectmanagement /closeonend:1</buildArgs>
</exec>
Also you can create cmd-file with your commands and use exec without parameters, if that would be easier for you.

Resources