# Groovy everywhere, with one large asterisk

> Groovy 4.0 shipped last month. What the language is, how it runs on the JVM, where it turns up, and why the Groovy in your Jenkinsfile is not quite it.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-02-26
- Tags: Groovy, JVM, Gradle, Jenkins, CI/CD
- URL: https://deyanpeev.com/posts/groovy-everywhere-with-one-large-asterisk

I didn't set out to learn Groovy. I set out to make a Jenkins pipeline do
something, and a Jenkinsfile is Groovy, so I learned as much of it as the
error messages demanded and no more. Six weeks later I had a shared library
and a `NotSerializableException` I could not explain, and at that point "as
much as the error messages demand" had stopped working as a strategy.

Groovy 4.0.0 went GA on the twenty-fifth of January, so that's a good excuse
to write down what I worked out. Including the bit where the Groovy in a
Jenkinsfile is a dialect from 2015 running through a rewriting compiler inside a
whitelist.

# Java minus the ceremony

A JVM language, first released in 2003, an Apache project since 2015.
`groovyc` compiles it to ordinary JVM bytecode. The `.class` files are
indistinguishable from Java's, and Java code can call into them without
knowing. Almost all valid Java is also valid Groovy, so the on-ramp feels very
short.

The pitch is everything Java does, minus the ceremony, plus closures, plus a
metaobject protocol that lets you bend the language into a domain-specific
one.

```groovy
class Agent {
  String name
  List<String> labels = []
}

def win = new Agent(name: 'win-build-01', labels: ['windows', 'signing'])

assert win.labels.any { it.startsWith('win') }
assert win.labels                                   // a non-empty list is truthy
```

No `public`, no getters and setters you wrote, a map constructor you didn't
write, `it` as the implicit closure parameter, and Groovy truth. Six lines, and
it reads like what you meant.

# How it runs

There are three mechanics to understand here, because all three come back
later as constraints.

## A script is a class

Compile a file with bare statements at the top level
and you get a class extending `groovy.lang.Script`, with your statements in a
`run()` method:

```bash
$ echo 'println "hello"' > hi.groovy
$ groovyc hi.groovy && javap hi.class
public class hi extends groovy.lang.Script {
  public hi();
  public java.lang.Object run();
  public static void main(java.lang.String...);
}
```

Variables declared without `def` or a type don't become locals, they go into
the script's `Binding`. That's how Jenkins injects `env`, `params`
and `currentBuild` into your Jenkinsfile, and how Gradle injects `project`
into a build script. The `Binding` is a `Map` the host filled in before calling
`run()`.

## Method calls go through a metaclass

`thing.doIt()` does not compile to a
direct virtual call on `doIt`. It goes to the object's `MetaClass`, which can
be modified at runtime. That indirection buys you `methodMissing`,
`propertyMissing`, category classes and builders. It's also why `task hello { }`
in a Gradle file reads like syntax when really it's a method call that the
project object handles dynamically.

Groovy 4 made that dispatch always go through `invokedynamic`, and the separate
non-indy build variants are gone. That and the move to the
`org.apache.groovy` group id are the two changes most likely to affect you
before any of the new syntax does.

## You can turn the dynamism off

`@CompileStatic` compiles a class with
Java-like static dispatch. You get real compile-time errors and performance
close to Java, and you lose the metaprogramming.

```groovy
import groovy.transform.CompileStatic

@CompileStatic
long freeBytes(List<Map<String, Object>> disks) {
  disks.sum { (long) it.freeBytes } as long
  // it.freBytes is now a compile error rather than a null at two in the morning
}
```

What works, I think, is static by default in anything that behaves like a
library, and dynamic only where the DSL lives. It's the usual "keep the clever
part small" advice.

# Where it turns up

Until I looked, I hadn't appreciated that I have been running Groovy for years
without writing any.

**Gradle.** Every `build.gradle` in the Java world, which is most of the Java
world. On sheer executions this probably makes Groovy one of the most-run
languages on Earth.

**Jenkins.** Jenkinsfiles, shared libraries, the script console, Job DSL, and
the Groovy hooks in Configuration as Code.

**Spock.** The nicest test DSL on the JVM. Groovy is what makes the
`given: / when: / then: / where:` blocks possible as syntax and not just a
comment convention. Spock 2.0 moved onto the JUnit 5 platform last year, so it
now drops into an existing Java build without an argument.

**Grails.** Still shipping; version 5 landed in the autumn.

**Anything with a scripting hook.** Apache NiFi, SoapUI, Jira, Confluence,
Bamboo, and a long tail of internal tools that needed "let the user write a
bit of logic" and already had a JVM in the process.

It's the same story each time. Groovy turns up as the *configuration and glue*
layer over a system written in Java, and not usually as the language people
chose for their application. It is the JVM's shell script, more or less.

# The asterisk, and it is Jenkins

The Groovy in a Jenkinsfile isn't the Groovy that shipped last month. There are
three separate reasons and they compound.

## It is Groovy 2.4

Jenkins core bundles a Groovy 2.4.x runtime and pipeline
execution uses it. No Parrot parser, so none of Groovy 3's syntax (no
Java-style lambdas, no method references, no `!in`, no `do`/`while`). And
obviously nothing from 4. Copy a snippet off a 2022 blog post that does
`agents.stream().map(Agent::getName)` and it won't compile in your pipeline,
and the error doesn't mention versions.

## It is CPS-transformed

A pipeline has to survive the controller restarting halfway through a build, so
the Pipeline: Groovy plugin rewrites your program into continuation-passing
style. Every call becomes a step in a state machine, and the entire state of
that machine is serialised to disk after each one. These are the consequences
you'll run into.

Every local variable that is live across a step must be `Serializable`. A
`Matcher` from `=~`, a `File`, an `InputStream`, a `SimpleDateFormat` - hold
one across a `sh` or a `powershell` and you get a `NotSerializableException`
naming a class you didn't think you were storing.

```groovy
// Fails on the powershell step: the Matcher is a live local.
def m = readFile('version.txt') =~ /(\d+)\.(\d+)/
powershell 'ci\\build.ps1'
echo m[0][1]

// Fine. The Matcher never crosses a step boundary.
@NonCPS
String major(String text) {
  def m = text =~ /(\d+)\.(\d+)/
  return m ? m[0][1] : null
}
```

Groovy's own iteration methods are not transformed, so a closure body inside
`.each { }` doesn't behave quite like the body of a `for` loop when it calls
steps. `java.util.stream` does not work at all, because the JDK isn't
transformed and your closure is. And the escape hatch, `@NonCPS`, runs a
method as plain Groovy, so no pipeline steps inside it, and whatever it
returns had better be serialisable.

## It is sandboxed

Groovy script security intercepts every method call and
checks it against a whitelist. `new File(...)`, `Jenkins.instance`,
`System.getenv()` are all blocked, until an administrator approves them in
*In-process Script Approval*.

That is correct behaviour. A Jenkinsfile is code from a repository, executed on
the controller, and an unsandboxed Jenkinsfile is remote code execution against
your CI. But it also means that a large share of the Groovy you find online is
script-console Groovy, written by an administrator with no sandbox, and it
will never run in a pipeline.

Put the three together and the practical rule is that a Jenkinsfile is a
declarative document with a small amount of orchestration in it. When I want to
write a program, I write it in a language the machine is going to run normally,
and by this month that means Python, for the reasons I went through a fortnight
ago.

# Where else "everywhere" runs out

Native images are the first place. GraalVM's `native-image` needs to know at
build time what can be called, and a runtime metaobject protocol is close to the
opposite of that. `@CompileStatic` on everything helps, but it's not a solved
problem.

On Android there was a serious effort to make Groovy work, but the dynamic
runtime and the DEX toolchain never came to terms.

Startup is slow. JVM start plus Groovy's runtime initialisation is a good
fraction of a second before your first line executes. You don't see it inside
the Gradle daemon, but you do in a CLI you call in a loop, and most automation
looks like that.

Tooling is weaker. Gradle's Kotlin DSL exists because an IDE can complete Kotlin
and cannot reliably complete a dynamic Groovy DSL. That's a structural
disadvantage and it is the same trade again. Whatever the metaclass gives you
at runtime, it takes away from any tool trying to reason about your code
beforehand.

# So: everywhere?

Groovy runs anywhere a JVM runs, and it's present in far more places than its
reputation suggests. But "Groovy everywhere" is true the way "bash everywhere"
is true. It is the language you find at the seams of systems built in
something else, doing configuration, glue and orchestration, and it is
very good at that.

In Jenkins somebody asked it to do more, and what you get is a dialect frozen
at 2.4, compiled through a rewriter and executed behind a whitelist, where a
regex match is a bug waiting for the next step.

Learn enough to read a `build.gradle` and write a clean Jenkinsfile, and keep
your logic somewhere you can test it. It's about a weekend, and it will pay for
itself the first time an error message mentions `CpsCallableInvocation`.
