Wednesday, November 28, 2018

Jenkins 2: A Builder Plugin & Some Jelly

In the previous tutorial we did the basic setup for jenkins plugin development. Now we will try to create a plugin that actually runs a build step.

Jenkins Tutorials

For a list of all jenkins related tutorials see Jenkins Tutorials Overview.

Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online.

Step 1: The Basic Builder

Maven allows to create a nice template for a builder plugin by calling
mvn archetype:generate -Dfilter=io.jenkins.archetypes:
then select the hello-world-plugin. But as we want to do it the hard way, we will add every single bit on our own and continue with the empty project from our previous tutorial.

The first thing we need is a class to implement our builder. Lets create a simple one. Create a new class com.codeandme.jenkins.builder.HelloBuilder:
package com.codeandme.jenkins.builder;

import java.io.IOException;

public class HelloBuilder extends Builder implements SimpleBuildStep {

 @DataBoundConstructor
 public HelloBuilder() {
 }

 @Override
 public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener)
   throws InterruptedException, IOException {
  listener.getLogger().println("This is the Hello plugin!");
 }

 @Symbol("hello")
 @Extension
 public static final class Descriptor extends BuildStepDescriptor<Builder> {

  @Override
  public boolean isApplicable(Class<? extends AbstractProject> aClass) {
   return true;
  }

  @Override
  public String getDisplayName() {
   return "Code & Me - Hello World";
  }
 }
}

Jenkins expects the constructor to be augmented with the @DataBoundConstructor annotation. Later we will add our build parameters to it.

The perform() method is the heart of our implementation. This is where we define what the build step should actually do. In this tutorial we focus on the definition, not the execution so we are just printing some log message to detect that our build step got triggered.

Now lets put our focus on the Descriptor class. It actually describes what our plugin looks like, what parameter it uses and whether the user input is valid or not. You need to use a static class as a descriptor and augment it with the @Extension annotation to allow jenkins to detect it automatically.

isApplicable() might be the most important one as it denotes if ou plugin is usable for the current project type.

Start a jenkins test server using
mvn hpi:run -Djetty.port=8090
Create a new Freestyle Project and add your custom build step to it. Then execute the job and browse the log for our log message.

Build Considerations

When writing a plugin it is vital to understand which parts of the plugin do get executed on the master and which ones on a slave machine. The java code we just wrote does get executed on the master only. Even when a job is executed on a slave machine, the perform() method still gets executed on master. Therefore we cannot use classic java libraries like NIO or the ProcessBuilder to access and execute stuff on the slave. Instead we need to use abstractions like the workspace and the launcher parameters we get from Jenkins. These objects will take care to delegate IO calls or program executions to the slave.

Make sure you always keep focus which parts of your code get executed where.

Step 2: Basic UI

Next we need a *.jelly file to describe how the UI should look like. Therefore create a new package in src/main/resources named com.codeandme.jenkins.builder.HelloBuilder. That is right, the package equals the class name of our builder class. Then create a config.jelly file inside that package:

<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">

 <f:block>
  <h1>Code &amp; Me Productions</h1>
  <p>We build the best <i>hellos</i> in the world</p>
 </f:block>

</j:jelly>

Inside the jelly definition we can use plain HTML code. Run your test instance again to see your changes in your project configuration view.

Step 3: Checkbox Input

Time to add some input. All build parameters need at least 2 steps of implementation: first we need to define the UI in the config.jelly file, then we need to define the parameters in the java class. Optionally we may add additional checks in the Descriptor class.

To define the UI for the checkbox we add following code to our jelly file:
 <f:entry title="Fail this build" field="failBuild">
  <f:checkbox />
 </f:entry>
This will create a label using the title field and a checkbox on the right side of the label. The field name is important as this is the ID of our field which we now use in the Java code:
public class HelloBuilder extends Builder implements SimpleBuildStep {

 private boolean fFailBuild;

 @DataBoundConstructor
 public HelloBuilder(boolean failBuild) {
  fFailBuild = failBuild;
 }

 @Override
 public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener)
   throws InterruptedException, IOException {
  listener.getLogger().println("This is the Hello plugin!");

  if (isFailBuild())
   throw new AbortException("Build error forced by plugin settings");
 }

 public boolean isFailBuild() {
  return fFailBuild;
 }
}

The new parameter needs to be added to our constructor. Make sure you use the same name as in the jelly file. Additionally we need a getter for our parameter. It will be queried to populate the UI when you configure your job and when the job gets executed. Jenkins expects the name of the getter to match the field name of your jelly file.

During the build we evaluate our parameter and throw an AbortException in case our builder is expected to fail.

Step 4: Adding Help

Lots of parameters in Jenkins plugins show a help button on the righthand side of the form. These buttons automatically appear when corresponding help files exist in the right location.

A general help file for the builder named help.html needs to be placed next to the config.jelly file. You may add any arbitrary HTML content there, with no need to use <html> or <body> tags.

To provide help for our checkbox we create another help file named help-failBuild.html. See the pattern? We again use the field ID and Jenkins figures out the rest.

Instead of a plain HTML files we could also provide jelly files following the same name pattern.

Changes like adding help or beautifying jelly files can be done without restarting our test instance. Simply change the file and reload the page in your webbrowser of your test instance.

Further reading

Good documentation on writing forms seems to be rare on the internet. To me the best choice seems to find an existing plugin and browse the source code for reference. At least a list of all control types is available online.


2 comments: