A Tutorial to Dev a Jenkins Plugin for a Distributed Jenkins

Ebay开源基于大数据的可视化框架:Pulsar Reporting ebay又新添了一个开源项目Pulsar Reporting – 基于大数据的可视化框架. 阅读详情

Author:  Yu, Qingguo

Background

Jenkins is an open source continuous integration tool written in Java, known as CI server. Plugins extend Jenkins use, which provides all kind of functionalities such as downloading code from version control system, building code with different kinds of tools like Maven, Ant, reporting testing results, and so on.

Jenkins has two working mode: one is only one instance, on which all jobs run on ; the other is that there may be one master node and several slave nodes in one Jenkins system, named distributed Jenkins, and the jobs may run on either master node or slave nodes. When a Jenkins plugin being developed, one potential issue is that the plugin can only run on Jenkins master node even the job is configured running on slave nodes. For beginners on Jenkins plugin development, it is very easy to fall into such trap. If your Jenkins system will be migrated to Apache Mesos platform, nearly all of the CI jobs will be run on slave node. That would be an issue if Jenkins plugin cannot handle that.

During developing a plugin to collect code coverage of integration testing, we also faced that issue. The plain code to download and build source cannot work well when CI jobs are configured running on slave nodes. In addition, there is no handy complete example available on the internet which can be referenced directly. It took us quite a long time to do the research and eventually overcome such issue. Here a complete example will be provided on developing a Jenkins plugin working well in a distributed Jenkins.

Overview

This blog will demonstrate how to build a Jenkins working in distributed Jenkins from scratch, and will focus on details how to leverage interfaces of Jenkins to access remote workspace. Also, please note the methods we introduce in this blog will make plugin work on both master node and slave node, not only on slave node, which is transparent to the user without any more code change, depending on which node where the CI job is configured to run.

There are four sections in this blog:

     1. Go through the basic steps to create a Jenkins plugin and set up development environment;

     2. Introduce two ways to leverage Jenkins’ interface to make your Jenkins plugin run on slave nodes;

     3. Introduce how to leverage the functionalities of existing plugins in your plugin to handle remote execution cases;

     4. A short introduction on what the theory is to support plugin work in a distributed Jenkins.

Create a sample Jenkins plugin

     1. First of all, you need to install JDK, Maven into your development server and configure related environment variable such as JDK_HOME, MAVEN_HOME, and so on.

     2. If you already have a seetings.xml file for you maven, please add two more repositories of Jenkins into this setting.xml, one in release repositories, the other in plugin repositories. Or you may create settings.xml as shown in reference [3]

                                     <repository>

                                       <id>repo.jenkins-ci.org</id>

                                       <url>http://repo.jenkins-ci.org/public/</url>

                                     </repository>

                                     <pluginRepository>

                                       <id>repo.jenkins-ci.org</id>

                                       <url>http://repo.jenkins-ci.org/public/</url>

                                     </pluginRepository>

     3. Create folder for your Jenkins plugin project. Here I use name “pluginsample” for the folder;

     4. Create the plugin using Jenkins Maven archetype by run the command under the folder in a command line console. Or you may create a maven command in Eclipse to do the same thing as shown below. Here we use “com.ebay.learn.jenkins.plugins” as groupId, “sample” as artifactId. After the maven command finishes, a project named “sample” created under the folder “pluginsample”

       

Figure 1

      5. Import the project into Eclipse. Or you may import the project into IntelliJ or Netbeans as you like. When you import project, please import the project through “Import Maven Projects” to make eclipse create the project metadata

     6. After importing is done, build and run this plugin in a Jenkins by run maven command:

     

     7. Enter the url like http://localhost:9090/jenkins/ and open the main page of Jenkins;

     8. Add a CI job named “TestSample” and add the build step of the new plugin we just created, which is named “Say hello world”. And enter “Jenkins” in the name field.

     9. Click “build now” to trigger the build of this CI job. The build finishes successfully, and from console you may check out the words like “hello, Jenkins”.

     Next, we will add code to make this plugin access workspace on the remote slave node.

Method 1: leverage launcher to make logic run on slave

     1. Open class “HelloWorldBuilder” in the sample project;

     2. Add static class implementing interface Callable

     //The 1st method

    private static class LauncherCallable implements Callable<String, IOException>{

    private BuildListener listener;

    public LauncherCallable(BuildListener listener){

        this.listener = listener;

    }

      private static final long serialVersionUID = 1L;

        public String call() throws IOException {

        final RemoteOutputStream ros = newRemoteOutputStream(listener.getLogger());

            // This code will run on the slave node

            String hostname = InetAddress.getLocalHost().getHostName();

            hostname = hostname + "\n";

            ros.write(hostname.getBytes());

             return hostname;

         }

     };

 

     3. Add following code to method “perform”:

     // Get a "channel" to the build machine and run the task there

      try {

      //The 1st method

       String hostname = launcher.getChannel().call(new LauncherCallable(listener));

    } catch (Exception e) {

       RuntimeException re = new RuntimeException();

       re.initCause(e);

       throw re;

    }

     4. Build and run the plugin on a local Jenkins using the same command as above when creating Jenkins plugin ;

     5. Kick off the CI job “TestSample” we created just now. You will find the hostname of current server will be got successfully and printed into the console of the log of the CI job.

    6. Compile and build a hpi file of this plugin;

    

    7. Install it onto a distributed Jenkins. Please refer to reference[5] on how to configure a distributed Jenkins.

    a. Open link of advance tab of plugin manager. ${master} refer to the master node in your distributed Jenkins. http://${master}/pluginManager/advanced

    b. In “Upload Plugin” section, click “Browser” button to locate hpi file built just now. The hpi file is always located under target folder like “pluginsample\sample\target\sample.hpi”.

    c. Click “Upload” button to install this hpi file to Jenkins.

    d. Restart Jenkins by invoking link http://${master}/restart

    8. Create a CI “TestSample” and restrict it running on Slave node. Check “Restrict where this project can be run” and enter the name of slave node

     

     9. Kick off this CI job. After job execution is finished, the hostname of slave node instead of master node will be found in the console log.

Method 2: leverage FilePath to make logic run on slave

     1. Open class “HelloWorldBuilder” in the sample project;

     2. Add static class implementing interface Callable

     //The 2nd method

    private static class MyFileCallable implements FileCallable<String> {

    private BuildListener listener;

    public MyFileCallable(BuildListener listener){

        this.listener = listener;

    }

      private static final long serialVersionUID = 1L;

        public String invoke(File file, VirtualChannel channel) throws IOException {

            final RemoteOutputStream ros = newRemoteOutputStream(listener.getLogger());

           // This code will run on the build slave

           String hostname = InetAddress.getLocalHost().getHostName();

           hostname = hostname + "\n";

           ros.write(hostname.getBytes());

            return hostname;

        }

    }; 

      3. Add following code to method “perform”:

      FileCallable<String> fTask = new MyFileCallable(listener);

      // Get a "channel" to the build machine and run the task there

      try {

       build.getWorkspace().act(fTask);

    } catch (Exception e) {

       RuntimeException re = new RuntimeException();

       re.initCause(e);

       throw re;

    } 

     4. Build and run the plugin on a local Jenkins using the same command as above when creating Jenkins plugin ;

     5. Kick off the CI job “TestSample” we created just now. You will find the hostname will be got successfully and printed into the console of the log of the CI job.

     6. Compile and build a hpi file of this plugin;

     7. Install it onto a distributed Jenkins as I did in “Method 1” and restart CI server.

     8. Kick off CI job “TestSample” on your distributed Jenkins.

     9. After job execution is finished, two of the hostnames of slave node instead of master node will be found in the console log, one is printed by Method1, the other is printed by Method 2.

How to do the logging when plugin runs on slave

The key point for logging remote operation is creating a serializable output stream. Fortunately Jenkins already provides one output stream class named RemoteOutputStream to support that. The common practice is wrapping up current logger with RemoteOutputStream like:

    final RemoteOutputStream ros = newRemoteOutputStream(listener.getLogger());

    Then print any log as you want like:

    ros.write(hostname.getBytes());

Leverage existing Jenkins plugins

When we need to download code, build code in our own plugin, it is naturally to think about to leverage some existing library like JGit, invoking maven in a ProcessBuilder per our existing experience on Java coding. However, the mechanisms mentioned cannot handle the scenario when your plugin runs in a distributed Jenkins.

For example, if you use JGit library to download the code in your plugin, when you make the CI job run on slave node, you will find that the source code is still downloaded to the master. If you want to download code to the workspace on the slave node, one possible way is to leverage the methods introduced above, and put code of Jgit invocation into them. Actually another simpler way is to leverage the existing Git Client Jenkins plugin in your project, which has already supported to download code to the remote workspace if you need. Here are the steps how to integrate Git Client Jenkins plugin into your plugin:

     1. Add dependency of Git Client to the pom.xml of your plugin project. Generally, you need to use latest version of the dependency.

<dependency>

          <groupId>org.jenkins-ci.plugins</groupId>

          <artifactId>Git Client</artifactId>

          <version>1.10.0</version>

      </dependency>

     2. Add code into the method to download the code;

     //code demo for git clone

       try {

           GitClient git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars))

                  .in(build.getWorkspace()).getClient();

           git.clone("https://github.scm.corp.ebay.com/RaptorCOE/WebResTest2.git",

                  "origin", false, null);

       } catch (GitException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       } catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       } catch (InterruptedException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

     3. Build and run the plugin on a local Jenkins;

     4. Kick off the CI job “TestSample” we created just now. You will find the code will be downloaded successfully into the workspace.

     5. Install Git Client plugin to your master node of CI server. Or the sample plugin’s installation will fail due to dependency missing.

     6. Compile and build a hpi file of this plugin, and install it onto a distributed Jenkins as mentioned above.

     7. Kick off this CI job “TestSample”. After job execution is finished, check the workspace folder on slave node. It will be found that the code is downloaded successfully.

The Theory behind the Scene

Jenkins uses a mechanism similar to distributed agents to perform distributed computing. That is, the thread that's running on the master can send serialized objects to remote machines, then get the result back when that the object finishes computation. The key point is the object serialization and deserialization when sending objects to remote slave nodes and getting the result back. If you want to do further reading please read reference [4].

Summary

In this blog, a complete example is provided about how to develop a Jenkins plugin to work in a distributed Jenkins. Please check out the complete source code from this link of git repo: https://github.com/qingguo-yu/jenkinspluginsample

Also you may check out many code examples on this topic on reference [6]

References

1. The official web site for Jenkins: http://jenkins-ci.org/

2. The description about Jenkins on Wikipedia:http://en.wikipedia.org/wiki/Jenkins_%28software%29

3. https://wiki.jenkins-ci.org/display/JENKINS/Plugin+tutorial

4. https://wiki.jenkins-ci.org/display/JENKINS/Making+your+plugin+behave+in+distributed+Jenkins

5. https://wiki.jenkins-ci.org/display/JENKINS/Step+by+step+guide+to+set+up+master+and+slave+machines

6. http://www.programcreek.com/java-api-examples/index.php?api=hudson.remoting.Callable

7. http://stackoverflow.com/questions/17727054/cannot-access-file-on-jenkins-slave

 

* 本文版权和/或知识产权归eBay Inc所有。如需引述,请和联系我们DL-eBay-CCOE-Tech@ebay.com。本文旨在进行学术探讨交流,如您认为某些信息侵犯您的合法权益,请联系我们DL-eBay-CCOE-Tech@ebay.com,并在通知中列明国家法律法规要求的必要信息,我们在收到您的通知后将根据国家法律法规尽快采取措施。

MapReduce的详细过程 MapReduce作为hadoop的编程框架,是工程师最常接触的部分,也是除去了网络环境和集群配 置之外对整个Job执行效率影响很大的部分,所以很有必要深入了解整个过程。本文写作的目的在于使得读者对整个MapReduce过程有比较细致的了解,当自己需要定制MapReduce行为时,知道该重写 哪些类和方法。在写作时,我贴了部分认为重要的源码和接口,并跟着自己的理解,对于某些内容,结 合了自己在工作中遇到的问题,给出了实践参考。 阅读详情

相关推荐

MapOutputBuffer理解的三重境界

MapOutputBuffer作为MapTask的内部类,是MR中二次排序非常重要的一环。本文从基本认识,到 详细过程,再到源码级别,由浅入深的介绍了这个类。

ebay的专栏 3140

Jenkins修改workspace和build目录

Jenkins: Change Workspaces and Build Directory Locations  转自: http://ingorichter.blogspot.jp/2012/02/jenkins-change-workspaces-and-build.html   Have you ever wanted to change the location o...

weixin_33895657的博客 3892

如何定制一个基于REST Service的ODBC驱动程序

Author:  Ma, Hongbin 概要 REST Service能够帮助开发者以简单统一的接口向终端用户提供服务。然而数据分析的应用场景中,一些成熟的数据分析工具(例如Tableau, Excel等)要求用户提供ODBC数据源,在这种情况下,REST Service并不能满足用户所有对数据的使用需求。本文从实现的角度详细介绍了如何在现有REST Service的基础上,

ebay的专栏 970

Maven依赖版本冲突报告

Author:  Wang, Yunfeng. 简介 依赖版本冲突是一个一直以来困扰Build系统的问题,众所周知,依赖版本冲突会带来很多运行时的问题,如果能够在开发和编译阶段就识别出这些问题,将会大大提高开发人员的工作效率,并且提高产品的稳定性。 本文将着重分析一下Maven依赖版本冲突的问题,然后介绍一下目前的常见的检测和报告工具。然后提出一个依赖版本冲突报告的增强。

ebay的专栏 2290

【信息科学与工程学】【数据中心】第三十五篇 云计算数据中心的学科知识04

编号学科(课程)核心知识点在云计算/云存储/云网络/云安全/云MaaS中的作用代表教材/资料/论文 + 数学方程式列表工业界应用D1421​云原生数据库:TiDB​HTAP(混合事务/分析处理)、分布式SQL、水平扩展、强一致(Raft)、自动故障恢复、与MySQL兼容、TiFlash列式引擎提供弹性扩展的分布式数据库;支撑高并发在线交易与实时分析教材:《TiDB in Action》PingCAP(2020) 论文:《TiDB: A Raft-based HTAP Database》(2017)

weixin_49199313的博客 530

智慧市政灯联网解决方案.pptx

智慧市政灯联网解决方案.pptx

JavaScript 异步原理

本文从一些基本软件设计常识和平时编程中不太注意的点中,带你看清JavaScript 中关于线程、回调、异步等的概念。

ebay的专栏 2081

【负荷频率和电压控制】电力系统的组合负荷频率和电压控制模型研究(Simulink)

内容概要:本文针对电力系统中频率与电压耦合控制的关键问题,研究了组合负荷频率控制(LFC)与自动电压调节(AVR)的协同建模方法,基于Simulink搭建动态仿真系统,构建了能够反映负载突变、发电侧扰动等实际工况的多变量控制系统模型。通过集成经典控制理论与现代仿真技术,设计协调控制器以同时稳定系统频率和关键母线电压,有效抑制因功率不平衡引发的动态波动,提升电力系统的整体稳定性与电能质量。文中详述了系统建模流程、控制策略设计原理及仿真验证过程,为复杂电力系统的多目标协同控制提供了理论依据与实践参考。; 适合人群:电力系统自动化、电气工程及其相关专业的高校研究生、科研机构研究人员以及从事电网运行、控制策略开发的工程技术从业人员。; 使用场景及目标:①用于深入理解负荷频率控制与电压调节之间的动态耦合机制及其交互影响;②为含高比例新能源接入的现代电力系统提供频率-电压协同控制的仿真验证平台;③支撑PID、模糊逻辑、最优控制等先进控制算法在多输入多输出(MIMO)电力系统稳定控制中的研究与应用。; 阅读建议:建议结合提供的Simulink模型文件进行同步操作学习,重点掌握控制器结构设计与参数整定方法,关注系统在不同扰动工况下的动态响应特性,并可进一步拓展研究新能源出力不确定性、负荷随机性对控制性能的影响。

JSON Compression

Author:  Ma, Guolai Story JSON data comprises a large majority of content sent around the internet, especially for social networking sites and HTML5 games. One day, someone wants to search somet

ebay的专栏 1708

华为ENSP完整安装教程

华为ENSP完整安装教程

Hnm456756的博客 7379

Windows本地化部署Dify完整指南

本文详细介绍了在Windows系统上本地化部署Dify的完整步骤,涵盖了Docker Desktop的安装与配置、Dify源代码的获取、环境变量的设置、服务的启动与管理、以及常见问题的解决方案。文章首先指导用户如何下载和安装Docker Desktop,并配置WSL 2功能。接着,详细说明了如何获取Dify源代码,并通过Docker Compose启动服务。文章还提供了高级配置指南,包括如何配置大语言模型和更新Dify版本。最后,针对Docker镜像拉取失败等常见问题,提供了详细的诊断和解决方案。通过本文,

jacky_zhuyuanlu的博客 1万+

Kepler性能分析之M2E调优

Author:Cai Eric   简介     在使用Eclipse Kepler v4.3.2(WTP v3.5.2, M2E v1.4.1)开发基于Maven的Java Web项目时,将工程导入到workspace速度非常之慢,而且保存修改的文件也会引发长时间的编译,严重影响了开发人员的工作效率。     通过分析日志,调试,辅以性能分析工具VisualVM,

ebay的专栏 1633

UsualToolCMS-验证码绕过漏洞复现

本文以UsualToolCMS为靶场,复现了验证码绕过漏洞

小小小屿屿屿的博客 927

Ansible Best Practices

In order to manager thousands of servers , we need a deployment tool to do all kinds of things. The most used tools are puppet, saltstack , ansible . Puppet and saltstack both have agent , but ansible donot have agent which is the advantage , because you d

ebay的专栏 1590

Altium Designer 16安装教程(Windows11、小白教程)

Altium Designer 16在Windows11中的超详细安装教程

qq_47003770的博客 1万+

八、ILI2511 初版调试

8.1 TP成品过程 TP厂在制造TP过程中会经过FPC、FOG和Model三个阶段。 FPC: 将IC做在FPC上面; FOG: 将FPC与sensor 绑定; Model:FOG阶段后,贴上CG(cover glass)。 经过上面三个阶段后,将会拿到没有烧录固件的TP模组。这个时候触摸TP,并不能上报触摸数据,需要对TP模组烧录固件(执行程序)后才会有TP有触摸数据。 8.2 源码编译固件与工具生成固件 我们可以通过以下两种方式获得固件 1)由奕力原厂直接通过源码,进行编...

qq_34343637的博客 3695

React同构漫谈

同构指的是相同代码可以同时在客户端与服务端同时渲染的技术,利用服务器资源对用户请求进行预渲染,而客户端仍然保持SPA特性。本文将从实际项目出发,谈谈开发过程中遇到的问题以及解决方案。

ebay的专栏 1356

YOLOv8【第十章:多任务扩展深度篇·第19节】YOLOv8 与 DeepLabV3+ 对比——实时性与精度的权衡!

🏆 本文收录于 《YOLOv8实战:从入门到深度优化》 专栏。该专栏系统复现并梳理全网各类 YOLOv8 改进与实战案例(当前已覆盖分类 / 检测 / 分割 / 追踪 / 关键点 / OBB 检测等方向),坚持持续更新 + 深度解析,质量分长期稳定在 97 分以上,可视为当前市面上 覆盖较全、更新较快、实战导向极强 的 YOLO 改进系列内容之一。

**My Coding Family** 1万+

eBay User feedback clustering in R

Author:  Zhao, Kevin Abstract Learning eBay user’s feedback is fairly important to improve our site service. However, Catching useful information from tons of user feedbacks is really not an eas

ebay的专栏 1345

【论文复现】——基于LM优化的NDT点云配准算法

传统的正态分布变换配准算法处理初始位姿变换相差较大的两帧点云时,存在无法收敛或者陷入局部最小值的问题。为了提高算法的收敛性能,提出了一种基于LM方法改进的三维正态分布变换配准算法。

点云侠的博客 1171

Qt Installer Framework 简单使用

qt installer framework 简单使用

qq_42815643的博客 2579

Ebay开源:Eclipse Plugin Repository Portal

Eclipse Plugin Repository Portal是eBay开源的关于eclipse插件管理的软件。其集中化的管理方式,可视化的操作界面简化了插件管理的流程,减少了人为因素引起的错误,使得插件开发和版本发布的效率得到极大提升,间接保证了软件开发的质量。

ebay的专栏 1286

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Maven中的扁平化POM

Author:  Jia, Weigang. Maven中的POM大致有两个目的: 开发人员用POM编译和发布构件被其他项目用于依赖管理 对于第一个目的,POM中的关于编译和发布的元素都是有意义的。对于第二个目的,POM中的关于编译和发布的元素就没有意义了。比如,一个项目A依赖于构件B,项目A仅仅需要知道构件B的GroupId、ArtifactId、Version以及构件B的依赖

ebay的专栏 1276

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

从dedup说起之JS数组去重

在JavaScript中,数组去重是一个基本的操作,方法众多:遍历去重到Set、Map去重、hashTable、Lodash Uniq,数组中是否存在对象、函数,每个去重方法的表现各有差异,本文将以此作为切入点深入源码进行分析。

ebay的专栏 1219

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

Maven Build Tracking

Author:  Mao, Maode. 从这个项目的名字我们不难发现,Maven Build Tracking (以下简称MBT) 这个项目是用来跟踪/监控Maven 的构建(Build)。但我们不仅仅记录项目的成功/失败, 同时需要衡量构建时长, 构建的环境, 甚至收集应用级别的信息。利用这些信息我们就可以全局的审查我们构建系统的性能以及可靠性。   在我们详细讨论MBT之前

ebay的专栏 987
上一篇: Seamless migration from Nova-network to Neutron in eBay production
下一篇: DBA的新领域:调试Oracle(进阶篇)
ebay
博客等级 码龄24年 109粉丝 69原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值