Book Image

Jenkins Continuous Integration Cookbook - Second Edition

By :
Book Image

Jenkins Continuous Integration Cookbook - Second Edition

By:

Overview of this book

<p>Jenkins is an award-wining and one of the most popular Continuous Integration servers in the market today. It was designed to maintain, secure, communicate, test, build, and improve the software development process.</p> <p>This book starts by examining the most common maintenance tasks. This is followed by steps that enable you to enhance the overall security of Jenkins. You will then explore the relationship between Jenkins builds and Maven pom.xml. Then, you will learn how to use plugins to display code metrics and fail builds to improve quality, followed by how to run performance and functional tests against a web application and web services. Finally, you will see what the available plugins are, concluding with best practices to improve quality.</p> <p>&nbsp;</p> <div class="book-toc-chapter">&nbsp;</div> <h2>Read an Extract from the book</h2> <h2><span lang="EN-GB" style="color: windowtext;">Analyzing project data with the R plugin</span></h2> <p class="NormalPACKT">This recipe describes how to use R to process metrics on each file in your project workspace. The recipe does this by traversing the workspace and collecting a list of files of a particular extension such as Java. The R script then analyzes each file individually and finally plots the results in a graphical format to a PDF file. The workflow is common to almost all quality-related analysis of software projects. This recipe is easily customized for tasks that are more complex.</p> <p class="NormalPACKT" style="margin-bottom: .0001pt;"><span style="letter-spacing: -.1pt;">In this example, we are looking at the size in words of the text files, printing to the console the names of large files and plotting the sizes of all files. From the visual representation, you can easily see which files are particularly large. If your property file is much larger than the other property files, it is probably corrupt. If a Java file is too large, it is difficult to read and understand.</span></p> <h2><span lang="EN-GB" style="color: windowtext;">How to do it...</span></h2> <ol> <li>Create a free-style job with the name <em>ch5.R.project.data</em>.</li> <li>In the <strong>Source Code Management </strong>section, select <strong>Subversion</strong>.</li> <li>Add the<strong> Repository URL</strong> as <a href="https://source.sakaiproject.org/svn/profile2/trunk">https://source.sakaiproject.org/svn/profile2/trunk</a>.</li> <li>In the <strong>build</strong> section, under <strong>Add build step</strong>, select <strong>Execute R script</strong>.</li> <li class="line-numbers">In the <strong>Script text</strong> area add the following code: <pre class="line-numbers"><code class="language-java">processFile &lt;- function(file){ text &lt;- readLines(file,encoding="UTF-8") if (length(text)&gt; 500) print(file) length(text) } javaFiles &lt;- list.files(Sys.getenv('WORKSPACE'), recursive = TRUE, full.names = TRUE, pattern = "\\.java$") propertiesFiles &lt;- list.files(Sys.getenv('WORKSPACE'), recursive = TRUE, full.names = TRUE, pattern = "\\.properties$") resultJava &lt;- sapply(javaFiles, processFile) resultProperties &lt;- sapply(propertiesFiles,processFile) warnings() filename &lt;-paste('Lengths_JAVA_',Sys.getenv('BUILD_NUMBER'),'.pdf',sep ="") pdf(file=filename) hist(resultJava,main="Frequency of length of JAVA files") filename &lt;- paste('Lengths_Properties_',Sys.getenv('BUILD_NUMBER'),'.pd f',sep="") pdf(file=filename) hist(resultProperties,main="Frequency of length of Property files")</code></pre> </li> <li>Click on the <strong>Save</strong> button.</li> <li>Click on the <strong>Build Now</strong> icon.</li> <li>Review the console output from the build. It should appear similar to the following: <pre class="line-numbers"><code class="language-java">At revision 313948 no change for https://source.sakaiproject.org/svn/profile2/trunk since the previous build [ch5.R.project.data] $ Rscript /tmp/hudson7641363251840585368.R [1] "/var/lib/jenkins/workspace/ch5.project.data/api/src/java/o rg/sakaiproject/profile2/logic/SakaiProxy.java" [1] "/var/lib/jenkins/workspace/ch5.project.data/impl/src/java/org/sakaiproject/profile2/conversion/ProfileConverter.java" [1] "/var/lib/jenkins/workspace/ch5.project.data/impl/src/java/ org/sakaiproject/profile2/dao/impl/ProfileDaoImpl.java" 14: In readLines(file, encoding = "UTF-8") : incomplete final line found on '/var/lib/jenkins/workspace/ch5.project.data/tool/src/java/ org/apache/wicket/markup/html/form/upload/MultiFileUploadFi eld_ca_ES.properties' Finished: SUCCESS</code></pre> </li> <li>Visit the workspace and review the files <em>Lengths_Properties_1.pdf</em>, <em>Lengths_JAVA_1.pdf</em>.</li> <li><span style="letter-spacing: -.1pt;">Notice the straggler files with a large number of lines. Property files should be of roughly similar length, as they contain, in this case, the international translations for the GUI.</span></li> </ol> <p class="NormalPACKT" style="margin-bottom: .0001pt;"><span lang="EN-GB">&nbsp;</span>This feels like a well-balanced project, as there are only a few files that have a large number of lines of code.</p> <h2><span lang="EN-GB" style="color: windowtext;">How it works...</span></h2> <p class="NormalPACKT">You loaded in the profile2 tool from subversion <a href="https://source.sakaiproject.org/svn/profile2/trunk">https://source.sakaiproject.org/svn/profile2/trunk</a>. This code is used by millions of students around the world and represents mature, realistic production code.</p> <p class="NormalPACKT">Within your R script, you defined a function that takes a filename as input and then reads the file into a text object. The function then checks to see whether the number of lines is greater than 500. If it is greater than 500 lines then the filename is printed to the console output. Finally, the function returns the number of lines in the text file.</p> <pre class="line-numbers"><code class="language-java">processFile &lt;- function(file){ text &lt;- readLines(file,encoding="UTF-8") if (length(text)&gt; 500) print(file) length(text) }</code></pre> <p class="NormalPACKT">Next, the script discovers the property and Java files under the workspace. The file search is filtered by the value defined in the <em>pattern</em> argument. In this case, <em>.java</em>:</p> <pre class="line-numbers"><code class="language-java">javaFiles &lt;- list.files(Sys.getenv('WORKSPACE'), recursive = TRUE, full.names = TRUE, pattern = "\\.java$") propertiesFiles &lt;- list.files(Sys.getenv('WORKSPACE'), recursive = TRUE, full.names = TRUE, pattern = "\\.properties$")</code></pre> <p class="NormalPACKT">The list of filenames is passed one name at a time to the <em>processFile</em> function you have previously defined. The results are a list of file lengths that are stored in the <em>resultJava </em>and <em>resultProperties</em> objects:</p> <pre class="line-numbers"><code class="language-java">resultJava &lt;- sapply(javaFiles, processFile) resultProperties &lt;- sapply(propertiesFiles,processFile)</code></pre> <p class="NormalPACKT">The <em>warnings()</em> function produces a list of issues generated while running the <em>sapply</em> command:</p> <pre class="line-numbers"><code class="language-java">14: In readLines(file, encoding = "UTF-8") : incomplete final line found on '/var/lib/jenkins/workspace/ch5.project.data/tool/src/java/org/apa che/wicket/markup/html/form/upload/MultiFileUploadField_ca_ES.prop erties'</code></pre> <p class="NormalPACKT">This is stating that a new line was expected at the end of the file. It is not a critical issue. Showing the warnings is a helpful approach to discovering corrupted files.</p> <p class="NormalPACKT">Finally, we generate two histograms of the results, one for the Java file and the other for the properties files. The filename is created from a constant string followed by the <em>BUILD_NUMBER</em> environment variable that is set uniquely for each build. The <em>pdf</em> function tells R that the output is to be stored in a PDF file and the <em>hist</em> function draws a histogram of the results:</p> <pre class="line-numbers"><code class="language-java">filename &lt;-paste('Lengths_JAVA_',Sys.getenv('BUILD_NUMBER'),'.pdf',sep="") pdf(file=filename) hist(resultJava,main="Frequency of length of JAVA files")</code></pre> <h2><span lang="EN-GB" style="color: windowtext;">There's more...</span></h2> <p class="NormalPACKT">When writing R code for processing your files, don't reinvent the wheel. R has many libraries for manipulating text. The stringi library is one example (<a href="http://cran.r-project.org/web/packages/stringi/stringi.pdf">http://cran.r-project.org/web/packages/stringi/stringi.pdf</a>). Here is some example code that counts the number of words in a text file:</p> <pre class="line-numbers"><code class="language-java">library(stringi) processFile &lt;-function(file){ stri_stats_latex(readLines(file,encoding="UTF-8")) } results&lt;-processFile(file.choose()) paste("Number of words in file:", results[4])</code></pre> <p class="NormalPACKT">The script defines the function <em>processFile</em>. The function requires a filename. The file is read into the <em>stri_stats_latex</em> function. This function is included in the <em>stringi</em> library. It returns a summary of the file as a vector (a series of numbers).</p> <p class="IgnorePACKT" style="margin: 0in 0in 6.0pt 0in;">The <em>file.choose()</em> function pops up a dialog that allows you to browse your file system and choose a file. The call returns the fully qualified path to the file. It passes the value to the <em>processFile</em> function call. The results are stored in the results vector. The script then prints out the fourth number that is the number of words in the file.</p> <blockquote> <p class="InformationBoxPACKT" style="margin: 9.0pt 0in 9.0pt 0in;"><em>Another interesting R package for text mining is tm: (<a href="http://cran.r-project.org/web/packages/tm/tm.pdf">http://cran.r-project.org/web/packages/tm/tm.pdf</a>). The tm package has the ability to load a set of text files and analyze them in many different ways.</em></p> </blockquote> <div class="book-toc-chapter">&nbsp;</div>
Table of Contents (16 chapters)
Jenkins Continuous Integration Cookbook Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Jenkins is a Java-based Continuous Integration (CI) server that supports the discovery of defects early in the software cycle. Thanks to a rapidly growing number of plugins (currently over 1,000), Jenkins communicates with many types of systems, building and triggering a wide variety of tests.

CI involves making small changes to software and then building and applying quality assurance processes. Defects do not only occur in the code, but also appear in naming conventions, documentation, how the software is designed, build scripts, the process of deploying the software to servers, and so on. CI forces the defects to emerge early, rather than waiting for software to be fully produced. If defects are caught in the later stages of the software development life cycle, the process will be more expensive. The cost of repair radically increases as soon as the bugs escape to production. Estimates suggest it is 100 to 1,000 times cheaper to capture defects early. Effective use of a CI server, such as Jenkins, could be the difference between enjoying a holiday and working unplanned hours to heroically save the day. And as you can imagine, in my day job as a senior developer with aspirations for quality assurance, I like long boring days, at least for mission-critical production environments.

Jenkins can automate the building of software regularly and trigger tests pulling in the results and failing based on defined criteria. Failing early via build failure lowers the costs, increases confidence in the software produced, and has the potential to morph subjective processes into an aggressive metrics-based process that the development team feels is unbiased.

Jenkins is not just a CI server, it is also a vibrant and highly active community. Enlightened self-interest dictates participation. There are a number of ways to do this:

What this book covers

Chapter 1, Maintaining Jenkins, describes common maintenance tasks such as backing up and monitoring. The recipes in this chapter outline methods for proper maintenance that in turn lowers the risk of failures.

Chapter 2, Enhancing Security, details how to secure Jenkins and the value of enabling single sign-on (SSO). This chapter covers many details, ranging from setting up basic security for Jenkins, deploying enterprise infrastructure such as a directory service, and a SSO solution to automatically test for the OWASP top 10 security.

Chapter 3, Building Software, reviews the relationship between Jenkins and Maven builds and a small amount of scripting with Groovy and Ant. The recipes include checking for license violations, controlling the creation of reports, running Groovy scripts, and plotting alternative metrics.

Chapter 4, Communicating Through Jenkins, reviews effective communication strategies for different target audiences from developers and project managers to the wider public. Jenkins is a talented communicator, with its hordes of plugins notifying you by e-mail, dashboards, and Google services. It shouts at you through mobile devices, radiates information as you walk pass big screens, and fires at you with USB sponge missile launchers.

Chapter 5, Using Metrics to Improve Quality, explores the use of source code metrics. To save money and improve quality, you need to remove defects in the software life cycle as early as possible. Jenkins test automation creates a safety net of measurements. The recipes in this chapter will help you build this safety net.

Chapter 6, Testing Remotely, details approaches to set up and run remote stress and functional tests. By the end of this chapter, you will have run performance and functional tests against a web application and web services. Two typical setup recipes are included. The first is the deployment of a WAR file through Jenkins to an application server. The second is the creation of multiple slave nodes, ready to move the hard work of testing away from the master node.

Chapter 7, Exploring Plugins, has two purposes. The first is to show a number of interesting plugins. The second is to review how plugins work.

Appendix, Processes that Improve Quality, discusses how the recipes in this book support quality processes and points to other relevant resources. This will help you form a coherent picture of how the recipes can support your quality processes.

What you need for this book

This book assumes you have a running an instance of Jenkins.

In order to run the recipes provided in the book, you need to have the following software:

Recommended:

Optional:

Helpful:

  • A local subversion or Git repository

  • OS of preference: Linux (Ubuntu)

    Note

    Note that from the Jenkins GUI (http://localhost:8080/configure), you can install different versions of Maven, Ant, and Java. You do not need to install these as part of the OS.

There are numerous ways to install Jenkins: as a Windows service, using the repository management features of Linux such as apt and yum, using Java Web Start, or running it directly from a WAR file. It is up to you to choose the approach that you feel is most comfortable. However, you can run Jenkins from a WAR file, using HTTPS from the command line, pointing to a custom directory. If any experiments go astray, then you can simply point to another directory and start fresh.

To use this approach, first set the JENKINS_HOME environment variable to the directory you wish Jenkins to run under. Next, run a command similar to the following command:

Java –jar jenkins.war –httpsPort=8443 –httpPort=-1

Jenkins will start to run over https on port 8443. The HTTP port is turned off by setting httpPort=-1 and the terminal will display logging information.

You can ask for help by executing the following command:

Java –jar jenkins.war –help

A wider range of installation instructions can be found at https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins.

For a more advanced recipe describing how to set up a virtual image under VirtualBox with Jenkins, you can use the Using a test Jenkins instance recipe in Chapter 1, Maintaining Jenkins.

Who this book is for

This book is for Java developers, software architects, technical project managers, build managers, and development or QA engineers. A basic understanding of the software development life cycle, some elementary web development knowledge, and a familiarity with basic application server concepts are expected. A basic understanding of Jenkins is also assumed.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows.

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The job-specific configuration is then stored in config.xml within the subdirectory."

A block of code is set as follows:

<?xml version='1.0' encoding='UTF-8'?>
<org.jvnet.hudson.plugins.thinbackup.ThinBackupPluginImpl plugin="[email protected]">
<fullBackupSchedule>1 0 * *  7</fullBackupSchedule>
<diffBackupSchedule>1 1 * * *</diffBackupSchedule>
<backupPath>/data/jenkins/backups</backupPath>
<nrMaxStoredFull>61</nrMaxStoredFull>
<excludedFilesRegex></excludedFilesRegex>
<waitForIdle>false</waitForIdle>
<forceQuietModeTimeout>120</forceQuietModeTimeout>
<cleanupDiff>true</cleanupDiff>
<moveOldBackupsToZipFile>true</moveOldBackupsToZipFile>
<backupBuildResults>true</backupBuildResults>
<backupBuildArchive>true</backupBuildArchive>
<backupUserContents>true</backupUserContents>
<backupNextBuildNumber>true</backupNextBuildNumber>
<backupBuildsToKeepOnly>true</backupBuildsToKeepOnly>
</org.jvnet.hudson.plugins.thinbackup.ThinBackupPluginImpl>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

server {
  listen   80;
  server_name  localhost;
  access_log  /var/log/nginx/jenkins _8080_proxypass_access.log;
  error_log  /var/log/nginx/jenkins_8080_proxypass_access.log;
  location / {
    proxy_pass      http://127.0.0.1:7070/;
    include         /etc/nginx/proxy.conf;
  }
}

Any command-line input or output is written as follows:

sudo apt-get install jenkins

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click on Save."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.