找回密码
 立即注册
首页 业界区 业界 Jenkins-Pipline实现原理

Jenkins-Pipline实现原理

扔飒 前天 20:08
Jenkins-Pipline原理

本文仅探讨jenkins pipline 的原理,是流水线的一个demo版本实现,不能代表Jenkins pipline的具体实现,仅供参考。
1. Jenkins流水线介绍

Jenkinsfile流水线是Jenkins CI/CD工具中用来定义、构建和管理软件交付流程的一种声明式文件。
它允许将整个软件交付流程以代码的形式进行描述,从而实现对软件交付过程的可追踪性、可维护性和可扩展性。
Jenkinsfile使用一种基于Groovy的DSL(领域特定语言)来定义流水线,开发人员可以通过编写Groovy代码来描述流水线的结构和逻辑。
简而言之:Jenkinsfile 就是 Groovy脚本。
2. Groovy实现DSL的基础

Groovy是一种基于JVM的动态语言,它可以直接使用Java类和库,也可以通过闭包和元编程等特性来实现DSL。
2.1 方法调用

在Groovy中,通常情况下需要使用括号来调用带有参数的方法。但是,在一些特定的情况下,也可以省略括号来调用方法,并将参数作为闭包的一部分传递。
  1. def greet(String name) {
  2.     println("Hello, $name!")
  3. }
  4. // 使用括号调用方法
  5. greet("Alice")  // 输出: Hello, Alice!
  6. // 省略括号,将参数作为闭包的一部分传递
  7. greet "Bob"    // 输出: Hello, Bob!
复制代码
2.2 闭包

闭包可以被视为一个可调用的代码块,它可以作为参数传递给方法、赋值给变量,以及作为返回值返回。

  • 定义闭包:可以使用{}大括号来定义一个闭包,并在其中编写代码块。例如:
  1. def closure = { param ->
  2.     println("Hello, $param!")
  3. }
复制代码

  • 参数传递:闭包可以接受零个或多个参数,并在代码块中使用这些参数。例如:
  1. def printSum = { a, b ->
  2.     println(a + b)
  3. }
复制代码

  • 调用闭包:可以通过将闭包像函数一样进行调用来执行其中的代码块。例如:
  1. closure("Alice")  // 输出: Hello, Alice!
  2. printSum(3, 5)   // 输出: 8
复制代码

  • 作为参数传递:闭包可以作为参数传递给其他方法,使得方法具有更高的灵活性和可重用性。例如:
  1. def processData(data, closure) {
  2. // 执行某些逻辑...
  3.     closure(data)
  4. }
  5. processData("Hello", { input ->
  6.     println("Received: $input")
  7. })
复制代码
2.3 闭包代理

Groovy还提供了闭包代理(Closure Delegate)机制。闭包代理允许在闭包中访问外部对象的成员变量和方法,而无需显式地使用点操作符。
以下是一个示例:
  1. class Person {
  2.     String name
  3.     void sayHello() {
  4.         println("Hello, I'm $name")
  5.     }
  6. }
  7. def person = new Person(name: "Alice")
  8. def closure = { sayHello() }  // 使用闭包代理调用Person对象的sayHello方法
  9. closure.delegate = person
  10. closure()  // 输出: Hello, I'm Alice
复制代码
在上面的例子中,我们定义了一个名为closure的闭包,其中调用了外部的Person对象的sayHello()方法。
通过将闭包的delegate属性设置为person对象,我们实现了在闭包中调用person.sayHello()的效果。
3. 从零实现DSL&Jenkinsfile

3.1 使用DSL编写流水线

实现的流水线如下:
jenkinsfile.groovy
  1. import static Dsl.pipeline
  2. pipeline {
  3.     agent any
  4.     environment {
  5.         SOME_NUMBER = 123
  6.         SOME_STRING = "foobar"
  7.     }
  8.     stages {
  9.         stage("Build") {
  10.             steps { env ->
  11.                 sh "ls -la"
  12.                 sh(script: 'date +%Y-%m-%d', returnStdout: false)
  13.                 echo "Groovy rocks!"
  14.                 echo "env.SOME_STRING = ${env.SOME_STRING}"
  15.             }
  16.         }
  17.         stage("Test") {
  18.             steps {
  19.                 sh """
  20.                     echo "Testing..."
  21.                     """
  22.             }
  23.         }
  24.     }
  25. }
复制代码
3.2 DSL的具体实现

DSL实现代码如下:
Dsl.groovy
  1. import groovy.transform.NamedParam
  2. import groovy.transform.NamedParams
  3. import groovy.transform.stc.ClosureParams
  4. import groovy.transform.stc.SimpleType
  5. import java.util.concurrent.ConcurrentHashMap
  6. import java.util.concurrent.ConcurrentMap
  7. import static groovy.lang.Closure.DELEGATE_FIRST
  8. import static groovy.lang.Closure.DELEGATE_ONLY
  9. class Dsl {
  10.     static void pipeline(@DelegatesTo(value = PipelineDsl, strategy = DELEGATE_ONLY) final Closure closure) {
  11.         final PipelineDsl dsl = new PipelineDsl()
  12.         closure.delegate = dsl
  13.         closure.resolveStrategy = DELEGATE_ONLY
  14.         closure.call()
  15.     }
  16. }
  17. class PipelineDsl {
  18.     // 定义一个占位符常量
  19.     final Placeholder any = Placeholder.ANY
  20.     // 使用 ConcurrentHashMap 创建环境变量的并发映射
  21.     static final ConcurrentMap<String, String> env = [:] as ConcurrentHashMap
  22.     // 定义 agent 方法
  23.     void agent(final Placeholder any) {
  24.         println "Running pipeline using any available agent..."
  25.     }
  26.     // 定义 environment 方法
  27.     void environment(@DelegatesTo(value = Map, strategy = DELEGATE_FIRST) final Closure closure) {
  28.         // 将闭包委托给 env 并执行闭包
  29.         env.with(closure)
  30.     }
  31.     // 定义 stages 方法
  32.     void stages(@DelegatesTo(value = StagesDsl, strategy = DELEGATE_ONLY) final Closure closure) {
  33.         final StagesDsl dsl = new StagesDsl()
  34.         closure.delegate = dsl
  35.         closure.resolveStrategy = DELEGATE_ONLY
  36.         closure.call()
  37.         // 遍历 stages 列表并依次运行每个 stage
  38.         dsl.stages.each { stage ->
  39.             stage.run()
  40.         }
  41.     }
  42.     // 定义占位符枚举类
  43.     enum Placeholder {
  44.         ANY
  45.     }
  46. }
  47. class StagesDsl {
  48.     // 定义 stages 列表
  49.     protected final List<Stage> stages = []
  50.     // 定义 stage 方法
  51.     void stage(final String name, @DelegatesTo(value = StageDsl, strategy = DELEGATE_ONLY) final Closure closure) {
  52.         // 将 stage 添加到 stages 列表中
  53.         stages << new Stage(name, closure)
  54.     }
  55. }
  56. class Stage {
  57.     final String name
  58.     final Closure closure
  59.     // 定义 Stage 类的构造函数
  60.     Stage(String name, Closure closure) {
  61.         this.name = name
  62.         this.closure = closure
  63.     }
  64.     // 运行 stage 的方法
  65.     void run() {
  66.         println "==> Running '${name}' stage..."
  67.         final StageDsl dsl = new StageDsl()
  68.         closure.delegate = dsl
  69.         closure.resolveStrategy = DELEGATE_ONLY
  70.         closure.call()
  71.     }
  72. }
  73. class StageDsl {
  74.     // 定义 steps 方法
  75.     void steps(
  76.             @DelegatesTo(value = Steps, strategy = DELEGATE_ONLY)
  77.             @ClosureParams(value = SimpleType, options = ["java.util.Map"]) final Closure closure) {
  78.         final Steps steps = new Steps()
  79.         closure.delegate = steps
  80.         closure.resolveStrategy = DELEGATE_ONLY
  81.         closure.call(PipelineDsl.env)
  82.     }
  83. }
  84. class Steps {
  85.     // 定义 sh 方法
  86.     void sh(final String script) {
  87.             sh(script: script, returnStdout: false)
  88.     }
  89.     // 定义重载的 sh 方法
  90.     Object sh(@NamedParams([
  91.             @NamedParam(value = "script", type = String, required = true),
  92.             @NamedParam(value = "returnStdout", type = Boolean)
  93.     ]) final Map param) {
  94.         // 执行 shell 脚本,并等待执行完成
  95.         final Process p = param.script.toString().execute()
  96.         p.waitFor()
  97.         println "+ ${param.script}"
  98.         if (p.exitValue() == 0) {
  99.             if (param.returnStdout) {
  100.                 return p.text
  101.             }
  102.             println p.text
  103.         } else {
  104.             println p.err.text
  105.         }
  106.     }
  107.     // 定义 echo 方法
  108.     void echo(final String message) {
  109.         println "[ECHO] ${message}"
  110.     }
  111. }
复制代码
3.4 流水线调用流程分析
  1. $ groovy jenkinsfile.groovy
  2. Running pipeline using any available agent...
  3. ==> Running 'Build' stage...
  4. + ls -la
  5. razem 32
  6. drwxrwxr-x   5 wololock wololock 4096 04-07 18:20 .
  7. drwxrwxr-x. 45 wololock wololock 4096 04-04 12:47 ..
  8. drwxrwxr-x   3 wololock wololock 4096 04-04 12:48 com
  9. drwxrwxr-x   7 wololock wololock 4096 04-07 18:20 .git
  10. -rw-rw-r--   1 wololock wololock   29 04-07 18:19 .gitignore
  11. drwxrwxr-x   2 wololock wololock 4096 04-07 18:19 .idea
  12. -rw-rw-r--   1 wololock wololock 1016 04-04 13:23 jenkinsfile.groovy
  13. -rw-rw-r--   1 wololock wololock   23 04-07 18:20 README.md
  14. + date +%Y-%m-%d
  15. 2020-04-07
  16. [ECHO] Groovy rocks!
  17. [ECHO] env.SOME_STRING = foobar
  18. ==> Running 'Test' stage...
  19. + mvn -version
  20. Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
  21. Maven home: /home/wololock/.sdkman/candidates/maven/current
  22. Java version: 1.8.0_232, vendor: Oracle Corporation, runtime: /home/wololock/.sdkman/candidates/java/8.0.232-open/jre
  23. Default locale: pl_PL, platform encoding: UTF-8
  24. OS name: "linux", version: "5.5.10-100.fc30.x86_64", arch: "amd64", family: "unix"
复制代码
The end.
参考资料:

Groovy DSL Quickstart:
https://github.com/wololock/groovy-dsl-quickstart

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册