I would like to write my company Jenkins Pipeline Library using Java not Groovy, as groovy is slower than Java. I tried to find examples of such Java Jenkins library source code, but I found only Groovy. Any help with this model (Java libraries + Jenkins). Do you have experience in such composition? Thanks in advance.
-
Why do you assume groovy is slower than Java? Groovy runs on the JVM, just as Java. There's just an additional initial compile step, which would probably add less than 0.001 % to your Jenkins Pipeline duration. – GeertPt Feb 07 '22 at 14:52
-
I am basing on this article: https://dzone.com/articles/groovy-20-performance-compared. I am trying to replicate similar test on Jenkins using similar functions written in Java and in Groovy. – MichalT Feb 07 '22 at 18:27
-
`1/` take any plugin source as example - almost all are written in java. https://plugins.jenkins.io/ `2/` pipeline itself is not a real groovy code - accept it as a configuration - your article is not really applicable here... – daggett Feb 07 '22 at 19:24
1 Answers
First option
You have to provide a Groovy interface, but you can call Java in your implementation.
That is, you need to write a Groovy shared library using groovy code and the folder hierarchy as shown in https://www.jenkins.io/doc/book/pipeline/shared-libraries/, but from within Groovy functions you can call into Java libraries you imported using @Grab
, explained later in the same doc page.
This way, the majority of the logic can be in Java.
The code you import through @Grab can be written in any JVM language. The main caveat is that it has to be already compiled, uploaded somewhere, and available to be fetched.
See Jenkins shared libraries with kotlin for another answer along these lines.
Second option
Build an executable in Java and have your pipeline download this prebuilt executable and run it. This is suggested in Jenkins documentation in
- https://www.jenkins.io/doc/book/pipeline/pipeline-best-practices/#making-sure-to-use-groovy-code-in-pipelines-as-glue
- https://www.jenkins.io/doc/book/pipeline/pipeline-best-practices/#avoiding-complex-groovy-code-in-pipelines
Third option
Build something akin to a GitHub Action. That is, create a prebuilt Docker container which contains the tool you want to run. Then, in your pipeline, you can use a different container for every pipeline stage, depending on what you need to do. This might end up being simpler than the previous option, in some cases.
This is documented in https://www.jenkins.io/doc/book/pipeline/docker/#workspace-synchronization
pipeline {
agent any
stages {
stage('Build') {
agent {
docker {
image 'docker.io/my-corp/my-tool:v2'
reuseNode true
}
}
steps {
sh 'my-tool --version'
}
}
}
}

- 25,267
- 15
- 124
- 150