Get custom grails plugin version from within the plugin - grails

I have a Grails plugin that I've written that has its version set using set-version within our continuous integration environment. While building, I'd like to programmatically output the version from within "eventCompileEnd" event hook. So, for my Grails app I can just get the "app.version" metadata but plugin versions are set in the GrailsPlugin.groovy file in the root of the plugin. Is there any way to access that value? Here's the version info I'm referring to:
class MyUtilityGrailsPlugin {
// the plugin version
def version = "4.6.8"
// the version or versions of Grails the plugin is designed for
def grailsVersion = "2.1 > *"
...etc.

You can use below eventCompileEnd event in _Events.groovy of the app to get the name and version of all the plugins used in the app from GantBinding which is by default available to the post compile event. You can filter your plugin info based on the name:
//scripts/_Events.groovy
eventCompileEnd = {msg->
msg.supportedPluginInfos.each{println "${it.name} - ${it.version}"}
}
If you want to access the plugin info from any where else (for example: BootStrap) using applicationContext would be the simplest approach. Something like below would be useful:
//Bootstrap.groovy
def grailsApplication
def init = { servletContext ->
grailsApplication.mainContext.getBean('pluginManager')
.allPlugins.each{plugin->
println "Plugin Info ${plugin.name} - ${plugin.version}"
}
}
In your case, appCtx will not be available in post compile event, so you have to depend on GantBinding.

I found that version information can be retrieved from within an event hook for that plugin by doing this:
pluginSettings.getPluginInfo(isPluginProject.getParent()).version;
pluginSettings is a bound variable in the current scope and isPluginProject actually returns a File object that represents the GrailsPlugin.groovy file.

Related

How to configure basic branch build strategies plugin using job dsl?

The multi branch pipeline plugin, awesome as it is, doesn't build tags out of the box. The usage of the basic-branch-build-strategies-plugin is required to enable tag discovery and building.
My question is directly related to: Is there a way to automatically build tags using the Multibranch Pipeline Jenkins plugin?
This plugin works great in the UI but doesn't appear to be easily configurable using the Jenkins job dsl. Does anyone have any examples of how to set the branch strategies using the dsl (or dsl configure->) so that tags will be discovered and built?
Having examined the delta between the config.xml files when the settings are changed via ui, it looks like I need to be able to add this trait:
<org.jenkinsci.plugins.github__branch__source.TagDiscoveryTrait />
and this section under build strategies:
<buildStrategies
<jenkins.branch.buildstrategies.basic.TagBuildStrategyImpl
plugin="basic-branch-build-strategies#1.1.1">
<atLeastMillis>-1</atLeastMillis>
<atMostMillis>172800000</atMostMillis>
</jenkins.branch.buildstrategies.basic.TagBuildStrategyImpl>
</buildStrategies>
Something like
multibranchPipelineJob('pipline') {
...
branchSources {
branchSource {
source {
github {
...
traits {
...
gitTagDiscovery()
}
}
buildStrategies {
buildTags {
atLeastDays '-1'
atMostDays '20'
}
}
}
}
}
}
is what I've been working with. It's not documented in the plugin, but that doesn't stop the job-dsl plugin from dynamically generating the API calls for it.
You can see what the API for your specific Jenkins installation is by going to {your_jenkins_url}/plugin/job-dsl/api-viewer/index.html.
Sometimes things won't appear there because a plugins lacks support for job-dsl.
In that case you can still generate the xml with the Configure Block.
However, this is pretty clumsy to use.
Edit: At least if I use gitHubTagDiscovery() as suggested by the dynamically generated API, Jenkins will crash. Instead, the configure block has to be used to get all the discovery methods for github.
configure {
def traits = it / sources / data / 'jenkins.branch.BranchSource' / source / traits
traits << 'org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait' {
strategyId(1)
}
traits << 'org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait' {
strategyId(1)
}
traits << 'org.jenkinsci.plugins.github__branch__source.TagDiscoveryTrait'()
}

grails 3 - Update grails config during Plugin "doWithApplicationContext"

I've got a plugin that, during startup, reads some properties from the applications Config file, creates some domain objects and then needs to update the configuration with some additional information. However, it seems that the config object available during doWithApplicationContext is not the actual grailsApplication.config object.
For instance, attempting to do something straightforward in the MyPluginGrailsPlugin.groovy file like:
void doWithApplicationContext() {
grailsApplication.config.put('test', 'testValue')
}
does not update the config.
If this plugin is incldued in an application, at any point after startup, grailsApplication.config.getProperty('test') will return null.
How does one go about updating the config map during plugin startup?
NOTE: In grails 2, this used to work.
With this code snippet in MyPluginGrailsPlugin.groovy's doWithApplicationContext, new properties were successfully added into the application's config object.
ConfigObject myConfigObject = new ConfigSlurper().parse(props)
PropertySource propertySource = new MapPropertySource('grails.plugins.myPlugin', [:] << myConfigObject)
def propertySources = grailsApplication.mainContext.environment.propertySources
propertySources.addFirst propertySource
As an additional note: in doWithApplicationContext in my plugin, changing the config object like this worked in Grails 2 and no longer works in Grails 3.
grailsApplication.config.merge(myConfigObject)
grailsApplication.configChanged()

Jenkins: read an existing job's plugin config via Groovy

We are in the early phases of using Jenkins DSL. One challenge we have come across is being able to read in an existing jobs plugin settings so that we retain it before running the DSL. This allows us the ability to give the Jenkins users the option to keep some of their settings. We have successfully retained the schedule settings for our jobs but the newest challenge is being able to retain a plugin setting. Specifically a setting in the "ExtendedEmailPublisher" plugin. We would like to retain the value:
In the config.xml file for this job in the ExtendedEmailPublisher tags we see the following:
<publishers>
<hudson.plugins.emailext.ExtendedEmailPublisher>
<recipientList>Our_Team#Our_Team.com</recipientList>
<configuredTriggers>
<hudson.plugins.emailext.plugins.trigger.FailureTrigger>
<email>
<recipientList/>
<subject>$PROJECT_DEFAULT_SUBJECT</subject>
<body>$PROJECT_DEFAULT_CONTENT</body>
<recipientProviders>
<hudson.plugins.emailext.plugins.recipients.ListRecipientProvider/>
</recipientProviders>
<attachmentsPattern/>
<attachBuildLog>false</attachBuildLog>
<compressBuildLog>false</compressBuildLog>
<replyTo>$PROJECT_DEFAULT_REPLYTO</replyTo>
<contentType>project</contentType>
</email>
</hudson.plugins.emailext.plugins.trigger.FailureTrigger>
</configuredTriggers>
<contentType>default</contentType>
<defaultSubject>$DEFAULT_SUBJECT</defaultSubject>
<defaultContent>$DEFAULT_CONTENT</defaultContent>
<attachmentsPattern/>
<presendScript>$DEFAULT_PRESEND_SCRIPT</presendScript>
<classpath/>
<attachBuildLog>false</attachBuildLog>
<compressBuildLog>false</compressBuildLog>
<replyTo>$DEFAULT_REPLYTO</replyTo>
<saveOutput>false</saveOutput>
<disabled>false</disabled>
</hudson.plugins.emailext.ExtendedEmailPublisher>
</publishers>
The value we would like to extract/preserve from this XML is:
<disabled>false</disabled>
We have tried getting the existing values using groovy but cant seem to find the right code. Our first idea was to try to read the value from the config.xml using the XmlSlurper. We ran this from the Jenkins Script Console:
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/api/xml".execute().text);
*we use 8100 for our Jenkins port
Unfortunately while this does return some config info it does not return plugin info.
Then, we also tried running the following to read/replace the existing settings:
def oldJob = hudson.model.Hudson.instance.getItem("Job_Name")
def isDisabled = false // Default Value
for(publisher in oldJob.publishersList) {
if (publisher instanceof hudson.plugins.emailext.ExtendedEmailPublisher) {
isDisabled = publisher.disabled
}
}
And while this works if executed from the Jenkins Script Console, when we try to use it in a DSL Job we get the message:
Processing provided DSL script
ERROR: startup failed:
script: 25: unable to resolve class
hudson.plugins.emailext.ExtendedEmailPublisher
# line 25, column 37.
if (publisher instanceof hudson.plugins.emailext.ExtendedEmailPublisher)
{
1 error
Finished: FAILURE
SOLUTION UPDATE:
Using url #aflat's URL suggestion for getting the raw XML config info, I was able to use the XML Slurper and then use the getProperty method to assign the property I wanted to a variable.
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/config.xml".execute().text);
def emailDisabled = projectXml.publishers."hudson.plugins.emailext.ExtendedEmailPublisher".getProperty("disabled");
If you want to parse the config.xml, use
def projectXml = new XmlSlurper().parseText("curl http://Server_Name:8100/job/Job_Name/config.xml");
That should return your raw config.xml data
Under "Manage Jenkins->Configure Global Security" did you try disabling "Enable script security for Job DSL scripts"?

Unable to resolve class AsyncHttpBuilder

Using Grails 1.3.9
buildConfig.groovy
compile "org.grails.plugins:async-http-builder"
code:
AsyncHttpBuilder client = new AsyncHttpBuilder()
Promise<HttpClientResponse> p = client.post("http://someuUrl") {
contentType 'application/json'
json {
receiver number
message content
sender sender
}
}
p.onComplete { HttpClientResponse resp ->
println(resp);
}
I get the error in the topic title. What am I missing here?
A rather general steps for checking problems with missing plugins
Check if you have mavenRepo "https://repo.grails.org/grails/plugins" in repositories { in BuildConfig.groovy
Provide plugin version, so instead of "org.grails.plugins:async-http-builder" try "org.grails.plugins:async-http-builder:1.0.0"
Try grails refresh-dependencies in the terminal
Looking at the commit dates, it looks like a fresh plugin (<1 year old), so it's possible it works only with newer Grails versions (2+/3+).
The documentation states
Note that this client does not require Grails itself, and can easily be used standalone or as an independent HTTP client.
(...)
To get started with the HTTP client you should declare a dependency on the grails-http-client project in your build.gradle file:
compile "org.grails:http-client:VERSION"
So I would probably just try that, as the plugin might not play well with your old Grails version.

How to configure the Grails embedded Tomcat to use the file based security realm

I need to create a user/password for the embedded Tomcat, since my app uses JAAS. I found some examples, but they refer to older versions of Grails. I am using 2.3.5.
The link above advises to create users via events, in a Grails script:
eventConfigureTomcat = {tomcat ->
println "Loading users"
tomcat.addUser("user", "password")
tomcat.addRole("user", "group")
}
But when I create a Grails script in the scripts folder, it is pre-populated with this:
includeTargets << grailsScript("_GrailsInit")
target(_Events: "The description of the script goes here!") {
// TODO: Implement script here
}
setDefaultTarget(_Events)
How to add the user in the new version of Grails? Thanks!
You have to add the event in the file scripts/_Events.groovy. If it's not there, just create it. If it's there, just append your event to the existing content.
Make sure to execute stop-app and run-app so that the event is processed. When executing run-app, you should see the output of your println-statement.

Resources