Klocwork Jenkins CI plugin

The Klocwork Plugin for Jenkins provides an easy way for you to automate industry-leading static code analysis as part of your Continuous Integration or Continuous Deployment environments.

Restriction: As of 2023.1, this plugin is not compatible with versions of Klocwork 2022.1 or older.

To support the DevOps and Continuous Delivery (CD) movement requiring speed from a static analysis tool, our plugin provides added functionality such as a “Diff” mechanism (based on your version control system), where we only analyze files that were changed in the last change set. You can also use it to generate periodic full analysis runs. The plugin supports Git out of the box, and supports all other SCMs with minimal setup. The plugin enables Klocwork to utilize the client tools to perform a differential analysis.

Prerequisites
  • Minimum Jenkins core version: 1.614
  • The Jenkins server must be running on the Java 1.8 JRE
  • You must install or deploy the Klocwork CI tools and build tools to your build machine (we recommend you use the same installation directory for both of these packages.)
  • A kwciagent license is required to use differential analysis; a Reprise (RLM) license is required.

Installing the Klocwork CI plugin

  1. Access your Jenkins server and click Manage Jenkins > Manage Plugins.
  2. Click the Available tab and type ‘Klocwork’ in the filter box. The search result ‘Klocwork Plug-in’ should appear. Alternatively, you can download the Klocwork Jenkins CI plugin package from the Klocwork Support Portal.
  3. Select the check box and click Download now and install after restart. After Jenkins restarts, you should see the plugin under the Installed tab.

Setting up the plugin

  1. Click Manage Jenkins in the sidebar, then select Configure System.
  2. In the Klocwork section, for each Klocwork Server you want to define, enter the server URL and give it a name. Leave the license server settings empty, as the Klocwork tools get the license server location from the Portal automatically.
  3. Optional: Click the Advanced button at the bottom to specify PATHs to a <server_install>/bin/ directory. This allows you to have access to the Klocwork CI tools and build tools which are needed when creating a Jenkins job later.

    If your Klocwork bin directory is set in your PATH, this is not required.

  4. Click Save.

Connecting to your source code management system

If you want to import your source code in Jenkins using your preferred SCM, you need to specify where Jenkins can find your repository:
  1. Under Configure, select Source Code Management.
  2. Select the option for Git or Subversion.
  3. Enter the URL for your repository and any necessary credentials.
  4. Optional: You can also specify a particular branch you want your CI build to pull from.

Configure the build environment

You need to configure the environment so that the plugin can connect to it to retrieve values (e.g. Klocwork Server URL, project name, license settings), as follows:

  1. Under Build Environment, select the Klocwork – Build Environment Settings checkbox.
  2. From the Klocwork Server Configuration drop down menu, select the name of the Klocwork Server you configured previously.
  3. Enter the name of the Klocwork project you want to analyze. The name must match a project name on the specified Klocwork Server.
  4. If your PATH does not have the Klocwork bin directory specified, click the drop down menu for Klocwork Install Configuration and select the name representing the path to the Klocwork Server installation directory configured previously.
    This step is completed automatically if you previously set the Klocwork bin in your PATH.
  5. Optional: If the path to the ltoken is not the default location, input the path to the ltoken. Otherwise, the plugin cannot authenticate to the Klocwork Server.

    Important: The ltoken file will only be in the .Klocwork directory if kwauth is run. For the Jenkins job to find it in its .Klocwork directory, kwauth must have been run using the same account as is running Jenkins.

Running a full analysis to create a baseline

From the Jenkins Build tab, click the Add build step button and add the following build steps:

  1. Step 1 (CI/Full) - Capture Build Information: Runs a Klocwork build specification generation tool to capture compilation information about the project. You need to ensure that your project build command is specified, along with your Klocwork build specification generation tool.
    You can specify a working directory from where the Build Spec Generation Command is executed. This can be useful if a workspace has multiple projects and you want to capture the build specification for a particular project existing within your workspace.
  2. Step 2 (Full) - Run Analysis: kwbuildproject is run on the build to perform a full integration analysis. You can specify the location of your Klocwork build specification (this is mandatory if you specified the build spec output location in step 1 above) and the location of your tables directory within this step.
  3. Step 3 (Full) - Load Analysis Results: Loads the results of the full integration analysis to the database on the Klocwork Server. Provide the location of your tables directory. You can also enable the option Display Klocwork Trend Chart; The Klocwork Trend Chart generates a trend chart of your CI builds that can help you track the health of your project.
    When viewing the Klocwork Trend Chart, all severity labels are displayed including those without any defects specified in the trend chart query.
  4. Post Analysis (Full) - Cross-Project Issue Sync (Optional): Synchronizes issues across different projects based on the Project Filter (which determines which projects should be processed during synchronization) and the Last Synchronization Date.
  5. Post Analysis (Full/CI) - Build Failure Conditions (Optional): Set up any preferred build failure conditions; The post-build action enables the plugin to mark builds as failed, unstable, or passed based on certain thresholds.

    Tip: Select Report Results to add a link in Jenkins for the Klocwork Dashboard. This dashboard allows you to see the integration analysis issues for your project.

  6. Save the job.
  7. Verify the relevant project exists on the Klocwork Server.
  8. Click Build Now.
Running a Differential Analysis

Important: To perform an Incremental Diff Analysis you must have the kwciagent tool installed and an available kwciagent license. If you do not have a proper license, contact your Account Manager or Klocwork Customer Support.

From the Jenkins Build tab, click the Add build step button and add the following build steps:

  1. Step 1 (CI/Full) - Capture Build Information: Runs a Klocwork build specification generation tool to capture compilation information about the project.
  2. Klocwork - Step 2 (CI) - Run Differential Analysis: kwciagent is run on your CI build to analyze any recently changed code.
    For your first CI build, if the Analyze Changed Files Only option is selected, you will get a 'Git commit variable <your git message> is not set' warning and the full CI build will run. For each subsequent build, this option generates a file (called 'diff_file_list' by default) which contains the names of all files that are changed compared to the previous commit.
  3. Post Analysis (Full/CI) - Build Failure Conditions (Optional): Set up any preferred build failure conditions; The post-build action enables the plugin to mark a build as failed by default or unstable (if the Fail as unstable option is selected). You can also select the 'Check Changed Files Only' option which specifies that the build only checks files in the specified diff file. By default, the diff_file_list.txt file is used, but you can specify an alternate file in the 'Diff File List' field if you prefer.

    Tip: Select Report Results to add a link in Jenkins for the Klocwork Analysis Results. This option allows you to see full trace for issues for each of your builds by clicking a particular build in Jenkins.

  4. Save the job.
  5. Verify the relevant project exists on the Klocwork Server.

    No data is uploaded to the Server but the project's configuration information is used to run the analysis.

  6. Click Build Now.

Citing an issue (CI)

If you set any build failure conditions with Report Results selected, the list of issues is found by selecting Klocwork Analysis Results from the sidebar in Jenkins. For each issue, click the Edit button to cite it and add a status.

To cite an issue, you need to be authenticated with the Klocwork Server. The first time you click on Edit, you are prompted to enter your user credentials for the Klocwork Portal. Authentication is preserved until you close the browser, or if you log out manually.

Example: setup with zlib (Freestyle project)

Let's test our Jenkins configuration by running an analysis on 'zlib', a small open source compression library.
  1. Download the Git plugin for Jenkins: Search for ‘Git plugin’ on the Manage Plugins page, install it and restart Jenkins.
  2. Create the project in Jenkins. Click New Item on the left sidebar, and select Freestyle project. Give your job a name and click OK.
    The plugin also supports Pipeline jobs.
  3. Scroll down to Source Code Management and select Git.
  4. For Repository URL, enter https://github.com/madler/zlib
  5. For Branches to build, enter */master
  6. Click Build Environment, select Klocwork - Build Environment Settings, and add the appropriate settings for your system.
  7. Under Build, click Add build step and add the following steps:
    • If on Linux: Execute shell, or
    • If on Windows: Execute Windows batch command
    • Step 1 (CI/Full) - Capture Build Information: kwinject is used by default. You also need to specify your build command, such as 'make'.
    • Step 2 (Full) - Run Analysis
    • Step 3 (Full) - Load Analysis Results
  8. Add the command to the Execute shell:./configure (this configures the make file for zlib.)
  9. Click Save.
  10. Run kwadmin create-project –-url http://<kw server host>:<port number>/zlib to create the project.
  11. Run the job by clicking Build Now. Wait for the job to finish running. To monitor your job’s progress hover your mouse over the build number and click the small arrow that appears, then click Console Output.
  12. After the Jenkins job is finished, you can log in to the Klocwork Portal to view the analysis results.

Example: Setting up a pipeline job

Pipeline jobs are configured using a Jenkins file. To generate specific steps, you can use a Snippet Generator tool which has predefined script blocks for different Klocwork steps:
  1. Create a new pipeline job and select Pipeline Syntax from the project in Jenkins.
  2. Choose your step (such as 'Capture build information') and click Generate Pipeline Script.
  3. Repeat step two for every step you want to include in your pipeline job. Every step should be included in the final Jenkins file. For example:
    pipeline {
       agent any
        
       environment {
            KLOCWORK_URL = "http://localhost:8080"
            KLOCWORK_PROJECT = "zlib-pipeline"
            KLOCWORK_LICENSE_HOST = "repriselm-server"
            KLOCWORK_LICENSE_PORT = "27000"
            KLOCWORK_LTOKEN = ""       
        }
        
       stages {
           stage('Get src from git') {
                 steps {
                    git 'https://github.com/madler/zlib.git'
                 }
            }
             
            stage('Klocwork Build') {
                 steps {
                      
                        klocworkBuildSpecGeneration([additionalOpts: '', buildCommand: 'c:\\dev\\zlib-git.bat', ignoreErrors: true, output: 'kwinject.out', tool: 'kwinject'])
                     
                 }
            }
               
            stage('Klocwork Analysis') {
                steps {             
                         klocworkIntegrationStep1([additionalOpts: '', buildSpec: 'kwinject.out', disableKwdeploy: true, duplicateFrom: '', enabledCreateProject: true, ignoreCompileErrors: true, importConfig: '', incrementalAnalysis:       false, tablesDir: 'kwtables'])
                                     
                 }
              }
               
              stage('Klocwork Db-load') {
                 steps {                
                         klocworkIntegrationStep2 reportConfig: [displayChart: true, query: 'status:Analyze'], serverConfig: [additionalOpts: '', buildName: '', tablesDir: 'kwtables']             
                 }
              }
               
              stage('Build Failure Conditions') {
                 steps {                
                         klocworkFailureCondition([enableCiFailureCondition: true, failureConditionCiConfigs: [[withDiffList: true, diffFileList: 'my_list.txt', enableHTMLReporting: true, name: 'one', reportFile: '', threshold: '1',]]])
                      
                 }
              }            
       }           
    }
  4. Add the script text and click save to finalize the pipeline job.
  5. After running the pipeline build, you should see a view representing all stages included in the job.