Jenkins-Pipline实现原理
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中,通常情况下需要使用括号来调用带有参数的方法。但是,在一些特定的情况下,也可以省略括号来调用方法,并将参数作为闭包的一部分传递。
def greet(String name) {
println("Hello, $name!")
}
// 使用括号调用方法
greet("Alice")// 输出: Hello, Alice!
// 省略括号,将参数作为闭包的一部分传递
greet "Bob" // 输出: Hello, Bob!2.2 闭包
闭包可以被视为一个可调用的代码块,它可以作为参数传递给方法、赋值给变量,以及作为返回值返回。
[*]定义闭包:可以使用{}大括号来定义一个闭包,并在其中编写代码块。例如:
def closure = { param ->
println("Hello, $param!")
}
[*]参数传递:闭包可以接受零个或多个参数,并在代码块中使用这些参数。例如:
def printSum = { a, b ->
println(a + b)
}
[*]调用闭包:可以通过将闭包像函数一样进行调用来执行其中的代码块。例如:
closure("Alice")// 输出: Hello, Alice!
printSum(3, 5) // 输出: 8
[*]作为参数传递:闭包可以作为参数传递给其他方法,使得方法具有更高的灵活性和可重用性。例如:
def processData(data, closure) {
// 执行某些逻辑...
closure(data)
}
processData("Hello", { input ->
println("Received: $input")
})2.3 闭包代理
Groovy还提供了闭包代理(Closure Delegate)机制。闭包代理允许在闭包中访问外部对象的成员变量和方法,而无需显式地使用点操作符。
以下是一个示例:
class Person {
String name
void sayHello() {
println("Hello, I'm $name")
}
}
def person = new Person(name: "Alice")
def closure = { sayHello() }// 使用闭包代理调用Person对象的sayHello方法
closure.delegate = person
closure()// 输出: Hello, I'm Alice在上面的例子中,我们定义了一个名为closure的闭包,其中调用了外部的Person对象的sayHello()方法。
通过将闭包的delegate属性设置为person对象,我们实现了在闭包中调用person.sayHello()的效果。
3. 从零实现DSL&Jenkinsfile
3.1 使用DSL编写流水线
实现的流水线如下:
jenkinsfile.groovy
import static Dsl.pipeline
pipeline {
agent any
environment {
SOME_NUMBER = 123
SOME_STRING = "foobar"
}
stages {
stage("Build") {
steps { env ->
sh "ls -la"
sh(script: 'date +%Y-%m-%d', returnStdout: false)
echo "Groovy rocks!"
echo "env.SOME_STRING = ${env.SOME_STRING}"
}
}
stage("Test") {
steps {
sh """
echo "Testing..."
"""
}
}
}
}3.2 DSL的具体实现
DSL实现代码如下:
Dsl.groovy
import groovy.transform.NamedParam
import groovy.transform.NamedParams
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.SimpleType
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import static groovy.lang.Closure.DELEGATE_FIRST
import static groovy.lang.Closure.DELEGATE_ONLY
class Dsl {
static void pipeline(@DelegatesTo(value = PipelineDsl, strategy = DELEGATE_ONLY) final Closure closure) {
final PipelineDsl dsl = new PipelineDsl()
closure.delegate = dsl
closure.resolveStrategy = DELEGATE_ONLY
closure.call()
}
}
class PipelineDsl {
// 定义一个占位符常量
final Placeholder any = Placeholder.ANY
// 使用 ConcurrentHashMap 创建环境变量的并发映射
static final ConcurrentMap<String, String> env = [:] as ConcurrentHashMap
// 定义 agent 方法
void agent(final Placeholder any) {
println "Running pipeline using any available agent..."
}
// 定义 environment 方法
void environment(@DelegatesTo(value = Map, strategy = DELEGATE_FIRST) final Closure closure) {
// 将闭包委托给 env 并执行闭包
env.with(closure)
}
// 定义 stages 方法
void stages(@DelegatesTo(value = StagesDsl, strategy = DELEGATE_ONLY) final Closure closure) {
final StagesDsl dsl = new StagesDsl()
closure.delegate = dsl
closure.resolveStrategy = DELEGATE_ONLY
closure.call()
// 遍历 stages 列表并依次运行每个 stage
dsl.stages.each { stage ->
stage.run()
}
}
// 定义占位符枚举类
enum Placeholder {
ANY
}
}
class StagesDsl {
// 定义 stages 列表
protected final List<Stage> stages = []
// 定义 stage 方法
void stage(final String name, @DelegatesTo(value = StageDsl, strategy = DELEGATE_ONLY) final Closure closure) {
// 将 stage 添加到 stages 列表中
stages << new Stage(name, closure)
}
}
class Stage {
final String name
final Closure closure
// 定义 Stage 类的构造函数
Stage(String name, Closure closure) {
this.name = name
this.closure = closure
}
// 运行 stage 的方法
void run() {
println "==> Running '${name}' stage..."
final StageDsl dsl = new StageDsl()
closure.delegate = dsl
closure.resolveStrategy = DELEGATE_ONLY
closure.call()
}
}
class StageDsl {
// 定义 steps 方法
void steps(
@DelegatesTo(value = Steps, strategy = DELEGATE_ONLY)
@ClosureParams(value = SimpleType, options = ["java.util.Map"]) final Closure closure) {
final Steps steps = new Steps()
closure.delegate = steps
closure.resolveStrategy = DELEGATE_ONLY
closure.call(PipelineDsl.env)
}
}
class Steps {
// 定义 sh 方法
void sh(final String script) {
sh(script: script, returnStdout: false)
}
// 定义重载的 sh 方法
Object sh(@NamedParams([
@NamedParam(value = "script", type = String, required = true),
@NamedParam(value = "returnStdout", type = Boolean)
]) final Map param) {
// 执行 shell 脚本,并等待执行完成
final Process p = param.script.toString().execute()
p.waitFor()
println "+ ${param.script}"
if (p.exitValue() == 0) {
if (param.returnStdout) {
return p.text
}
println p.text
} else {
println p.err.text
}
}
// 定义 echo 方法
void echo(final String message) {
println " ${message}"
}
}3.4 流水线调用流程分析
$ groovy jenkinsfile.groovy
Running pipeline using any available agent...
==> Running 'Build' stage...
+ ls -la
razem 32
drwxrwxr-x 5 wololock wololock 4096 04-07 18:20 .
drwxrwxr-x. 45 wololock wololock 4096 04-04 12:47 ..
drwxrwxr-x 3 wololock wololock 4096 04-04 12:48 com
drwxrwxr-x 7 wololock wololock 4096 04-07 18:20 .git
-rw-rw-r-- 1 wololock wololock 29 04-07 18:19 .gitignore
drwxrwxr-x 2 wololock wololock 4096 04-07 18:19 .idea
-rw-rw-r-- 1 wololock wololock 1016 04-04 13:23 jenkinsfile.groovy
-rw-rw-r-- 1 wololock wololock 23 04-07 18:20 README.md
+ date +%Y-%m-%d
2020-04-07
Groovy rocks!
env.SOME_STRING = foobar
==> Running 'Test' stage...
+ mvn -version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
Maven home: /home/wololock/.sdkman/candidates/maven/current
Java version: 1.8.0_232, vendor: Oracle Corporation, runtime: /home/wololock/.sdkman/candidates/java/8.0.232-open/jre
Default locale: pl_PL, platform encoding: UTF-8
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
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]