Narration: The first step in troubleshooting is not digging through logs, but figuring out which layer is broken.
Jenkins Hour 7: Deep Troubleshooting, Optimization, and Advanced Topics
- Master the Jenkins troubleshooting method of “layer first, collect evidence, change one thing at a time”: build log → controller log and Log Recorder → System Information / thread dump → Support Bundle → Script Console (read-only first).
- Explain precisely why a build is stuck in the queue: read
There are no nodes with the label ‘…’,All nodes of label ‘…’ are offline,Waiting for next available executor on ‘…’,Build #N is already in progress,Jenkins is about to shut downand other real queue reasons, and handle agent disconnects and ping timeouts. - Identify and fix 4 types of Pipeline runtime errors: CPS mismatch (
expected to call … but wound up catching …),java.io.NotSerializableException, sandboxRejectedAccessException: Scripts not permitted to use …,MissingMethodException/No such DSL method. - Read plugin-loading failure messages (
Update required,Required plugin is disabled,Jenkins (…) or higher required), and perform plugin upgrade assessments, rollbacks, and “plugin manifest as code” practices. - Set controller sizing: heap, G1GC and GC log options, no builds on the controller, build retention (Build Discarder), workspace cleanup, and Pipeline durability level.
- Explain the high-availability limits of open-source Jenkins (no native active-active), and design backup and restore (including
secrets/), RTO/RPO, and the scaling approach of “multiple controllers” rather than “one giant controller”. - Use the GitHub Actions Importer audit → forecast → dry-run → migrate workflow to assess migration, and manually map Jenkinsfiles to GitHub Actions and Azure Pipelines.
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before Class | Preparation: Fault-Injection Environment | Reuse ~/jenkinslab (or kind lab), API tokens,faults/ fault-injection scripts, baseline job faultbox | — | Get a green baseline |
| 1 | 00–06 | Troubleshooting Methodology | Five evidence layers, build log, controller log, Log Recorder, System Information, thread dump, Support Bundle, Script Console | “Evidence ladder” step-by-step animation | Use scriptText the API to write a diagnostic script why.sh |
| 2 | 06–13 | Stuck Builds | Queue state machine, label matching, executor exhaustion, agent disconnects, ping thread, throttling and quiet down | Queue diagnosis simulator (core animation) | Reproduce 4 queueing causes |
| 3 | 13–21 | Pipeline Errors | CPS transformation and program.dat, CPS mismatch, NotSerializableException, @NonCPS, sandbox approval, MissingMethod | CPS persistence animation (bad code vs fix) | Reproduce and fix 3 kinds of errors |
| 4 | 21–28 | Plugin Dependencies and Upgrades | Dependency graph, load failure messages, upgrade assessment, rollback, pinned versions in plugins.txt | Dependency conflict resolver | Disable a dependency plugin and restore it |
| 5 | 28–35 | Performance | Controller sizing, heap / G1GC / GC logs, build retention, workspace cleanup, durability level | JENKINS_HOME capacity and heap estimator | Add JVM options and read GC logs |
| 6 | 35–42 | Reliability | HA options, backup and restore, secrets, RTO/RPO, multiple controllers | Failure recovery timeline simulation | Backup → delete → restore drill |
| 7 | 42–50 | Migration | GitHub Actions Importer, Jenkinsfile → Actions / Azure Pipelines mapping | Syntax mapper | Importer audit + dry-run |
| 8 | 50–60 | Mixed Fault Mystery Box | Random injection of 8 fault types + interactive troubleshooting tree | Mystery box simulator + troubleshooting tree | Open the mystery box in a real environment |
| — | After Class | Cheat Sheet · Capstone Lab | Fault mystery box + performance health report + DR drill | Final quiz: 12 questions | Acceptance checklist: 12 items |
Knowledge Coverage Matrix
| Target Skill | Module | Key Commands / Settings | Lab | Production Case |
|---|---|---|---|---|
| Evidence Collection | M1 | consoleText,/manage/log,/manage/systemInfo,/threadDump, Support Bundle | ✓ | ✓ |
| Script Console and API | M1 · M2 | POST /scriptText,/queue/api/json,/computer/api/json | ✓ | ✓ |
| queue reasons | M2 | why,stuck,blocked, label expressions, executor count | ✓ | ✓ |
| agent connection | M2 | hudson.slaves.ChannelPinger.pingIntervalSeconds / pingTimeoutSeconds, agent log | ✓ | ✓ |
| CPS and serialization | M3 | @NonCPS,program.dat,durabilityHint | ✓ | ✓ |
| sandbox and approval | M3 | In-process Script Approval,ScriptApproval | ✓ | ✓ |
| plugin dependencies | M4 | jenkins-plugin-cli,plugins.txt,*.jpi.disabled, Downgrade | ✓ | ✓ |
| JVM tuning | M5 | JAVA_OPTS,controller.javaOpts,-Xlog:gc*,jcmd | ✓ | ✓ |
| retention and cleanup | M5 | buildDiscarder(logRotator(...)), Global Build Discarders,cleanWs() | ✓ | ✓ |
| backup and disaster recovery | M6 | tar JENKINS_HOME (including secrets/), ThinBackup, JCasC | ✓ | ✓ |
| migration | M7 | gh actions-importer audit/forecast/dry-run/migrate jenkins | ✓ | ✓ |
| Comprehensive troubleshooting | M8 | All | ✓ | ✓ |
Content Not Covered in This Lesson
| Topic | Reason | Where to Learn |
|---|---|---|
| Jenkins installation, agent connection, first Jenkinsfile | Covered in Lesson 1 | Lesson 1 |
| Declarative syntax, Multibranch, Webhook, Shared Library usage | Covered in Lesson 2; this lesson only covers “what to do when it breaks” | Lesson 2 |
| Full configuration of JCasC, Helm chart, and Kubernetes plugin Pod agents | Covered in Lesson 5 | Lesson 5 |
| Authorization matrix and the security model of Script Security approvals | Covered in Lesson 6; this lesson only covers troubleshooting | Lesson 6 |
| GitHub Actions syntax and runners | Topics in the GitHub course | GitHub 8-hour course |
| Azure Pipelines YAML and agent pools | Topics in the Azure DevOps course | Azure DevOps 8-hour course |
| Kubernetes Pod scheduling and resource quotas | Topics in the Kubernetes course | Kubernetes 8 + 1-hour course |
How to Use These Materials
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · narration · video. Read the “theory + animation” first, then
faults/inject.sh reproduce it yourself in your local environment.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (key name
jenkins60-part7-progress-v1).Main path: the Docker Compose environment from Lessons 1 and 2
~/jenkinslab (free, works offline). Alternative: the kind cluster from Lesson 5 lab + Helm release jenkins (namespace jenkins), some faults are injected differently; these are handled with branches in the scripts.Module 0 · Preparation: Fault-Injection Environment
~/jenkinslab (or the kind cluster lab), and set up a “known green” baseline job faultbox and a set of repeatable fault-injection / restore / diagnostic scripts. Troubleshooting practice depends on being able to return to a healthy state at any time- Completed Lessons 1 and 2:
~/jenkinslab/compose.yamlcontainsjenkins(127.0.0.1:8080),agent1(labellinux docker),gitea(127.0.0.1:3000, repositorylab/myapp); admin useradmin. - or completed Lesson 5: kind cluster
lab, namespacejenkins, Helm releasejenkins(official jenkinsci chart, controller Podjenkins-0), with agents as Pods dynamically created by the Kubernetes plugin. - Plugins: Pipeline (including Declarative), Docker Pipeline, Support Core (installed in M1). This lesson uses the Script Console,and only runs write operations in the lab environment.
- Local machine: bash, curl, python3, jq; the Compose path requires Docker Engine + Compose v2; the kind path requires kubectl and helm.
1. Connection to the previous lesson (reused variables and resources)
| Name | Value | Source |
|---|---|---|
| Lab directory / Compose file | ~/jenkinslab / compose.yaml (services jenkins,agent1,gitea) | Lesson 1 |
| controller address | http://127.0.0.1:8080 (used for the kind path kubectl -n jenkins port-forward svc/jenkins 8080:8080) | Lesson 1 / 5 |
| agent node name / label | agent1 (inbound agent, secret in .env of AGENT1_SECRET, 2 executors, mounting docker.sock) / linux docker | Lesson 1 |
| Image / API token | jenkins/jenkins:2.580.2-jdk21 / ~/jenkinslab/.secrets/jenkins-token | Lesson 1 |
| credential ID | gitea-myapp,registry-creds | Lessons 1, 2 |
| Application and Pipeline | myapp (Flask, port 5000,/healthz), Gitea repository lab/myapp, job myapp | Lessons 1, 2 |
| Created in this lesson | directory ~/jenkinslab/faults/; Pipeline job faultbox,faultbox-hog | this lesson |
2. Cost, Permissions, and Security
- Cost: Both the Compose path and the kind path use local resources at zero cost. The GitHub Actions Importer in M7 only reads Jenkins and opens PRs on GitHub (optional), and does not incur cost; if you run the generated workflows on a private repository, they are billed by GitHub Actions minutes (see the GitHub course).
- Permissions: The Script Console and
/scriptTextrequire Overall/Administer; the API token belongs toadmin,revoke it after use. - Security risk: Groovy in the Script Console runs as the controller process and can read all credentials and files,which is equivalent to root-level access on the controller host; in production, only run read-only queries and keep an audit record. If agent1 mounts
/var/run/docker.sock(a security trade-off from Lesson 1), the fault scripts will not modify it. - Cleanup:
faults/reset.shRestore all faults; delete after classfaultbox*the job and the API token.
3. Create the API Token and Environment File
Lesson 1 already saved admin 's API token in ~/jenkinslab/.secrets/jenkins-token (and provided the jcli helper command). If this file does not exist: log in to the browser admin → top-right username → Security → API Token → Add new Token, copy the token (shown only once), write it to this file and chmod 600. This lesson's scripts call the REST API directly with curl, but you can also use jcli.
mkdir -p ~/jenkinslab/faults && cd ~/jenkinslab/faults cat > env.sh <<'EOF' export JENKINS_URL=http://127.0.0.1:8080 export JENKINS_USER=admin export JENKINS_TOKEN=$(cat ~/jenkinslab/.secrets/jenkins-token) # API token saved in Lesson 1; do not commit it to Git export LAB=compose # for the kind path, change to k8s export COMPOSE_FILE=$HOME/jenkinslab/compose.yaml EOF chmod 600 env.sh && source env.sh # No CSRF crumb is needed when authenticating with an API token curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/api/json?tree=mode,numExecutors,quietingDown" | jq .
{
"_class": "hudson.model.Hudson",
"mode": "NORMAL",
"numExecutors": 0,
"quietingDown": false
}
numExecutors: 0 means no builds run on the built-in node (controller), which is the official recommendation (M5). If you see 2, Lesson 1 did not disable executors on the controller; some labs in this lesson still work, but change it to 0 in M5.4. Fault-Injection Scripts inject.sh
All Pipeline-type faults are injected into a separate inline Pipeline job faultbox (without changing the lab/myapp repository); infrastructure faults (agent offline, executor exhaustion, plugin disabled) act directly on the environment. The script writes the answer to .fault-answer, so do not peek during the mystery box exercise.
cat > ~/jenkinslab/faults/inject.sh <<'EOF'
#!/usr/bin/env bash
# Usage: inject.sh base | F1..F8 | random
set -euo pipefail
cd "$(dirname "$0")"; source ./env.sh
api(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
groovy(){ api --data-urlencode "script=$1" "$JENKINS_URL/scriptText"; }
dc(){ docker compose -f "$COMPOSE_FILE" "$@"; }
put_job(){ # $1=job name $2=Pipeline script, inline with sandbox enabled
local esc xml; esc=$(python3 -c 'import sys,html;print(html.escape(sys.argv[1]))' "$2")
xml="<flow-definition plugin=\"workflow-job\"><description>fault lab</description><definition class=\"org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition\" plugin=\"workflow-cps\"><script>$esc</script><sandbox>true</sandbox></definition></flow-definition>"
if api -o /dev/null "$JENKINS_URL/job/$1/api/json" 2>/dev/null; then
api -X POST -H 'Content-Type: application/xml' --data-binary "$xml" "$JENKINS_URL/job/$1/config.xml"
else
api -X POST -H 'Content-Type: application/xml' --data-binary "$xml" "$JENKINS_URL/createItem?name=$1"
fi
}
build(){ api -X POST "$JENKINS_URL/job/$1/build"; }
pipe(){ # $1=label $2=steps content $3=sleep seconds
cat <<GROOVY
pipeline {
agent { label '$1' }
options { disableConcurrentBuilds(); timeout(time: 15, unit: 'MINUTES') }
stages {
stage('Build') { steps { sh 'echo "build on \$NODE_NAME"; sleep ${3:-5}' } }
stage('Check') { steps { $2 } }
}
}
GROOVY
}
OK_STEPS="echo 'all good'"
f="${1:-random}"; [ "$f" = random ] && f="F$(( RANDOM % 8 + 1 ))"
echo "$f" > .fault-answer; chmod 600 .fault-answer
case "$f" in
base) put_job faultbox "$(pipe linux "$OK_STEPS")" ;;
F1) put_job faultbox "$(pipe linux-dokcer "$OK_STEPS")" ;; # label typo
F2) put_job faultbox "$(pipe linux "$OK_STEPS")" # agent goes offline
if [ "$LAB" = k8s ]; then
kubectl -n jenkins create quota fault-pods --hard=pods=1 2>/dev/null || true
else dc stop agent1; fi ;;
F3) put_job faultbox "$(pipe linux "$OK_STEPS")" # executor exhaustion
put_job faultbox-hog "pipeline {
agent { label 'linux' }
stages { stage('hog') { steps { sh 'sleep 900' } } }
}"
if [ "$LAB" = k8s ]; then
groovy "def c=Jenkins.get().clouds.getByName('kubernetes'); new File(Jenkins.get().rootDir,'faults-cap.txt').text=c.containerCapStr; c.containerCapStr='1'; Jenkins.get().save(); println 'cap=1'"
else
groovy "def n=Jenkins.get().getNode('agent1'); new File(Jenkins.get().rootDir,'faults-exec.txt').text=String.valueOf(n.numExecutors); n.numExecutors=1; Jenkins.get().updateNode(n); println 'executors=1'"
fi
build faultbox-hog; sleep 3 ;;
F4) put_job faultbox "$(pipe linux "$OK_STEPS" 300)"; build faultbox; sleep 2 ;; # throttling: concurrent runs of the same job are prohibited
F5) put_job faultbox "$(pipe linux "script { def m = ('myapp-1.1' =~ /(\\d+)\\.(\\d+)/); if (m.find()) { sh \"echo major=\${m.group(1)}\" } }")" ;;
F6) put_job faultbox "$(pipe linux "script { def h = 'hostname'.execute().text; echo h }")" ;;
F7) put_job faultbox "$(pipe linux "script { docker.image('python:3.12-slim').inside { sh 'python -V' } }")"
if [ "$LAB" = k8s ]; then
kubectl -n jenkins exec jenkins-0 -c jenkins -- touch /var/jenkins_home/plugins/docker-commons.jpi.disabled
kubectl -n jenkins delete pod jenkins-0 --wait=false
else
dc exec -T jenkins touch /var/jenkins_home/plugins/docker-commons.jpi.disabled; dc restart jenkins
fi
echo "controller is restarting, trigger the build again in about 1 minute"; exit 0 ;;
F8) put_job faultbox "$(pipe linux "script { echo 'myapp'.toUppercase() }")" ;;
*) echo "unknown fault $f" >&2; exit 1 ;;
esac
build faultbox
echo "One fault has been injected. Start troubleshooting: faults/why.sh"
EOF
chmod +x ~/jenkinslab/faults/inject.sh
faultbox the job configuration page and confirm the script reads /(\d+)\.(\d+)/ is sufficient. The Groovy and plugin-disabling operations in F3 / F7 change the controller configuration, so run them only in the lab environment.5. Restore Script reset.sh
cat > ~/jenkinslab/faults/reset.sh <<'EOF'
#!/usr/bin/env bash
set -uo pipefail
cd "$(dirname "$0")"; source ./env.sh
api(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
groovy(){ api --data-urlencode "script=$1" "$JENKINS_URL/scriptText"; }
if [ "$LAB" = k8s ]; then
kubectl -n jenkins delete quota fault-pods --ignore-not-found
if kubectl -n jenkins exec jenkins-0 -c jenkins -- test -e /var/jenkins_home/plugins/docker-commons.jpi.disabled; then
kubectl -n jenkins exec jenkins-0 -c jenkins -- rm -f /var/jenkins_home/plugins/docker-commons.jpi.disabled
kubectl -n jenkins delete pod jenkins-0; kubectl -n jenkins wait --for=condition=Ready pod/jenkins-0 --timeout=300s
fi
else
docker compose -f "$COMPOSE_FILE" start agent1
if docker compose -f "$COMPOSE_FILE" exec -T jenkins test -e /var/jenkins_home/plugins/docker-commons.jpi.disabled; then
docker compose -f "$COMPOSE_FILE" exec -T jenkins rm -f /var/jenkins_home/plugins/docker-commons.jpi.disabled
docker compose -f "$COMPOSE_FILE" restart jenkins; sleep 60
fi
fi
groovy '
def j = Jenkins.get(); def home = j.rootDir
def f = new File(home, "faults-exec.txt"); if (f.exists()) { def n = j.getNode("agent1"); n.numExecutors = f.text.trim() as int; j.updateNode(n); f.delete() }
def c = new File(home, "faults-cap.txt"); if (c.exists()) { j.clouds.getByName("kubernetes").containerCapStr = c.text.trim(); j.save(); c.delete() }
j.queue.items.findAll { it.task.name?.startsWith("faultbox") }.each { j.queue.cancel(it.task) }
["faultbox","faultbox-hog"].each { name -> j.getItem(name)?.builds?.findAll { it.building }?.each { it.doStop() } }
println "reset done"'
./inject.sh base >/dev/null; rm -f .fault-answer; echo "Baseline restored"
EOF
chmod +x ~/jenkinslab/faults/reset.sh
6. Get a Green Baseline
cd ~/jenkinslab/faults && ./inject.sh base && sleep 25 curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/api/json?tree=number,result,building" | jq -c .
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","building":false,"number":1,"result":"SUCCESS"}
Self-check checklist
Module 1 · Troubleshooting Methodology: Logs, System Information, and the Script Console
- Use the “five-layer method” (job definition → queue → agent / connection → Pipeline engine → steps and tools) to identify which layer a fault belongs to within 1 minute.
- Know where each type of evidence is: build log (
consoleText), controller log (container stdout /kubectl logs), System Log and Log Recorder, System Information, thread dumps, agent logs. - Can generate and securely share a Support Bundle (Support Core plugin), and knows what it contains and what must be redacted.
- Can use the Script Console and
POST /scriptTextthe API to run read-only diagnostic scripts, understanding their risks and audit requirements.
What: What exactly is being debugged in Jenkins troubleshooting
A build goes through the following stages in order: ① job definition (trigger, SCM, Jenkinsfile read and compiled) → ② queue (waiting for a free executor on a node with a matching label) → ③ agent and connection (Remoting channel, workspace, tools) → ④ Pipeline engine (the controller interprets Groovy in CPS style, persists program state, and performs sandbox checks) → ⑤ steps and tools (sh,docker,git and other real processes running on the agent). Where a failure occurs determines where the evidence is.
| Layer | Typical symptom | Where to find evidence | Common tools |
|---|---|---|---|
| ① Job definition | No trigger after push, Jenkinsfile compile error (WorkflowScript: 12: …) | Start of the build log, Multibranch's Scan Log, Webhook delivery log | Replay, Pipeline Syntax, Declarative Linter |
| ② Queue | The build stays queued in grey, or the Pipeline log shows Still waiting to schedule task | hovering over a queue entry shows the reason (why),/queue/api/json | all of M2 |
| ③ Agent / connection | Agent offline,ChannelClosedException,Ping started at … hasn't completed by … | the node page's Log, agent process log, controller log | /computer/api/json, thread dump |
| ④ Pipeline engine | NotSerializableException,RejectedAccessException, CPS mismatch | Java stack trace in the build log | M3, Script Approval |
| ⑤ Steps and tools | script returned exit code 1 | The output of that step in the build log | Manually reproduce the same command on the agent |
| Cross-cutting: the controller itself | Slow UI, frequent Full GC, plugin load failures | controller log, GC log, top-of-page alerts in Manage Jenkins | M4, M5, Support Bundle |
Why: why collect evidence along the “evidence ladder”
Jenkins problems are often misdiagnosed as “the script is wrong.” In reality, problems with queuing (②), connections (③), and controller resources (the cross-cutting layer) usually just show up in the build log as “slow” or “interrupted.” First identify the layer, then climb the evidence ladder: start with the cheapest and safest evidence, and use the Script Console (highest risk) only when needed.
How: the evidence ladder (from shallow to deep)
- Build log: the build page's Console Output, or plain text
…/job/<name>/<n>/consoleText. Pipeline also lets you view Pipeline Steps (the duration and status of each step) and Stage View / Pipeline Graph View. The log file is located at$JENKINS_HOME/jobs/<name>/builds/<n>/log(folders and multibranch jobs have one more leveljobs/orbranches/). - Controller log: in container deployments, this is the container stdout (
docker compose logs jenkins,kubectl -n jenkins logs jenkins-0 -c jenkins). In the UI, Manage Jenkins → System Log shows recent log records. - Log Recorder: in System Log, Add recorder by logger name (for example
hudson.model.Queue,hudson.slaves.ChannelPinger,org.jenkinsci.plugins.workflow.cps) collect logs at a higher level (FINE / ALL). Raise the log level only for one subsystem, and remove it after troubleshooting. - System Information and thread dumps:
/manage/systemInfolists system properties, environment variables, plugins, and memory;/threadDumpshows the stack of all threads (to determine whether the UI is hung, there is a deadlock, or a plugin is blocking the queue maintenance thread). The node page also has System Information and a thread dump for that agent. - Support Bundle: After installing Support Core the plugin,Manage Jenkins → Troubleshooting → Support (the menu location may vary; follow what your UI shows) select the content to generate a zip: version and plugin list (
about.md), node information, logs, thread dumps, system properties, etc. Useful to attach to a ticket or hand to upstream maintainers. - Script Console:
/manage/scriptorPOST /scriptText, runs arbitrary Groovy in the controller JVM, and can read the internal state of queues, nodes, and plugins. Most powerful, highest risk, so in production only run read-only queries.
When: when to escalate to the next level of evidence
- If the build log shows a clear error (exit code, Java stack trace), stop at level 1.
- If the build log has no errors but the build “has not started / is stuck / was interrupted,” check the queue and nodes (M2), then the controller log.
- If multiple jobs fail at once or the UI slows down, use a thread dump + GC log (M5) + Support Bundle.
- If you need precise internal state (for example, a certain queue entry's
CauseOfBlockage, or all offline reasons), use a read-only Script Console script.
Common Misconceptions
- “Set the root logger to ALL and you’ll see everything” — the log volume will overwhelm the controller; create a Log Recorder only for specific loggers.
- “The Support Bundle is redacted, so it can be published directly” — it tries to filter secrets, but may still contain host names, user names, job names, environment variables, and log content; check it yourself before sharing, and do not paste it into a public issue.
- “The Script Console is just a debugging window” — it runs as the controller process and can read all credentials and change any configuration; anyone who can access it effectively has full control of the controller host.
- “Code changed in Replay is saved” — Replay only applies to that one build; fixes must be committed back to the Jenkinsfile.
Five-layer method and evidence sources
Evidence in JENKINS_HOME
program.dat is the persisted file of CPS program state (M3); secrets/ determines whether credentials can be decrypted (M6)Step-by-step animation: follow the evidence ladder to locate “why the build never starts”
Scenario: the developer says faultbox the build has “been waiting for 10 minutes and still hasn’t started.” Follow the animation to see what question each level of evidence answers.
1. Build log and Pipeline steps
source ~/jenkinslab/faults/env.sh
J(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
J "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | tail -30
# Path for a multibranch job: /job/myapp-multibranch/job/main/lastBuild/consoleText
J "$JENKINS_URL/job/faultbox/lastBuild/api/json?tree=number,result,building,duration,executor[currentExecutable[url]]" | jq .
2. Controller log
# Compose path docker compose -f ~/jenkinslab/compose.yaml logs --since 15m jenkins | grep -E "WARNING|SEVERE" | tail -20 # kind path kubectl -n jenkins logs jenkins-0 -c jenkins --since=15m | grep -E "WARNING|SEVERE" | tail -20 kubectl -n jenkins logs jenkins-0 -c jenkins --previous | tail -50 # if the container has restarted, view the previous log
2026-11-16 09:12:03.118+0000 [id=58] WARNING hudson.slaves.ChannelPinger$1#onDead: Ping failed. Terminating the channel agent1. java.util.concurrent.TimeoutException: Ping started at 1763284083110 hasn't completed by 1763284323110
3. System information and thread dumps
# Browser: /manage/systemInfo (System Information), /threadDump (thread dump), /manage/log (System Log) J "$JENKINS_URL/threadDump" -o threaddump-$(date +%s).html # JVM level: use jcmd inside the controller container (the official image includes a JDK) docker compose -f ~/jenkinslab/compose.yaml exec jenkins sh -c 'jcmd 1 Thread.print | head -40' docker compose -f ~/jenkinslab/compose.yaml exec jenkins sh -c 'jcmd 1 GC.heap_info'
jcmd -l find jenkins.war the matching PID, then replace the 1.4. Read-only diagnostics using the Script Console API
J --data-urlencode 'script=
def j = Jenkins.get()
println "version=${Jenkins.VERSION} quietingDown=${j.quietingDown}"
j.queue.items.each { println "QUEUE ${it.task.fullDisplayName} | why=${it.why} | stuck=${it.stuck}" }
j.computers.each { c -> println "NODE ${c.name ?: "built-in"} offline=${c.offline} busy=${c.countBusy()}/${c.numExecutors} cause=${c.offlineCause}" }
j.pluginManager.failedPlugins.each { println "PLUGIN-FAILED ${it.name}: ${it.cause}" }' "$JENKINS_URL/scriptText"
version=2.580.2 quietingDown=false QUEUE part of faultbox #7 | why=There are no nodes with the label ‘linux-dokcer’ | stuck=false NODE built-in offline=false busy=0/0 cause=null NODE agent1 offline=false busy=0/2 cause=null
5. Temporarily raise the log level for a subsystem
Manage Jenkins → System Log → Add recorder
Name: queue-debug
Loggers: hudson.model.Queue Log level: FINE
hudson.slaves.ChannelPinger Log level: FINE
→ reproduce the problem → view /manage/log/queue-debug → delete the recorder after troubleshooting
6. Support Bundle
Install the Support Core plugin (support-core) Manage Jenkins → Troubleshooting → Support → select the needed components (About Jenkins, Agents, Loggers, Thread dumps …) → Generate Bundle You get support_<timestamp>.zip; unzip and check it before attaching it to the ticket (menu locations depend on your actual version)
Lab: write a reusable diagnostic script why.sh
cd ~/jenkinslab/faults && ./inject.sh F1 && sleep 10
agent the node it needs.
curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText"
Started by user admin [Pipeline] Start of Pipeline [Pipeline] node Still waiting to schedule task There are no nodes with the label ‘linux-dokcer’
cat > ~/jenkinslab/faults/why.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"; source ./env.sh
J(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
job="${1:-faultbox}"
echo "== queue"
J "$JENKINS_URL/queue/api/json?tree=items[id,why,stuck,blocked,buildable,inQueueSince,task[name]]" |
jq -r '.items[] | "\(.id) \(.task.name // "-") stuck=\(.stuck) blocked=\(.blocked) why=\(.why)"'
echo "== nodes"
J "$JENKINS_URL/computer/api/json?tree=busyExecutors,totalExecutors,computer[displayName,offline,temporarilyOffline,offlineCauseReason,numExecutors]" |
jq -r '"executors busy/total: \(.busyExecutors)/\(.totalExecutors)", (.computer[] | "\(.displayName) offline=\(.offline) temp=\(.temporarilyOffline) executors=\(.numExecutors) reason=\(.offlineCauseReason)")'
echo "== last build of $job"
J "$JENKINS_URL/job/$job/lastBuild/api/json?tree=number,result,building" | jq -c .
J "$JENKINS_URL/job/$job/lastBuild/consoleText" | tail -15
echo "== failed plugins"
J --data-urlencode 'script=Jenkins.get().pluginManager.failedPlugins.each{ println "${it.name}: ${it.cause?.message}" }' "$JENKINS_URL/scriptText"
EOF
chmod +x ~/jenkinslab/faults/why.sh && ~/jenkinslab/faults/why.sh
== queue
12 part of faultbox #2 stuck=false blocked=false why=There are no nodes with the label ‘linux-dokcer’
== nodes
executors busy/total: 0/2
Built-In Node offline=false temp=false executors=0 reason=
agent1 offline=false temp=false executors=2 reason=
== last build of faultbox
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","building":true,"number":2,"result":null}
...
== failed pluginshudson.model.Queue create a FINE-level recorder, observe the queue maintenance logs, then delete it.about.md and the node directory, and list the 3 types of information you think need redaction../reset.sh; delete the Log Recorder.Case 1: “Jenkins is slow” was actually a plugin blocking the queue
Symptoms: Starting at 10 a.m., all builds queued up, and the UI was intermittently slow. Evidence: Three consecutive thread dumps (10 seconds apart) all showed AtmostOneTaskExecutor[Queue.maintain] related threads stuck in the same plugin's QueueTaskDispatcher implementation, waiting for an external HTTP call. Fix: Temporarily disable that plugin's feature and upgrade to the fixed version. Lesson: For “global slowness,” first capture multiple thread dumps and compare the stacks that stay unchanged.
Case 2: Support Bundle leaked internal host names
A team pasted a Support Bundle directly into a public GitHub issue; it contained agent host names, internal network segments, and job names. Improvement: Adopt a rule: “share bundles only through private channels, and check for IPs / host names / email addresses with a script before sharing”; when asking for help publicly, paste only minimal log snippets.
Case 3: The Script Console was treated as a “universal fix tool”
An administrator bulk-deleted builds that “looked unused” in the production Script Console, accidentally removing release records that compliance required be kept. Improvement: Use the Script Console for read-only diagnostics only; write operations should instead go through reviewed JCasC / Job DSL or scripts with a dry-run switch, recorded in a change ticket; minimize Overall/Administer permissions (Lesson 6).
Common errors and solutions
/scriptText returns 403 No valid crumb was included in the request
Cause: A POST was sent with username + password (session authentication), which requires a CSRF crumb. Fix: Switch to API token authentication (requests using token authentication do not need a crumb); or first send a GET /crumbIssuer/api/json and include the cookie from the same session.
The build log only shows “Still waiting to schedule task”
Cause: The Pipeline's node / agent block is queued; the problem is at layer ②. Action: Check the reason line that follows, or the queue entry's why field, then go to M2.
The Console Output page opens extremely slowly or even freezes the browser
Cause: The log is too large (hundreds of MB). Action: Use consoleText + tail; the real fix is to reduce log output (set +x, quiet flags for tools), and build retention policies (M5).
curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/myapp/lastBuild/consoleText" | tail -200 # for multibranch jobs use /job/myapp-multibranch/job/main/
kubectl logs does not show logs from before the crash
Cause: The container has restarted. Fix:kubectl -n jenkins logs jenkins-0 -c jenkins --previous; and check kubectl -n jenkins describe pod jenkins-0 in the Last State: Terminated Reason: OOMKilled (M5).
The Support menu does not exist
Cause: The Support Core plugin is not installed, or you do not have Administer permission. Fix: Install support-core; if the instance is managed by JCasC / plugins.txt, add it to the plugin list and then publish (M4).
1. Using an API token, print from the command line faultbox the last 20 lines of the most recent build log.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | tail -20
2. Using /scriptText list all offline nodes and their offline reasons.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" --data-urlencode 'script=Jenkins.get().computers.findAll{ it.offline }.each{ println "${it.name}: ${it.offlineCause}" }' "$JENKINS_URL/scriptText"Scenario analysis question: On Monday morning, a developer reports “all builds are queued, and the UI takes 20 seconds to open.” In what order do you collect evidence?
Reference answer
① Check the queue reasons (are they the same reason, is quiet down on?) and node status, ruling out simple causes such as “all agents are offline”; ② check the controller log for SEVERE / OutOfMemoryError / GC warnings; ③ capture 3 thread dumps 10 seconds apart and find threads that stay stuck in the same place (queue maintenance, a certain plugin, locks); ④ check the GC log and heap usage (M5); ⑤ generate a Support Bundle to preserve evidence; ⑥ only then run read-only queries in the Script Console. At each step, only observe; once the root cause is confirmed, change one thing.
Instructional video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering Support Bundle, Log Recorder, and Script Console diagnostics was found; please refer to the official documentation and storyboard script below.
Official documentation
Video storyboard script
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Narration: The first step in troubleshooting is not digging through logs, but figuring out which layer is broken.
Narration: The build log has no errors, so the problem is in the queue; the queue entry tells you what it is waiting for.
Narration: When you need more detail, raise the log level for only one subsystem; for global slowness, capture thread dumps repeatedly.
Narration: The Script Console can see everything and change everything; production is read-only, and write operations go through code review.
Module 2 · Stuck Builds: Queues, Executors, and Agent Disconnects
- Name the four stages of a queue entry (waiting → blocked → buildable → pending / left) and the typical reason for each stage.
- Identify the root cause from the actual reason text: no matching label, all nodes offline, executor exhaustion, concurrent builds of the same job prohibited, throttle plugin, controller preparing to shut down, quiet period.
- Diagnose agent disconnects: distinguish “never connected,” “marked offline,” and “channel closed by the ping thread,” and know the
ChannelPingerdefault interval and timeout. - Understand the Pipeline's waiting logic when an agent disconnects (by default, it waits 5 minutes for the node to recover), and how to safely abort a stuck build.
What: what happens to an entry in the queue
Each time a build is triggered, Jenkins places an entry in hudson.model.Queue , and the queue maintenance thread (Queue.maintain()) periodically advances it:
- waiting: during the quiet period, the reason is
In the quiet period. Expires in …. Repeated triggers of the same job during the quiet period are merged. - blocked: the job itself or a plugin says “it cannot run now.” For example, with the Pipeline option
disableConcurrentBuilds()the reason isBuild #41 is already in progress (ETA: 3 min 12 sec); the Throttle Concurrent Builds plugin givesAlready running 1 builds across all nodes; when the controller is in Prepare for shutdown (quiet down), it isJenkins is about to shut down. - buildable: it can run now, and is only waiting for a node and an executor. The reason comes from label resolution:
There are no nodes with the label ‘X’(no node or cloud has this label),All nodes of label ‘X’ are offline,‘agent1’ is offline(a single node is specified),Waiting for next available executor on ‘X’(the node is online but all executors are busy). - pending → left: an executor has been assigned and is starting; once it leaves the queue, it becomes a build.
Pipeline has one key detail: a Pipeline build first starts on the controller with a lightweight (flyweight) executor,each node / agent block then enters the queue as a separate entry (shown as part of faultbox #7) to request an executor on an agent. So the build page shows “running,” but the log stops at Still waiting to schedule task; it is stuck at the second queue entry.
Why: four main categories of causes
| Cause | Original queue reason text (Jenkins core / plugin messages) | First step |
|---|---|---|
| No matching label | There are no nodes with the label ‘linux-dokcer’ | Compare the Jenkinsfile's label against node labels; the Label page lists matching nodes and clouds |
| Agent offline | All nodes of label ‘linux’ are offline / ‘agent1’ is offline | node page Log; whether the agent process is running; network and port 50000 / WebSocket |
| Executor exhaustion | Waiting for next available executor on ‘linux’ | Who is holding the executor? /computer/api/json busy/total; are there any hung builds |
| Throttling / blocking | Build #41 is already in progress (ETA: …),Already running 1 builds across all nodes,Jenkins is about to shut down | job options, throttle category, lock resource, whether someone clicked Prepare for shutdown |
Additionally: when a node is set to Only build jobs with label expressions matching this node (EXCLUSIVE mode), jobs without a label will not run on it; the reason is ‘agent1’ is reserved for jobs with matching label expression; when a node is temporarily taken offline, it is ‘agent1’ is not accepting tasks a category (verify against actual output).
How: three forms of agent disconnects
- Never connected: the node page shows offline, and the Log has connection errors (SSH authentication failure, wrong inbound agent secret, unable to reach the controller URL / port 50000 or WebSocket).
- Marked offline by a person or a monitor: the node page shows the offline reason (for example, “Disconnected by admin,” or the disk space monitor considers free space below the threshold).
offlineCauseReasonThe field can be read from the API. - Channel closed: on the Remoting channel, the controller's ChannelPinger periodically pings the agent. The source code default interval is 300 seconds, timeout is 240 seconds, and after a timeout the log shows
Ping started at … hasn't completed by …and the channel is terminated. You can adjust it with the system propertyhudson.slaves.ChannelPinger.pingIntervalSeconds/hudson.slaves.ChannelPinger.pingTimeoutSeconds(usually no change is needed; frequent timeouts are usually caused by network issues, load balancer idle timeouts, or agent memory problems).
The Pipeline is running on an agent sh that disconnects, but the Pipeline does not fail immediately: the log prints agent1 seems to be removed or offline …; will wait for 5 min 0 sec for it to come back online (the source code waits 5 minutes by default; the system property org.jenkinsci.plugins.workflow.support.pickles.ExecutorPickle.timeoutForNodeMillis), and after the timeout it reports Timeout waiting for agent to come back. Once a Kubernetes Pod agent's Pod is deleted, the Pod does not “come back,” so it usually fails faster (the plugin has corresponding detection; behavior depends on the plugin version).
When: when is it considered “stuck”
In the queue API, the stuck: true indicates that the entry is already buildable, but the wait time is clearly longer than expected (see the decision logic in Queue.BuildableItem#isStuck, where the UI shows a red clock icon). In practice, define it by SLO: for example, “alert if queued for > 5 minutes,” using queue metrics exported by the Prometheus metrics plugin or calling /queue/api/json on a schedule.
Common Misconceptions
- “If the build shows as running, it is not a queue problem” — the Pipeline's
nodeblock is a separate queue entry. - “Adding executors to the controller will solve queuing” — the official recommendation is not to run builds on the controller (set executors to 0); queuing must be addressed by scaling out on the agent / cloud side.
- “An agent being offline means the agent process crashed” — it may also be a disk monitor, a manual offline by an admin, a ping timeout, or a network policy on the controller side.
- “Case-sensitivity issues in label matching are rare” — labels are exact-match strings,
Linuxandlinuxare different; label expressions support&&,||,!.
Queue state machine and reason sources
Messages.properties and plugin messages; once you understand them, you know where to lookTwo-level queuing in Pipeline
Core animation: why a build is stuck in the queue
Adjust the conditions on the right, then click “Trigger build.” The dot passes through each checkpoint in the real order of the Jenkins queue: shutdown check → job blocking (concurrency) → plugin blocking (throttling) → label resolution → node online → idle executor. A stuck checkpoint turns red and displays the same kind of reason as /queue/api/json in why .
Label expression in the Jenkinsfile:
1. Queue: who is waiting and for what
source ~/jenkinslab/faults/env.sh
J(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
J "$JENKINS_URL/queue/api/json?tree=items[id,why,stuck,blocked,buildable,inQueueSince,task[name,url]]" |
jq -r '.items[] | [.id, .task.name, (if .blocked then "blocked" elif .buildable then "buildable" else "waiting" end), .stuck, .why] | @tsv'
31 part of faultbox #9 buildable false Waiting for next available executor on ‘linux’ 32 faultbox blocked false Build #9 is already in progress (ETA: 4 min 51 sec)
2. Nodes: online status, executors, offline reasons
J "$JENKINS_URL/computer/api/json?tree=busyExecutors,totalExecutors,computer[displayName,offline,temporarilyOffline,offlineCauseReason,numExecutors,assignedLabels[name]]" |
jq -r '"busy/total=\(.busyExecutors)/\(.totalExecutors)", (.computer[] | "\(.displayName)\toffline=\(.offline)\texec=\(.numExecutors)\tlabels=\([.assignedLabels[].name]|join(","))\t\(.offlineCauseReason)")'
# Which nodes match a label (also visible on the label page)
J "$JENKINS_URL/label/linux/api/json?tree=name,nodes[nodeName],idleExecutors,busyExecutors,clouds[name]" | jq .
3. Jenkins CLI: bringing nodes online/offline and connecting nodes
curl -fsSO "$JENKINS_URL/jnlpJars/jenkins-cli.jar"
CLI(){ java -jar jenkins-cli.jar -s "$JENKINS_URL" -auth "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
CLI offline-node agent1 -m "maintenance: disk cleanup" # take offline temporarily (running builds keep going)
CLI online-node agent1
CLI disconnect-node agent1 -m "reconnect test" && CLI connect-node agent1
CLI cancel-quiet-down # cancel Prepare for shutdown
4. Agent side
# Compose: agent process log docker compose -f ~/jenkinslab/compose.yaml logs --since 30m agent1 | tail -40 docker compose -f ~/jenkinslab/compose.yaml exec agent1 df -h /home/jenkins # the disk monitor takes the node offline # kind: why the Pod agent did not start kubectl -n jenkins get pods -l jenkins/label --sort-by=.metadata.creationTimestamp kubectl -n jenkins get events --sort-by=.lastTimestamp | tail -15 kubectl -n jenkins describe pod <agent-pod> | sed -n '/Events/,$p'
Warning FailedScheduling pod/myapp-ci-3-xk2p1-0w7lm-2v9qd 0/1 nodes are available: 1 Insufficient cpu. Warning FailedCreate ... pods "myapp-ci-3-..." is forbidden: exceeded quota: fault-pods, requested: pods=1, used: pods=1, limited: pods=1
-l jenkins/label so if they do not match, use kubectl -n jenkins get pods --show-labels to check.5. Ping parameters (controller startup parameters; usually no change needed)
# jenkins service in compose.yaml (the official image reads JAVA_OPTS)
environment:
JAVA_OPTS: >-
-Dhudson.slaves.ChannelPinger.pingIntervalSeconds=300
-Dhudson.slaves.ChannelPinger.pingTimeoutSeconds=240
6. Safely abort a stuck Pipeline
# Try in order: UI Abort → the "Click here to forcibly terminate running steps" message in the log → "forcibly kill entire build" J -X POST "$JENKINS_URL/job/faultbox/9/stop" # equivalent to Abort J -X POST "$JENKINS_URL/job/faultbox/9/term" # forcibly terminate the running steps (Pipeline) J -X POST "$JENKINS_URL/job/faultbox/9/kill" # last resort: end the entire build immediately
Lab: reproduce the 4 queueing causes yourself
cd ~/jenkinslab/faults && ./inject.sh F1 && sleep 10 && ./why.sh | sed -n '1,3p'
== queue 14 part of faultbox #3 stuck=false blocked=false why=There are no nodes with the label ‘linux-dokcer’
Fix: ./reset.sh (equivalent to changing the label back to linux).
agent1 the container; the kind path creates a ResourceQuota that allows only 1 Pod, so the agent Pod is rejected at creation.
./inject.sh F2 && sleep 15 && ./why.sh | sed -n '1,8p'
14 part of faultbox #4 stuck=false blocked=false why=All nodes of label ‘linux’ are offline ... agent1 offline=true temp=false executors=2 reason=
Think about it: why would the kind path's reason not be “offline,” but more likely “Waiting for next available executor” or waiting for a Pod indefinitely? (The cloud can “provision” this label, so the queue assumes a node will come later; the real error is in the Kubernetes events.)
./reset.sh
faultbox-hog hold it.
./inject.sh F3 && sleep 15 && ./why.sh | sed -n '1,6p'
15 part of faultbox #5 stuck=false blocked=false why=Waiting for next available executor on ‘linux’ == nodes executors busy/total: 1/1
Find the “occupant”:
curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/computer/agent1/api/json?tree=executors[currentExecutable[url]]" | jq -r '.executors[].currentExecutable.url' ./reset.sh
disableConcurrentBuilds(), and the script triggers it twice in a row.
./inject.sh F4 && sleep 8 && ./why.sh | sed -n '1,3p'
16 faultbox stuck=false blocked=true why=Build #6 is already in progress (ETA: 4 min 48 sec)
Note blocked=true: this is the job itself blocking, not a missing node. Wait for the first build to finish, or abort it.
./reset.sh
faultbox, and the reason is Jenkins is about to shut down; use CLI cancel-quiet-down or the cancel button on the page to restore.Case 1: after a label rename, half the team's builds queued all afternoon
The platform team changed the node label from docker to docker-24, but only updated half of the Jenkinsfiles. The queue filled up with There are no nodes with the label ‘docker’. Fix: Restore the old label as an alias (a node can have multiple labels). Prevention: Treat labels as an API: add the new label first, migrate, then remove the old label; use a Shared Library to unify agent the declarations.
Case 2: a load balancer idle timeout caused agents to drop every 6 minutes
The inbound agent connects to port 50000 through a cloud load balancer that has a 350-second idle timeout, while the ping interval is 300 seconds and network jitter occasionally pushes it past the threshold, and the log shows Ping started at … hasn't completed by …. Fix: Switch to WebSocket mode to connect through the HTTPS entry point (Lesson 5), and raise the LB idle timeout to more than 15 minutes. Lesson: For periodic disconnects, first find which intermediate device the “period” comes from.
Case 3: Kubernetes Pod agent stuck in Pending
The build log stops at Still waiting to schedule task, and Jenkins shows no errors. kubectl get events shows 0/6 nodes are available: 6 Insufficient memory: the Pod template requests 8Gi of memory, but the node pool can allocate at most 7Gi. Fix: Lower the requests, or create a separate node pool and label for large-memory builds.
Case 4: the overnight “hang” was caused by forgetting to cancel Prepare for shutdown
On-call staff clicked Prepare for shutdown to upgrade plugins; the upgrade was postponed but the shutdown was never cancelled. The next day, all new builds showed Jenkins is about to shut down. Prevention: Make “cancel quiet down or complete the restart” a mandatory step in the upgrade runbook; monitor /api/json for the quietingDown.
Common errors and solutions
There are no nodes with the label ‘linux-dokcer’
Cause: No node or cloud template has this label (spelling, case, or the label was renamed). Diagnosis: Open /label/<label>/ or the label validation in Pipeline Syntax (it will show No agent/cloud matches this label expression. Did you mean ‘…’). Fix: Change the Jenkinsfile or add the label to the node.
All nodes of label ‘linux’ are offline
Cause: All nodes matching the label are offline. Diagnosis:why.sh 's nodes section, the node page Log, and agent process logs. Fix: Start or reconnect the agent; if the disk monitor took it offline, the node recovers automatically after you clean up the disk (or bring it online manually).
Waiting for next available executor on ‘linux’
Cause: The node is online, but all executors are occupied. Diagnosis: Check which build each executor is running, and whether any are hung (input steps, or sleep or network waits without a timeout). Fix: Add timeout; place input in the agent none stage, so it does not hold an executor while waiting for people; scale out agents or raise the cloud limit.
Build #41 is already in progress (ETA: 3 min 12 sec)
Cause: The job disallows concurrent builds (disableConcurrentBuilds() or the Freestyle job does not check “Execute concurrent builds if necessary”). Fix: This is by design; if you need to cancel old builds, you can use disableConcurrentBuilds(abortPrevious: true) (supported in newer workflow-job versions; verify against actual output).
java.util.concurrent.TimeoutException: Ping started at 1763284083110 hasn't completed by 1763284323110
Cause: ChannelPinger did not receive a response from the agent within the timeout (default 240 seconds): a network interruption, an intermediate device idle timeout, the agent JVM running a long GC, or the agent being suspended. Diagnosis: GC and memory on the agent side, and timeout settings along the network path. Fix: Fix the network or resource problem, rather than blindly increasing the timeout.
agent1 seems to be removed or offline; will wait for 5 min 0 sec for it to come back online
Cause: The node went offline while the Pipeline was executing a step on it, and the Pipeline is waiting for the node to return. Fix: Restore the agent as soon as possible; if the node will not come back (a temporary Pod or a deleted VM), abort the build and rerun it. After the timeout, it reports Timeout waiting for agent to come back.
hudson.remoting.ChannelClosedException: Channel "hudson.remoting.Channel@…:agent1": Remote call on agent1 failed. The channel is closing down or has closed down
Cause: The Remoting channel disconnected during step execution (agent restart, OOM, network). Diagnosis: the exit reason of the agent container / Pod (docker inspect,kubectl describe pod of OOMKilled). Verify the exact message format against actual output.
1. Use jq to list only the queue entries where stuck is true, showing names and reasons.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" "$JENKINS_URL/queue/api/json?tree=items[why,stuck,task[name]]" | jq -r '.items[] | select(.stuck) | "\(.task.name)\t\(.why)"'
2. Use the Jenkins CLI to take agent1 offline temporarily with a stated reason, and bring it back online after maintenance.
Reference answer
java -jar jenkins-cli.jar -s "$JENKINS_URL" -auth "admin:$JENKINS_TOKEN" offline-node agent1 -m "maintenance" java -jar jenkins-cli.jar -s "$JENKINS_URL" -auth "admin:$JENKINS_TOKEN" online-node agent1
Scenario analysis question: The build page shows myapp/main #120 has been running for 25 minutes, and the last line of the log is Still waiting to schedule task,/computer/api/json shows busy/total = 6/6. What is the next step?
Reference answer
This is executor exhaustion. List the builds currently running on the 6 executors (/computer/<node>/api/json?tree=executors[currentExecutable[url]]), and check whether any are stuck at input, waiting without a timeout, or abnormally long builds; short term: abort stuck builds and temporarily scale out; long term: add timeout, so that input does not hold an executor, alert on queue-time SLOs, and consider Kubernetes elastic agents.
Instructional video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering queue reasons and ChannelPinger was found; please refer to the official documentation, source code, and storyboard script below.
Official documentation and source code
- Managing Nodes
- core Messages.properties (Queue.* reason text)
- ChannelPinger.java (ping defaults)
- Throttle Concurrent Builds
- Pipeline: Nodes and Processes (node step)
Video storyboard script
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Narration: Every build must pass the same checks: shutdown, concurrency, throttling, label, online, executor.
Narration: The queue reason is the answer: no node has this label.
Narration: The nodes are online but all busy: find out who is holding the executors, rather than adding executors to the controller.
Narration: When the connection drops, the Pipeline waits for the node to come back for a while; a temporary Pod will not come back, so just rerun.
Module 3 · Pipeline Errors: CPS, Serialization, and Sandbox Rejections
- Explain the CPS execution model: Groovy is transformed into continuation form, executed on the controller, and at step boundaries program state is persisted to the build directory's
program.dat. - Identify and fix
java.io.NotSerializableException(for examplejava.util.regex.Matcher, JsonSlurper'sLazyMap). - Understand the CPS mismatch warning
expected to call … but wound up catching …'s meaning, and use@NonCPScorrectly. - Handle sandbox rejections
RejectedAccessException: Scripts not permitted to use …: when to approve, when to rewrite, and when to move code into a trusted Shared Library. - Distinguish
MissingMethodException,MissingPropertyException,No such DSL methodfrom compile errorsMultipleCompilationErrorsException.
What: the CPS execution model
The Pipeline plugin (Pipeline: Groovy,workflow-cps) first compiles the Jenkinsfile into a Groovy class, then performs a CPS (Continuation-Passing Style) transformation: every method call becomes a form that can be “paused and resumed later.” Interpreted execution happens in controller on the CPS VM thread; sh,bat and other steps run as external processes on the agent. When the Pipeline needs to wait (step execution,sleep,input, waiting for a node), the engine serializes the entire program state (call stack, local variables, closures) to the build directory's program.dat. After the controller restarts, the Pipeline resumes from exactly this file.
Why: where the four error types come from
| Error | Root cause | Actual error message (verbatim) | Preferred fix |
|---|---|---|---|
| Not serializable | At a step boundary, an object that is not serializable is in scope | java.io.NotSerializableException: java.util.regex.Matcher | Do not keep that object in CPS code: move it into @NonCPS a method that returns only a String / List, or use readJSON and similar steps |
| CPS mismatch | Non-CPS code (native Groovy / Java methods,@NonCPS methods, constructors,toString) calls back a CPS-transformed closure or method | expected to call java.util.ArrayList.toSorted but wound up catching org.jenkinsci.plugins.workflow.cps.CpsClosure2.call; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/ | Do not pass a CPS closure to a native method (such as toSorted { a, b -> … }); put the pure computation as a whole into an @NonCPS method |
| Sandbox rejection | By default the sandbox only allows whitelisted methods / constructors / fields | org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String | Use steps instead (sh,readFile,readJSON); move the necessary logic into a trusted global Shared Library; admin approval is the last resort |
| Method / property / step does not exist | Typo, mismatched parameter types, or the plugin is not installed or not loaded | groovy.lang.MissingMethodException: No signature of method: java.lang.String.toUppercase() is applicable for argument types: () values: []; java.lang.NoSuchMethodError: No such DSL method 'shh' found among steps [...]; groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding | Fix the spelling / parameters; confirm the plugin that provides this step or global variable is installed and loaded (M4) |
How: correct usage of @NonCPS
@NonCPSThe method runs to completion in one go as plain Groovy,and it cannot be paused, so it can use non-serializable objects (Matcher, iterators), but it cannot call Pipeline steps (sh,echo,readFile...), and it should not call CPS methods.- Its parameters and return value must be serializable simple values (String, Number, List / Map of String).
- In Declarative, the
@NonCPSmethod must be written outside thepipeline { }block (at file top level), or moved into a Shared Library. - The sandbox still applies:
@NonCPSdoes not bypass Script Security.
When: durability level (durabilityHint)
Pipeline supports three durability levels: MAX_SURVIVABILITY (default, safest, most disk writes),SURVIVABLE_NONATOMIC,PERFORMANCE_OPTIMIZED (fewest disk writes; running Pipelines may not be recoverable if the controller shuts down abnormally). It can be set globally (Manage Jenkins → System → Pipeline Speed/Durability Settings), in Multibranch branch properties, or options { durabilityHint('PERFORMANCE_OPTIMIZED') } setting. It cannot make non-serializable objects “legitimate”.
Common misconceptions
- “Pipeline just runs Groovy on the agent” — all Groovy logic is interpreted on the controller; only steps (
shetc.) run on the agent. Heavy Groovy computation slows down the controller (M5). - “Adding @NonCPS to a method solves every problem” — if the method calls
sh, it will fail or behave unexpectedly (CPS mismatch). - “Just click Approve when the sandbox reports an error” — approval applies globally; approving
execute,Jenkins.instanceand similar “dangerous signatures” effectively hands the controller to anyone who can edit a Jenkinsfile. - “Fixing it in Replay fixes it” — Replay only affects that single build.
CPS execution and program.dat
Sandbox decision flow
method / staticMethod / new / field + class name + method name + parameter typesStep-by-step animation: why a Matcher crashes the Pipeline
Select a code version, then play. Watch the “Local variables” box being serialized at the step boundary.
script {
def m = ('myapp-1.1' =~ /(\d+)\.(\d+)/) // java.util.regex.Matcher
if (m.find()) {
sh "echo major=${m.group(1)}" // step boundary: writes program.dat
}
}
1. Three ways to fix NotSerializableException
// Fix A: use a Matcher inside an @NonCPS method and return only a String (write it outside pipeline { })
@NonCPS
String majorOf(String v) {
def m = (v =~ /(\d+)\.(\d+)/)
return m.find() ? m.group(1) : null
}
pipeline {
agent { label 'linux' }
stages { stage('Version') { steps { script {
def major = majorOf('myapp-1.1')
sh "echo major=${major}"
} } } }
}
// Fix B: set the non-serializable variable to null before the step
script {
def m = ('myapp-1.1' =~ /(\d+)\.(\d+)/)
def major = m.find() ? m.group(1) : null
m = null
sh "echo major=${major}"
}
// Fix C: parse JSON with a step (Pipeline Utility Steps plugin) instead of JsonSlurper's LazyMap
script {
def cfg = readJSON file: 'deploy.json' // returns a serializable object
sh "echo replicas=${cfg.replicas}"
}
2. Sandbox rejection: rewrite instead of approving
// ✗ Rejected: runs a process on the controller and needs approval of a dangerous signature
def h = 'hostname'.execute().text
// ✓ Run on the agent and capture the output
def h = sh(script: 'hostname', returnStdout: true).trim()
// ✗ new File(...) reads the controller's file system and needs approval
// ✓ readFile reads the current agent workspace
def v = readFile('VERSION').trim()
3. Review and handle pending signatures
# UI: Manage Jenkins → In-process Script Approval
# Read-only query of pending signatures (Script Console / scriptText)
curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" --data-urlencode 'script=
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval
ScriptApproval.get().pendingSignatures.each { println it.signature }' "$JENKINS_URL/scriptText"
staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String
4. Syntax and compile errors: validate before committing
# Declarative Linter (requires Overall/Read; token auth does not need a crumb) curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" -X POST -F "jenkinsfile=<Jenkinsfile" "$JENKINS_URL/pipeline-model-converter/validate"
Errors encountered validating Jenkinsfile: WorkflowScript: 6: Unknown stage section "step". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 6, column 5.
5. Inspect the build's persistence file and adjust the durability level
docker compose -f ~/jenkinslab/compose.yaml exec jenkins ls -la /var/jenkins_home/jobs/faultbox/builds/lastSuccessfulBuild/ # program.dat only exists while the build is running (it is deleted when the build ends); you can observe it during the long build run in F4
pipeline {
agent { label 'linux' }
options { durabilityHint('PERFORMANCE_OPTIMIZED') } // suitable for read-only, re-runnable CI builds
stages { stage('Test') { steps { sh 'pytest -q' } } }
}
Lab: reproduce and fix three Pipeline runtime errors
cd ~/jenkinslab/faults && ./inject.sh F5 && sleep 20 curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | grep -m3 -E "NotSerializable|Caused|in field"
java.io.NotSerializableException: java.util.regex.Matcher in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@6a1f…
Fix: open faultbox → latest build → Replay, change the code to Fix B from section 1 of “Commands” and confirm SUCCESS; then understand why Fix A is more general.
./inject.sh F6 && sleep 20 curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | grep -m2 -E "RejectedAccess|Scripts not permitted"
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String
Open Manage Jenkins → In-process Script Approval, and you will see that the signature is flagged as dangerous. Do not approve; use Replay to change it to sh(script: 'hostname', returnStdout: true).trim().
./inject.sh F8 && sleep 20 curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | grep -m1 -A1 "MissingMethodException"
groovy.lang.MissingMethodException: No signature of method: java.lang.String.toUppercase() is applicable for argument types: () values: [] Possible solutions: toUpperCase(), toUpperCase(java.util.Locale)
Fix: toUpperCase(). Then try changing sh to shh (in script {} ), observe No such DSL method 'shh' found among steps and the list of steps that follows it.
sorted becomes -1).
script {
def names = ['myapp-web', 'db', 'cache']
def sorted = names.toSorted { a, b -> a.length() <=> b.length() } // CPS closure passed to the native toSorted
echo "sorted=${sorted}"
}
expected to call java.util.ArrayList.toSorted but wound up catching org.jenkinsci.plugins.workflow.cps.CpsClosure2.call; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/
Fix: put the sort inside @NonCPS method, which returns a new list.
./reset.sh; confirm that In-process Script Approval has no leftover approved dangerous signatures.Case 1: JSON parsing starts failing randomly after an upgrade
The team had been using new groovy.json.JsonSlurper().parseText(...), and the result was LazyMap (not serializable); previously no step happened to be called after it. After adding a sh the failure appeared java.io.NotSerializableException: groovy.json.internal.LazyMap. Fix: switch to readJSON. Prevention: In the Shared Library, provide parseJson() wrapper, and cover it with unit tests in the library.
Case 2: to “get it fixed quickly,” approved Jenkins.instance
: a Jenkinsfile needed to read all node names, and the developer requested approval for staticMethod jenkins.model.Jenkins getInstance, and an admin approved it. Afterward, anyone who could commit a Jenkinsfile could use it to read credentials. Fix: revoke the approval (the Script Approval page can clear approved signatures); move privileged logic into a trusted global Shared Library and expose only a minimal interface (Lesson 6).
Case 3: a “build” that pins the controller CPU at 100%
A Jenkinsfile looped in Groovy over 200,000 lines of test reports (string concatenation, regex). All the computation ran in the controller's CPS VM and produced heavy persistence overhead on every iteration. Fix: move the processing into a script on the agent (Python / jq), and have the Pipeline read only the final summary. Principle: The Pipeline is “glue”; heavy computation belongs in sh .
Common errors and solutions
java.io.NotSerializableException: java.util.regex.Matcher
Cause: a Matcher was kept in scope at a step boundary. Fix: the @NonCPS method returns only a string, or set it to null before the step. Similar types: java.util.ArrayList$Itr (explicit iterators),groovy.json.internal.LazyMap, some SDK client objects.
expected to call … but wound up catching …; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/
Cause: non-CPS code called CPS code (a native method calling back a CPS closure, calling a step inside @NonCPS, a constructor, or a toString() method that calls a CPS method). Fix: rewrite following the pattern in the linked hint; put pure computation entirely inside @NonCPS; call steps only from CPS code.
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method …
Cause: the signature is not on the whitelist. Handling order:① Can a Pipeline step replace it? ② Can it be moved into a trusted global Shared Library? ③ Only a signature that is truly safe should be approved in In-process Script Approval, with the reason recorded. The end of the log usually also tells you that an admin can approve it (Administrators can decide whether to approve or reject this signature.).
java.lang.NoSuchMethodError: No such DSL method 'xxx' found among steps [...]
Cause: the step name is misspelled, or the plugin that provides the step is not installed or failed to load (e.g. readJSON requires the Pipeline Utility Steps plugin). Diagnosis: check whether Pipeline Syntax → Steps Reference lists the step, and whether Manage Jenkins shows a plugin load failure warning at the top (M4).
groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding
Cause: global variable docker is provided by the Docker Pipeline plugin, which is not installed or failed to load (mystery case F7). Fix: fix the plugin dependencies (M4).
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 12: …
Cause: Jenkinsfile compile error (syntax, Declarative structure). Fix: correct the lines indicated; validate with the Declarative Linter before committing (“Commands” section 4). If the file is too large, you may also see Method code too large!— split the logic into a Shared Library.
1. Rewrite def out = 'git rev-parse HEAD'.execute().text as a sandbox-friendly version that runs on the agent.
Reference answer
def out = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
2. Write an @NonCPS method that extracts the major version number from v1.2.3 and returns it as a string.
Reference answer
@NonCPS
String major(String v) { def m = (v =~ /^v?(\d+)\./); return m.find() ? m.group(1) : '0' }Scenario analysis question: A developer says, “My Pipeline always fails after the controller restarts with NotSerializableException, but it's fine normally.” Why?
Reference answer
Normally, some code paths never trigger persistence while a non-serializable object is alive, or the durability level is PERFORMANCE_OPTIMIZED, which writes less to disk. A restart requires saving and restoring the full program state, so the problem surfaces. The correct fix is to avoid holding non-serializable objects in CPS scope (return simple values from @NonCPS, set them to null, or use steps), rather than changing the durability level.
Teaching video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering CPS serialization and Script Security troubleshooting was found; please refer to the official docs and storyboard script below.
Official documentation
- Pipeline CPS method mismatches
- Pipeline Best Practices
- Scaling Pipelines (durability)
- In-process Script Approval
- workflow-cps-plugin source and README
Video storyboard script
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
Narration: The Pipeline's Groovy runs on the controller in CPS style; only steps run on the agent.
Narration: At every step boundary the program state is written to disk; a single non-serializable object in scope makes it fail.
Narration: Keep the non-serializable computation inside an @NonCPS method, and return only simple values.
Narration: When the sandbox rejects something, first check whether a step can do the job instead of clicking Approve.
Module 4 · Plugin dependency conflicts and upgrade failures
- Understand the plugin dependency model: each plugin declares its minimum core version and the minimum versions of its dependency plugins (required or optional); the controller loads plugins according to the dependency graph at startup.
- Recognize the raw text of 5 load-failure types:
Failed to load,Update required,Jenkins (…) or higher required,Required plugin is disabled,Plugin is missing. - Set up an upgrade process: read the LTS upgrade guide and security advisories → rehearse in a staging environment → back up → upgrade core and plugins together → verify → rollback plan.
- Use
jenkins-plugin-cliandplugins.txt/ Helmcontroller.installPluginsto pin versions and avoid “latest drift”.
What: plugin dependency graph
Each plugin (.jpi / .hpi) declares in its manifest: Jenkins-Version (the minimum required core version) and Plugin-Dependencies (the dependency plugins and their minimum versions, which can be marked optional). At startup, PluginManager loads them in dependency order. If a plugin's dependencies are not met, it does not load, and plugins that depend on it also fail to load (indirect failure). For example, as of 2026-11-16, Pipeline: Groovy 4403.v471713a_cea_19 requires core ≥ 2.568.1; Docker Pipeline 653.v2f2c08eff0ec depends on Docker Commons ≥ 477.v289085a_b_6896; Git 5.11.0 depends on Git client ≥ 6.5.0.
Why: five load-failure types (source: hudson/Messages.properties)
| Message template | Meaning | Typical trigger |
|---|---|---|
Failed to load: {display name} ({short name} {version}) | The plugin did not load (heading line; the specific cause follows) | Any one of the following |
Jenkins ({version}) or higher required | The plugin requires a newer core | Only the plugin was upgraded, not core; a .hpi was uploaded manually; the image build pulled latest for the plugin |
Update required: {display name} ({short name} {current version}) to be updated to {minimum version} or higher | Dependency plugin version is too low | Only the plugin that depends on it was upgraded |
Required plugin is disabled: {display name} ({short name}) | A dependency plugin was disabled | Someone disabled a plugin that “looked unused” |
Plugin is missing: {short name} ({version}) | The dependency plugin does not exist at all | The .jpi was deleted manually, plugins.txt omitted the dependency, and dependency resolution was turned off |
After the controller starts,Manage Jenkins a red warning appears at the top of the page: Some plugins could not be loaded due to unsatisfied dependencies. Fix these issues and restart Jenkins to re-enable these plugins., split into Dependency errors (direct) and Indirectly dependent plugins (indirect) groups.
How: upgrade process
- Read: the LTS upgrade guide (jenkins.io/doc/upgrade-guide/, which lists breaking changes per version, such as Java version requirements), each plugin's changelog, and security advisories (jenkins.io/security/advisories/). Note that since 2.555.1, LTS no longer supports Java 17.
- Rehearse: using the same
plugins.txt+ new core to build the image in a staging environment (or kindlab) and start it; check for “Manage Jenkins” warnings and run a set of smoke-test Pipelines. - Back up: snapshot of JENKINS_HOME (at least
plugins/,config.xml,jobs/*/config.xml,secrets/, M6). - Upgrade together: core and plugins are released as one versioned set (image tag); do not piecemeal click “Update All” in the UI.
- Verify and roll back: on failure, roll back to the previous image tag plus the backup; an individual plugin can be rolled back on the Installed page of Plugin Manager using Downgrade to … (the
.bakfile left over from before the upgrade).
When: the plugin manifest is code
The official image includes jenkins-plugin-cli (Plugin Installation Manager Tool), which in the Dockerfile installs from plugins.txt and resolves dependencies; the Helm chart uses controller.installPlugins list,controller.installLatestPlugins (whether to upgrade dependencies to the latest) and similar parameters control behavior. Recommended: pin versions and periodically (e.g. monthly) batch-upgrade via PR.
Common misconceptions
- “Clicking ‘Update All’ in the UI is the easiest” — it makes the production controller the first test environment, and there is no reproducible version record.
- “Disabling a plugin does not affect others” — every plugin that depends on it will fail to load; Plugin Manager warns about dependencies when you disable, but deleting the file does not.
- “If a plugin fails to load, reinstall core” — in most cases you only need to add, upgrade, or enable the dependency plugins and then restart.
- “Downgrade always works” — only plugins upgraded through Plugin Manager that still have
.bakhave a downgrade button; a plugin whose data format was migrated by a newer version may be incompatible when downgraded.
Dependency graph and cascading failures
Upgrade pipeline
Dependency conflict resolver
Select an “upgrade operation” and watch how PluginManager checks dependencies one by one at controller startup, which plugins fail directly, which fail indirectly, and the raw text that appears in Manage Jenkins. Version numbers come from plugins.jenkins.io as of 2026-11-16; the old version numbers in scenario C are examples.
1. View installed plugins and load failures
source ~/jenkinslab/faults/env.sh
J(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
J "$JENKINS_URL/pluginManager/api/json?depth=1&tree=plugins[shortName,version,active,enabled,hasUpdate]" |
jq -r '.plugins[] | select(.active|not) | "\(.shortName) \(.version) enabled=\(.enabled)"'
J --data-urlencode 'script=Jenkins.get().pluginManager.failedPlugins.each { println "${it.name}\n${it.cause?.message}\n" }' "$JENKINS_URL/scriptText"
docker-workflow Failed to load: Docker Pipeline (docker-workflow 653.v2f2c08eff0ec) - Required plugin is disabled: Docker Commons (docker-commons)
2. Generate a reproducible plugin list
# Export shortName:version from the running controller (as the starting point for plugins.txt)
J --data-urlencode 'script=Jenkins.get().pluginManager.plugins.sort{ it.shortName }.each { println "${it.shortName}:${it.version}" }' "$JENKINS_URL/scriptText" > plugins.txt
wc -l plugins.txt
3. jenkins-plugin-cli: check for updates and security warnings
docker compose -f ~/jenkinslab/compose.yaml cp plugins.txt jenkins:/tmp/plugins.txt docker compose -f ~/jenkinslab/compose.yaml exec jenkins jenkins-plugin-cli \ --plugin-file /tmp/plugins.txt --war /usr/share/jenkins/jenkins.war \ --available-updates --output txt --no-download
jenkins-plugin-cli --help (tool version verified for this lesson: 2.16.0). --war Have the tool judge compatibility against that core version; --no-download analysis only, no download; plugins with security warnings are shown by default (use --hide-security-warnings to hide them,--view-all-security-warnings to show all).4. Pin core + plugins in the image
# ~/jenkinslab/controller/Dockerfile (example) FROM jenkins/jenkins:2.580.2-jdk21 COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
# kind route: Helm values (jenkinsci/jenkins chart)
controller:
image:
tag: "2.580.2-jdk21"
installPlugins:
- workflow-aggregator:608.v67378e9d3db_1
- docker-workflow:653.v2f2c08eff0ec
- configuration-as-code:2147.v8a_8d38668c72
installLatestPlugins: false # dependencies are not auto-upgraded to latest; check the chart docs for exact behavior
jenkins/jenkins (the course convention writes it as jenkins/jenkins:<current LTS>-jdk21).5. Disable, enable, and roll back an individual plugin
CLI(){ java -jar jenkins-cli.jar -s "$JENKINS_URL" -auth "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
CLI disable-plugin docker-commons -restart # prompts about or handles plugins that depend on it; see --help for the policy
CLI enable-plugin docker-commons -restart
# File-level (when the controller will not start):
docker compose -f ~/jenkinslab/compose.yaml exec jenkins ls /var/jenkins_home/plugins | grep -E "\.(disabled|bak)$"
# Downgrade: Manage Jenkins → Plugins → Installed plugins → the plugin → "Downgrade to …" (requires a .bak)
Lab: disable a dependency plugin → diagnose → restore (F7)
~/jenkinslab Git repository as the baseline.plugins/ , creates docker-commons.jpi.disabled and restarts the controller.
cd ~/jenkinslab/faults && ./inject.sh F7 sleep 60 && docker compose -f ~/jenkinslab/compose.yaml logs --since 3m jenkins | grep -E "Failed (to load|Loading)" -A2 | head
SEVERE jenkins.InitReactorRunner$1#onTaskFailed: Failed Loading plugin Docker Pipeline v653.v2f2c08eff0ec (docker-workflow) java.io.IOException: Failed to load: Docker Pipeline (docker-workflow 653.v2f2c08eff0ec) - Required plugin is disabled: Docker Commons (docker-commons)
Some plugins could not be loaded due to unsatisfied dependencies., record the two groups, Dependency errors and Indirectly dependent plugins.curl -fsS -X POST -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/build"; sleep 25 curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | grep -m1 "MissingPropertyException"
groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding
Notice the gap between the build log error (Pipeline layer) and the actual root cause (plugin layer).
./reset.sh (delete .disabled file and restart), confirm the warning is gone and faultbox turns green.Jenkins (2.568.1) or higher required; after the experiment, helm uninstall.Case 1: “Update All” on Friday afternoon
An administrator updated 40 plugins at once in the UI and restarted; one plugin's new version required a higher core, which caused 12 Pipeline-related plugins to fail indirectly, and all Pipeline jobs showed as unable to load. Recovery: Restore from the previous day's plugins/ backup and restart (30 minutes). Improvements: keep the plugin list in Git, with monthly upgrade PRs and a staging environment; in production, disable plugin-install permissions in the UI (keep them only for the platform team).
Case 2: the container image quietly differs on every build
In the Dockerfile, plugins.txt only the plugin name was specified (equivalent to latest); two weeks later, the same Dockerfile built an image with incompatible plugins. Fix: pin all plugin versions, tag images by date + core version, and generate upgrade PRs with Renovate or scheduled jobs.
Case 3: data format incompatible after downgrade
A plugin migrated its configuration format after an upgrade; after downgrading to the old version, job configuration reads failed (Manage Jenkins → Manage Old Data shows unreadable data). Lesson: Roll back using the full JENKINS_HOME backup from before the upgrade plus the old image, rather than downgrading only a single plugin.
Common errors and solutions
Failed to load: Pipeline: Groovy (workflow-cps 4403.v471713a_cea_19) - Jenkins (2.568.1) or higher required
Cause: the plugin requires a newer core. Fix: upgrade core to an LTS that meets the requirement, or pin the plugin to a version compatible with the older core (the version history on the plugin page lists the required core).
Update required: Docker Commons (docker-commons 451.vd12c371eeeb_3) to be updated to 477.v289085a_b_6896 or higher
Cause: the dependency plugin version is too low (version numbers are examples). Fix: upgrade that dependency plugin; build the image with jenkins-plugin-cli , and it resolves dependencies automatically.
Required plugin is disabled: Docker Commons (docker-commons)
Cause: a dependency plugin is disabled. Fix: Enable it, then restart: enable-plugin docker-commons -restart or delete plugins/docker-commons.jpi.disabled.
Plugin is missing: git-client (6.5.0)
Cause: the dependency plugin file does not exist. Fix: install the plugin (meeting the minimum version), then restart; check whether plugins.txt omits it and whether the image build turned off dependency resolution.
Controller fails to start after upgrading core: UnsupportedClassVersionError / requires a newer Java
Cause: the new LTS requires a newer Java (since 2.555.1, Java 17 is not supported). Fix: use the -jdk21 or -jdk25 image; for non-container deployments, upgrade the JDK first. The exact error text varies by JVM, so go by what you actually see.
After a plugin is deleted or downgraded, Manage Jenkins reports unreadable old data (Manage Old Data)
Cause: after a plugin is deleted or downgraded, the configuration still contains data it no longer recognizes. Action: Review it in Manage Old Data; discard it only after confirming it is unused (wording may vary; follow what you see).
1. Use the Script Console API to list all plugins that failed to load, along with their causes.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" --data-urlencode 'script=Jenkins.get().pluginManager.failedPlugins.each{ println "${it.name}: ${it.cause?.message}" }' "$JENKINS_URL/scriptText"2. Write the two lines in a Dockerfile that install plugins from plugins.txt.
Reference answer
COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
Scenario analysis question: A security advisory requires you to upgrade a plugin to the fixed version immediately, but the new version requires a newer core than your current LTS. What do you do?
Reference answer
First check whether the advisory lists a fixed version compatible with the older core, or a temporary mitigation (disable the affected feature, restrict permissions). If there is none, schedule an urgent core upgrade: verify the same plugins.txt + new core image in a staging environment (including Java version requirements), back up, and release in a maintenance window. At the same time, assess the exposure (who can reach the feature), record “core lagging too far behind” as technical debt, and establish a monthly upgrade cadence.
Teaching video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering plugin dependency errors and upgrade rollback was found; please refer to the official docs and storyboard script below.
Official documentation
- Managing Plugins
- LTS Upgrade Guide
- Security Advisories
- Plugin Installation Manager Tool
- jenkinsci Helm chart
Video storyboard script
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
Narration: Plugins load according to the dependency graph; if one lower-level plugin fails, every plugin above it fails too.
Narration: Fix the “direct” errors first; the indirect failures disappear on their own.
Narration: Release core and plugins together as one image version; rolling back means switching back to the previous tag.
Module 5 · Performance: controller sizing, JVM, and build retention
- State the key principles for controller sizing: set the built-in node's executors to 0; cap the heap (a common recommendation is no more than about 16 GB; beyond that, split the controller); put JENKINS_HOME on fast local or block storage.
- Set JVM options for a controller running in a container (
JAVA_OPTS/ Helmcontroller.javaOpts): G1GC, GC logging, a heap dump on OOM, and a heap size set as a percentage of container memory. - Use GC logs,
jcmdand thread dumps to determine whether “slowness” comes from GC or from a plugin. - Configure build retention (job-level
buildDiscarderand Global Build Discarders) and workspace cleanup (cleanWs()), and understand how the Pipeline durability level affects I/O.
What: the controller's workload
The controller handles: Web UI and REST API, queue scheduling, Remoting channels with all agents,interpreting all Pipelines' Groovy (M3), receiving and storing build logs and artifacts, SCM scanning and webhook handling, and plugins' background tasks. The official hardware recommendations page notes that memory ranges from about 200 MB for a small instance to over 70 GB for a very large single instance; each agent connection needs about 2–3 threads (more than about 2 MB of memory); and allocating executors on the controller is generally a bad practice.
Why: common performance bottlenecks
| Bottleneck | Symptom | Evidence | Remedy |
|---|---|---|---|
| Insufficient heap / GC pressure | Periodic UI lag, high CPU, eventually java.lang.OutOfMemoryError: Java heap space or the container OOMKilled | Frequent long pauses in the GC log,jcmd GC.heap_info | tune the heap, find memory hogs (heap dump), reduce retained builds |
| Builds running on the controller | UI slows during builds; security risk | built-in node executors > 0 | Set executors to 0; use agents for everything |
| JENKINS_HOME I/O | Slow startup, slow job loading, long gaps between Pipeline steps | Disk latency, number of build directories | Fast storage, build retention,durabilityHint |
| heavy computation in Pipelines | High-CPU threads whose names include CPS VM | Thread dump | move the computation to sh |
| Massive logs / large artifacts | Disk grows fast; Console Output will not open | du builds directory | Trim logs; store artifacts in an external repository |
| SCM polling and scanning | Background threads busy; many Git processes | Thread dump, Multibranch Scan Log | Switch to webhooks; reduce scan frequency |
How: JVM options (based on CloudBees' “Prepare Jenkins for Support” recommended set)
This knowledge base article gives the baseline parameters for Java 11 / 17 / 21, including: -XX:+AlwaysPreTouch,-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=…,-XX:-OmitStackTraceInFastThrow,-XX:+UseG1GC,-XX:+UseStringDeduplication,-XX:+ParallelRefProcEnabled,-XX:+DisableExplicitGC, as well as GC logging -Xlog:gc*=info,gc+heap=debug,gc+ref*=debug,gc+ergo*=trace,gc+age*=trace:file=…/gc.log:utctime,pid,level,tags:filecount=2,filesize=100M. Heap: for containers / cloud platforms, the recommendation is -XX:InitialRAMPercentage=50.0 -XX:MaxRAMPercentage=50.0; for traditional hosts, set -Xms and -Xmx to the same value,with at least 2 GB, 4 GB or more in production, and about 16 GB at most. The article also requires “only use these parameters unless a support engineer asks for something else.”
Note: the above comes from CloudBees' knowledge base (CloudBees is a major commercial contributor to Jenkins) and applies to the JVM level of open-source Jenkins; the jenkins.io hardware recommendations page does not give specific heap values.
When: build retention and cleanup
- Job-level: Declarative
options { buildDiscarder(logRotator(numToKeepStr: '30', daysToKeepStr: '30', artifactNumToKeepStr: '5')) }, called “Discard old builds” in the UI. - Global: Manage Jenkins → System → Global Build Discarders, you can add “Project Build Discarder” (periodically runs each job's own retention policy) and “Specific Build Discarder” (applies one global policy to all jobs).
- Multibranch: jobs for deleted branches are cleaned up by the Orphaned Item Strategy (Lesson 2).
- Workspace: workspaces on agents are not removed when a build is deleted; clean them up in
post { cleanup { cleanWs() } }(the Workspace Cleanup plugin) ordeleteDir()(the cleanWs step); Kubernetes pod agents are one-off by design.
Common misconceptions
- “Bigger heap is always better” — an oversized heap makes each GC pause longer and recovery slower; beyond about 16 GB, it usually means this controller is taking on too much and should be split (M6).
- “A container limit of 8Gi means setting -Xmx8g” — the JVM also uses metaspace, thread stacks, and direct memory; the heap is only part of container memory (the recommendation above is 50%).
- “Once a Build Discarder is configured, it deletes immediately” — job-level policies run when a build completes; for a large backlog of existing old builds, use Global Build Discarders to process them periodically.
- “cleanWs cleans the controller's disk” — it cleans the agent workspace; the controller's disk is managed by build retention and artifact policies.
Where the controller's memory and disk go
How to read G1GC logs
JENKINS_HOME capacity and heap rough estimator
Enter your scale to see the disk used by build records and how the retention policy changes it. Heap recommendations use the ranges from the CloudBees knowledge base above (2 GB minimum / 4 GB to start in production / about 16 GB upper limit). The disk figures are a teaching estimate, not an official formula.
1. Set executors on the controller to 0
# JCasC (Lesson 5) jenkins: numExecutors: 0 mode: EXCLUSIVE
2. Compose route: JVM options and memory limit
# ~/jenkinslab/compose.yaml (jenkins service snippet)
services:
jenkins:
image: jenkins/jenkins:2.580.2-jdk21
mem_limit: 4g
environment:
JAVA_OPTS: >-
-XX:InitialRAMPercentage=50.0 -XX:MaxRAMPercentage=50.0
-XX:+AlwaysPreTouch -XX:+UseG1GC -XX:+UseStringDeduplication
-XX:+ParallelRefProcEnabled -XX:+DisableExplicitGC
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/jenkins_home/logs
-XX:-OmitStackTraceInFastThrow
-Xlog:gc*=info,gc+heap=debug,gc+ref*=debug,gc+ergo*=trace,gc+age*=trace:file=/var/jenkins_home/logs/gc.log:utctime,pid,level,tags:filecount=2,filesize=100M
mkdir -p ~/jenkinslab && cd ~/jenkinslab docker compose exec jenkins mkdir -p /var/jenkins_home/logs docker compose up -d jenkins && sleep 60 docker compose exec jenkins sh -c 'jcmd -l' # find the PID of jenkins.war docker compose exec jenkins sh -c 'jcmd $(pgrep -f jenkins.war) VM.flags | tr " " "\n" | grep -E "G1|RAMPercentage"'
-XX:InitialRAMPercentage=50.000000 -XX:MaxRAMPercentage=50.000000 -XX:+UseG1GC
-XX:+UnlockDiagnosticVMOptions -XX:+UnlockExperimentalVMOptions and similar options, and specifically says they must not be omitted. This lab uses only the GC / heap subset, so for production, follow the latest version of that article. If the container image does not have pgrep, use the PID from the output of jcmd -l .3. kind route: Helm values
controller:
resources:
requests: { cpu: "1", memory: "4Gi" }
limits: { cpu: "2", memory: "4Gi" }
javaOpts: >-
-XX:InitialRAMPercentage=50.0 -XX:MaxRAMPercentage=50.0
-XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/jenkins_home/logs
-Xlog:gc*:file=/var/jenkins_home/logs/gc.log:utctime,level,tags:filecount=2,filesize=100M
helm upgrade jenkins jenkins/jenkins -n jenkins -f values.yaml --reuse-values kubectl -n jenkins describe pod jenkins-0 | grep -A3 "Last State" # check whether it was OOMKilled
4. Read GC logs and the heap
docker compose exec jenkins sh -c 'grep -E "Pause (Young|Full)" /var/jenkins_home/logs/gc.log | tail -5' docker compose exec jenkins sh -c 'jcmd $(pgrep -f jenkins.war) GC.heap_info'
[2026-11-16T10:02:11.418+0000][1][info][gc] GC(84) Pause Young (Normal) (G1 Evacuation Pause) 1210M->402M(2048M) 18.204ms [2026-11-16T10:05:40.002+0000][1][info][gc] GC(85) Pause Young (Normal) (G1 Evacuation Pause) 1230M->405M(2048M) 17.881ms
5. Build retention and workspace cleanup
pipeline {
agent { label 'linux' }
options {
buildDiscarder(logRotator(numToKeepStr: '30', daysToKeepStr: '30', artifactNumToKeepStr: '5'))
durabilityHint('PERFORMANCE_OPTIMIZED') // when CI builds can accept “not recoverable after restart”
timeout(time: 30, unit: 'MINUTES')
}
stages {
stage('Test') { steps { sh 'pytest -q --junitxml=report.xml' } }
}
post {
always { junit 'report.xml' }
cleanup { cleanWs() } // Workspace Cleanup plugin
}
}
6. Find the jobs that use the most disk
docker compose exec jenkins sh -c 'du -sh /var/jenkins_home/jobs/* 2>/dev/null | sort -rh | head -10'
docker compose exec jenkins sh -c 'find /var/jenkins_home/jobs -maxdepth 3 -type d -name builds -exec sh -c "echo \$(ls \"{}\" | wc -l) {}" \; | sort -rn | head'
Lab: give the controller a health check
numExecutors (should be 0),du -sh /var/jenkins_home,jcmd … GC.heap_info.compose.yaml,docker compose up -d jenkins, and use VM.flags to confirm it takes effect.faultbox (baseline), and watch the GC log.
for i in $(seq 20); do curl -fsS -X POST -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/build?delay=0sec"; done sleep 120; docker compose -f ~/jenkinslab/compose.yaml exec jenkins sh -c 'grep -c "Pause Young" /var/jenkins_home/logs/gc.log'
Think about it: why might 20 triggers be merged into fewer builds in the queue? (If the same job already has a waiting item in the queue, duplicate triggers are merged; disableConcurrentBuilds the remaining ones run one after another.)
faultbox 's Pipeline, add buildDiscarder(logRotator(numToKeepStr: '5')) (you can edit the inject.sh of the pipe() template), build once more, and confirm the builds directory has only about 5 left.jcmd <pid> GC.heap_dump /var/jenkins_home/logs/heap.hprof to generate a dump, and open it in Eclipse MAT to view the Dominator Tree. A heap dump contains secrets from memory; delete it after use.Case 1: controller OOMKilled every afternoon
Controller on Kubernetes: limit 8Gi,-Xmx8g. During the afternoon build peak, the pod was OOMKilled, but the GC log shows the heap used only 6 GB. Root cause: heap + metaspace + thread stacks + direct memory exceeded the container limit and the kernel killed the process (not a Java OutOfMemoryError). Fix: change to -XX:MaxRAMPercentage=50, raise the limit to 12Gi.
Case 2: 400,000 build records make startup take 25 minutes
A 3-year-old controller with no retention policy at all; JENKINS_HOME is 1.8 TB. Remediation: First confirm retention requirements with the compliance team, and export release records that must be kept long term to an artifact repository; enable Global Build Discarders to clean up in batches; afterward, startup time dropped to 3 minutes, and backup time dropped from 6 hours to 40 minutes.
Case 3: “slowness” came from a Groovy loop in one Pipeline
In the thread dump, several Running CpsFlowExecution[Owner[…]] threads were constantly running string processing. Fix: move the parsing logic into a Python script on the agent, and use readJSON to read the result. Controller CPU dropped from 90% to 25%.
Case 4: agent disk filled by workspaces
On a static agent, workspaces for 300 branches accumulated to 400 GB; the disk monitor marked the node offline, and the queue showed All nodes of label ‘linux’ are offline (M2). Fix:post { cleanup { cleanWs() } } into the Shared Library template, and in the long term switch to one-off Kubernetes agents.
Common errors and solutions
java.lang.OutOfMemoryError: Java heap space
Cause: insufficient heap or a memory leak. Diagnosis: If there is -XX:+HeapDumpOnOutOfMemoryError , analyze the generated .hprof; check the GC log for baseline trends. Fix: short term: increase the heap; long term: find the memory hogs (common culprits: too many retained builds being loaded, a plugin's cache, huge Pipelines).
java.lang.OutOfMemoryError: Metaspace
Cause: too much class metadata (many plugins, Groovy script classes continuously generated). Fix: trim plugins; check whether any job keeps generating new script classes; if needed, set -XX:MaxMetaspaceSize just makes the problem surface earlier.
Pod status OOMKilled (Last State: Terminated, Reason: OOMKilled, Exit Code: 137)
Cause: total container memory exceeded the limit, and the kernel killed the process. Fix: set the heap as a percentage and leave headroom (≈50%), or raise the limit.
No space left on device (controller or agent)
Diagnosis:df -h determine whether it is the controller's JENKINS_HOME or the agent workspace / Docker image cache. Fix: retention policies,cleanWs(),docker system prune (on agents, with caution), or expanding storage.
JVM fails to start: Unrecognized VM option 'UseConcMarkSweepGC'
Cause: old Java options were carried over (CMS has been removed from newer JDKs; old -XX:+PrintGCDetails etc. have also been -Xlog replaced). Fix: Rewrite for the current JDK 21 / 25 option set JAVA_OPTS. The exact error text depends on the actual JVM output.
1. Write the Declarative option that keeps the last 20 builds and keeps artifacts only for the last 3 builds.
Reference answer
options { buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '3')) }2. Inside the container, confirm the GC and heap percentage that the controller JVM actually uses.
Reference answer
docker compose exec jenkins sh -c 'jcmd $(pgrep -f jenkins.war) VM.flags | tr " " "\n" | grep -E "Use.*GC|RAMPercentage"'
Scenario analysis question: One controller serves 1,500 jobs and 60 static agents. The heap is already 24 GB, yet it still has several long GC pauses a day. What would you recommend?
Reference answer
Stop the bleeding first: check retention policies and large logs, confirm the controller's executors are 0, analyze the heap dump to find memory hogs, and move heavy computation out of Pipelines. Structurally: 24 GB already exceeds the common recommended cap of about 16 GB, so split the controller into several by team or business line (M6), manage configuration uniformly with JCasC + Helm, and switch agents to elastic Kubernetes pods to reduce persistent connections.
Teaching video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering Jenkins JVM tuning and build retention was found; please refer to the documents and storyboard script below.
Official documentation
- Hardware Recommendations
- Architecting for Scale
- CloudBees KB: Prepare Jenkins for Support (JVM options)
- Scaling Pipelines
- Workspace Cleanup plugin
Video storyboard script
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
Narration: The heap is only part of container memory; set it as a percentage and leave headroom.
Narration: When reading the GC log, look at only two things: whether the post-GC baseline keeps rising, and how long each pause lasts.
Narration: The most effective way to control disk usage is build retention; workspace cleanup happens on the agent.
Module 6 · Reliability: high availability, disaster recovery, and large-scale Jenkins
- Explain the HA limits of open-source Jenkins: there is no native active-active,two controllers cannot share the same JENKINS_HOME at the same time; the options are fast restart (Kubernetes), cold / warm primary-standby switchover, or commercial-product HA.
- Know what backups must include (especially
secrets/andcredentials.xml), and what can be excluded (workspace/, caches), and how to get a consistent backup. - Design RTO / RPO for different failures (pod crash, node failure, accidental data deletion, regional outage) and write a recovery runbook.
- Understand the scaling pattern of “multiple small controllers + configuration as code”, and agent-side reliability measures (one-off agents,
retryconditions).
What: the controller is a stateful single point
All of the controller's state lives in JENKINS_HOME (configuration, jobs, build records, plugins, encryption keys) and memory (queue, running Pipelines, Remoting connections). Open-source Jenkins supports only one controller process per JENKINS_HOME: starting two at once would overwrite each other's files and corrupt data. So in the open-source world, “high availability” really means: shortening recovery time (RTO) and reducing data loss (RPO).
Why: comparison of options
| Option | Mechanism | Typical RTO | Cost / risk |
|---|---|---|---|
| Kubernetes StatefulSet + PVC (Helm chart default) | Pod crash auto-restarts; on node failure, the pod is rescheduled to another node in the same availability zone and the volume is remounted | minutes (including Jenkins startup time) | block storage is usually bound to an availability zone; ineffective for regional outages |
| Primary / standby (cold / warm standby) | storage-level replication or periodic restore to a standby instance; on failure, start the standby and switch DNS | tens of minutes to hours | you must ensure the old primary is stopped; rehearse the switchover |
| Rebuildable controller | JCasC + plugins.txt + Job DSL / Organization Folder: configuration and jobs all come from Git | time to build a new one (minutes) | build history is lost (simplest when acceptable); credentials must be re-injected from an external secrets store |
| Commercial-product HA | For example, CloudBees CI provides active/active high availability | refer to the vendor documentation | License fees; not part of open-source Jenkins |
How: what to back up
| Path | Required? | Notes |
|---|---|---|
secrets/ (includes master.key,hudson.util.Secret , etc.) | Required | Without it,credentials.xml and the encrypted values in the configuration cannot be decrypted. Keep it separate from other data and store it encrypted |
config.xml,*.xml (top level),credentials.xml | Required | Global configuration, credentials (encrypted) |
jobs/ | Required (at least config.xml) | build records: whether to back up in full depends on RPO requirements |
users/,nodes/ | Required | users (including API tokens), static node definitions |
plugins/*.jpi | Recommended | or rebuild from plugins.txt |
workspace/,caches/,war/,.cache | Exclude | regenerable |
Consistency: A running controller keeps writing files. Options: ① filesystem / volume snapshots (CSI VolumeSnapshot, cloud disk snapshots); ② before backup, quiet-down wait for running builds to finish; ③ the ThinBackup plugin (scheduled full / differential backups, which can run when idle). Restores must be rehearsed, otherwise the backup only “looks like it exists”.
When: large-scale Jenkins
- Multiple small controllers: split by team, business line, or security boundary; keep each controller's heap within the commonly recommended ~16 GB (M5); the blast radius of a failure is smaller, and upgrades can be done in batches.
- Configuration as code: each controller = one Helm release + JCasC + plugins.txt (Lesson 5); differences live only in the values file.
- Shared services: unified identity (OIDC / SAML, Lesson 6), a shared Shared Library repository, a shared Kubernetes agent cluster, unified Prometheus metrics and alerts (see Prometheus & Grafana course).
- Agent reliability: one-off pod agents; multiple nodes sharing the same label; in Pipelines,
retry(count: 2, conditions: [agent(), kubernetesAgent()])retries only when the agent is lost, rather than on every failure.
Common misconceptions
- “Two controllers mounting the same NFS share is HA” — it corrupts data; open-source Jenkins does not support this.
- “Backing up jobs/ is enough to recover” — without
secrets/, every credential comes back as garbage. - “It is automatically highly available on Kubernetes” — all builds and the UI are unavailable during a pod restart; whether running Pipelines can recover depends on the durability level and whether the agents are still there.
- “One very large controller is simpler” — it is the biggest single point of failure, and upgrades and restarts affect everyone.
Recovery path comparison
Multi-controller architecture
Failure recovery timeline simulation
Select an architecture and a failure to see the recovery steps and RTO / RPO. The figures are illustrative teaching values (they depend on storage, Jenkins startup time, and staff response); the key point is “which failures a given option simply cannot rescue”.
1. Compose route: consistent backup of JENKINS_HOME
cd ~/jenkinslab && source faults/env.sh
CLI(){ java -jar faults/jenkins-cli.jar -s "$JENKINS_URL" -auth "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
curl -fsS -o faults/jenkins-cli.jar "$JENKINS_URL/jnlpJars/jenkins-cli.jar"
CLI quiet-down -block -timeout 600000 # wait for running builds to finish (up to 10 minutes)
VOL=$(docker volume ls -q | grep -E '(^|_)jenkins_home$' | head -1); echo "$VOL"
mkdir -p ~/jenkins-backups
docker run --rm -v "$VOL":/data:ro -v ~/jenkins-backups:/backup alpine \
tar czf /backup/jh-$(date +%F-%H%M).tgz -C /data \
--exclude=./workspace --exclude=./caches --exclude=./war --exclude=./.cache .
CLI cancel-quiet-down
ls -lh ~/jenkins-backups
jenkinslab_jenkins_home -rw-r--r-- 1 root root 148M Nov 16 11:20 jh-2026-11-16-1120.tgz
secrets/, which is equivalent to a plaintext key for every credential. When uploading to object storage, enable server-side encryption and restrict access; ideally, encrypt secrets/ separately (e.g. age / KMS).2. Restore rehearsal (does not affect the running instance)
docker volume create jh_restore
docker run --rm -v jh_restore:/data -v ~/jenkins-backups:/backup alpine \
sh -c 'tar xzf /backup/$(ls /backup | tail -1) -C /data && chown -R 1000:1000 /data'
docker run -d --name jenkins-restore -p 127.0.0.1:8081:8080 -v jh_restore:/var/jenkins_home \
jenkins/jenkins:2.580.2-jdk21
sleep 90 && curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8081/login
200
Log in http://127.0.0.1:8081, confirm that the jobs and users exist, and open a credential's “Update” page to confirm it can be decrypted (no plaintext is shown, but no error appears). After the rehearsal:
docker rm -f jenkins-restore && docker volume rm jh_restore
-Djenkins.model.Jenkins.slaveAgentPort=-1 or a similar method to close the inbound agent port (adjust to your actual needs).3. kind route: PVCs and snapshots
kubectl -n jenkins get statefulset,pvc # Streaming backup (excluding workspaces) kubectl -n jenkins exec jenkins-0 -c jenkins -- tar czf - -C /var/jenkins_home \ --exclude=./workspace --exclude=./caches . > ~/jenkins-backups/jh-k8s-$(date +%F).tgz # If the cluster has a CSI snapshot controller and VolumeSnapshotClass installed, you can use VolumeSnapshot (kind does not include them by default)
4. Minimal manifest for a rebuildable controller
git repo: platform-jenkins/
values-team-web.yaml # Helm values (image tag, resources, javaOpts, installPlugins)
casc/jenkins.yaml # JCasC: security realm, authorization, cloud, Shared Library, credential references ${SECRET}
jobs/seed.groovy # Job DSL or Organization Folder definition
External: secrets store (Key Vault / Secrets Manager) → Kubernetes Secret → JCasC variables
5. Automatic retry when an agent is lost
pipeline {
agent none
stages {
stage('Test') {
steps {
retry(count: 2, conditions: [agent(), kubernetesAgent()]) {
node('linux') { checkout scm; sh 'pytest -q' }
}
}
}
}
}
agent() The condition comes from Pipeline: Nodes and Processes,kubernetesAgent() comes from the Kubernetes plugin; it retries only when the failure cause is a lost agent, so ordinary test failures are not masked (check the plugin version docs).
Lab: backup → “disaster” → restore, and measure your RTO
tar tzf ~/jenkins-backups/$(ls ~/jenkins-backups | tail -1) | grep -E "^\./(secrets/master.key|credentials.xml|config.xml)$"
./config.xml ./credentials.xml ./secrets/master.key
secrets/ directory, open a credential or use gitea-myapp job, observe how decryption fails (use the actual error message as the reference), and understand why secrets/ must be backed up.jenkins-restore containers and jh_restore volumes; keep or delete backup files according to your security requirements.Case 1: restore succeeded, but all credentials became invalid
The team backed up daily jobs/ and config.xml, and after a disk failure they restored to a new VM; all Pipelines failed because credentials could not be decrypted. Root cause: the backup script excluded the “looks like a cache” secrets/. Fix: reissue tokens from each system and rebuild 40 credentials, which took 2 days. Prevention: the backup manifest is written into the runbook, and quarterly restore rehearsals verify that credentials work.
Case 2: “active-active” NFS setup corrupted configuration
For “high availability,” two VMs mounted the same NFS directory and ran Jenkins simultaneously; a few days later, job configurations overwrote each other and build numbers were duplicated. Fix: switch to single-active + Kubernetes rescheduling + daily snapshots.
Case 3: one controller split into five
A company ran 2,500 jobs on one controller, and every plugin upgrade required company-wide coordinated downtime. It was split into 5 controllers divided by business line (same Helm chart, different values). Upgrades can now go first on one low-risk controller, and a single failure now affects only 20%.
Case 4: regional outage drill
The controller's PVC was located in a single availability zone. During the drill, all nodes in that zone were cordoned, and the Pod could not be scheduled (the volume is bound to its original zone). Improvements: hourly volume snapshots replicated to another region, plus the Git configuration of the rebuildable controller; during a regional outage, rebuild the controller in another region with helm install and restore from the latest snapshot; RTO went from “unrecoverable” to about 45 minutes.
Common errors and solutions
After restore, credential errors or encrypted values in the configuration cannot be read
Cause: Missing or replaced secrets/master.key,secrets/hudson.util.Secret. Fix: restore from a backup taken at the same point in time secrets/; if it has been lost, all secrets must be re-entered. Exact error messages vary by plugin; go by what you actually see.
Pod stuck in Pending on Kubernetes: volume node affinity conflict
Cause: The volume bound to the PVC is in another availability zone, where no nodes are available. Fix: Restore the nodes in that zone, or create a new volume from a snapshot in another zone (RWO block storage cannot be attached across zones). The original K8s event message reads something like 0/3 nodes are available: 3 node(s) had volume node affinity conflict.
The restored instance starts running scheduled builds and deploying to production.
Cause: The backup contains jobs and triggers. Prevention: Run drills on an isolated network; before startup, disable triggers via JCasC / system properties or put the instance into quiet down; do not let the drill instance have a network path to production deployment credentials.
Backup file corrupted / tar: Unexpected EOF
Cause: Files were modified during the backup, or the disk filled up. Fix: Use a snapshot or quiet down; after the backup, use tar tzf to verify and record the checksum.
After upgrading the Helm release, the controller fails to start, and rolling back the chart does not help either
Cause: The new version has migrated the data in JENKINS_HOME (plugin or core upgrade), which the old image cannot read. Fix: Rollback = old image + volume snapshot taken before the upgrade; the two must go together (M4).
1. Write the tar command to back up /var/jenkins_home but exclude the workspace and cache.
Reference answer
tar czf jh-$(date +%F).tgz -C /var/jenkins_home --exclude=./workspace --exclude=./caches --exclude=./war .
2. Use the Jenkins CLI to enter quiet down before the backup, waiting at most 10 minutes.
Reference answer
java -jar jenkins-cli.jar -s "$JENKINS_URL" -auth "admin:$JENKINS_TOKEN" quiet-down -block -timeout 600000
Scenario analysis question: The boss requires “Jenkins must not be down for more than 15 minutes, and at most 1 hour of data may be lost.” How would you design it?
Reference answer
Run on Kubernetes (single-replica StatefulSet + PVC) to cover Pod and node failures (minutes); take a volume snapshot every hour and replicate it to a second availability zone / region to meet the 1-hour RPO; keep all configuration in Git (Helm values + JCasC + plugins.txt), with credentials sourced from an external secrets store; in a regional failure, deploy in the standby region and restore from the snapshot; drill every quarter and measure the real RTO; also note that open-source Jenkins has no active-active mode, so if “zero-downtime upgrades” are required, evaluate a commercial solution or split the controllers to reduce the impact.
Instructional video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video specifically covering open-source Jenkins backup, restore and HA design was found; please refer to the official documentation and storyboard script below.
Official documentation
- Backing-up/Restoring Jenkins
- Architecting for Scale
- ThinBackup plugin
- Installing Jenkins on Kubernetes
- retry step
Video storyboard script
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: In open-source Jenkins, each JENKINS_HOME can have only one controller.
Narration: The key to a backup is not the jobs but the secrets that can decrypt the credentials.
Narration: When the scale grows, split it: same template, different configuration, so a failure or upgrade affects only a small group of people.
Module 7 · Migration: Jenkins to GitHub Actions / Azure Pipelines
- Plan the migration in the order “inventory → forecast → trial conversion → migrate → run in parallel → decommission”, and know which cases should keep Jenkins.
- Configure and run the GitHub Actions Importer's
audit,forecast,dry-run,migrate(Jenkins source), and know its prerequisites (Docker, gh CLI, Jenkins API token, GitHub PAT; forecast requires the Paginated Builds plugin). - Remember the Importer's support boundaries for Jenkinsfile:
docker,stagesupported;agent,environment,stages,steps,triggers,whenpartially supported;inputs,matrix,options,parametersnot supported; Scripted Pipeline, secrets, self-hosted runners and unknown plugins need manual handling. - Be able to manually map common Jenkinsfile structures to GitHub Actions and Azure Pipelines YAML.
What: the migration covers more than the Jenkinsfile
Behind a Jenkins job there are: Pipeline code, Shared Library, plugin-provided steps, credentials, agent labels and tools, triggers (webhooks, schedules, upstream jobs), approvals (input), build history and artifacts, and notifications. Migration means finding the equivalent on the target platform for each item; code conversion is only one of them.
Why: migrate or not
| Good candidates for migration | Consider keeping Jenkins |
|---|---|
| Code already in GitHub / Azure Repos; Declarative Pipeline with simple logic; you want to reduce controller operations and plugin upgrade burden | Heavy use of Scripted Pipeline and complex Shared Libraries; dependence on special plugins; need to access many dedicated agents on an isolated network; compliance requires build history to stay in the original system |
How: GitHub Actions Importer (Jenkins source)
- Prerequisites: Docker is running; install the gh CLI and its extension
gh extension install github/gh-actions-importer; Jenkins API token (must be able to access all jobs to be migrated / audited); GitHub classic PAT (workflowscope; creating a PR also requiresrepo);forecastInstall the Paginated Builds plugin (paginated-builds). The Importer does not need to run on the Jenkins server, but it must be able to reach it. - configure: interactive write
.env.local(JENKINS_ACCESS_TOKEN,JENKINS_INSTANCE_URL,JENKINS_USERNAME,GITHUB_ACCESS_TOKEN,GITHUB_INSTANCE_URL, optionalJENKINSFILE_ACCESS_TOKEN); update pull the latest Importer container image. - audit: converts all jobs on the server and outputs
audit_summary.md(the proportions of success / partial success / unsupported / failed, plus the secrets and runners that need manual handling), as well asworkflow_usage.csv. - forecast: estimates GitHub Actions usage (job count, duration, concurrency) based on builds completed in the last 7 days (default).
- dry-run: converts a single job into a workflow file and writes it locally, without opening a PR; for Jenkinsfile and multibranch jobs, you can use
--source-file-pathto specify a local file. - migrate: converts it and opens a PR in the target repository for review; merge after the secrets and manual items are completed.
When: what about Azure Pipelines?
GitHub Actions Importer only targets GitHub Actions; there is no official automatic conversion tool from Jenkins to Azure Pipelines, and Microsoft's documentation only provides conceptual mappings (agent → pool, stage → stage, steps → steps, post → condition, etc.). During the transition, both can coexist: Azure Pipelines uses the Jenkins service connection and JenkinsQueueJob@2 tasks to trigger Jenkins jobs, or Azure DevOps service hooks to notify Jenkins, migrating orchestration first and builds later (for details, see Azure DevOps course).
Common misconceptions
- “The Importer can migrate 100% automatically”—it explicitly lists Scripted Pipeline, secrets, self-hosted runners and unknown plugins as manual tasks;
matrix,parameters,input,optionsare not supported. - “Audit just reads data”—it attempts a conversion of every job and downloads its configuration; with many jobs it can take a long time, and the token needs the appropriate permissions.
- “Just copy Jenkins’ cron over”—Jenkins’
H(hash) syntax does not exist in GitHub Actions or Azure Pipelines; time zones also differ (cron in GitHub Actions and Azure Pipelines uses UTC). - “Shut down Jenkins once migration is done”—first run both in parallel for a while, compare results and durations, and only then decommission Jenkins and archive the build history.
Migration flow
Conceptual mapping
| Jenkins | GitHub Actions | Azure Pipelines |
|---|---|---|
| controller + agent (labels) | GitHub-hosted runner / self-hosted runner (labels) | Microsoft-hosted agent / self-hosted agent pool (demands) |
stage | jobs.<id> (needs order of expression) | stages / jobs |
sh | run | script / bash |
environment | env | variables |
Credentials + withCredentials | Secrets / OIDC | secret variables, variable groups, service connections |
when | if | condition |
post { always / failure } | if: always() / failure() | condition: always() / failed() |
input | Environment required reviewers | Environment approvals and checks |
archiveArtifacts / stash | actions/upload-artifact / download-artifact | Pipeline artifacts (publish / download) |
| Shared Library | reusable workflows, composite actions | Templates (template / extends) |
parameters | workflow_dispatch.inputs | Runtime parameters |
Syntax mapper: click a Jenkinsfile structure
The left side shows a Jenkinsfile snippet; the right side shows the equivalent in GitHub Actions and Azure Pipelines, plus the support status of that structure in the GitHub Actions Importer documentation.
1. Install and configure the Importer
gh auth login # skip if already logged in gh extension install github/gh-actions-importer gh actions-importer update # pull the latest Importer container image gh actions-importer configure # choose Jenkins, then enter the two tokens, two URLs and the Jenkins username when prompted
# Equivalent .env.local (generated by configure; do not commit to Git) JENKINS_ACCESS_TOKEN=<Jenkins API token> JENKINS_INSTANCE_URL=http://host.docker.internal:8080 JENKINS_USERNAME=admin GITHUB_ACCESS_TOKEN=<classic PAT: workflow (repo also needed to open PRs)> GITHUB_INSTANCE_URL=https://github.com
127.0.0.1:8080 points to the container itself. On Docker Desktop you can use host.docker.internal; on Linux, use a host address reachable from the Docker network (for example the docker0 bridge IP) and adjust the compose port bindings accordingly. Follow your actual Docker network setup,do not expose Jenkins to the public internet.2. Inventory and forecast
gh actions-importer audit jenkins --output-dir tmp/audit sed -n '1,40p' tmp/audit/audit_summary.md # forecast requires installing the paginated-builds plugin in Jenkins first gh actions-importer forecast jenkins --output-dir tmp/forecast
# Audit summary Pipelines: 3 Successful: 1 (33%) Partially successful: 1 (33%) Unsupported: 1 (33%) Manual tasks Secrets: 1 (REGISTRY_CREDS) Self hosted runners: 1 (linux)
3. Trial-convert a single job
gh actions-importer dry-run jenkins \
--source-url "$JENKINS_URL/job/myapp/" \
--output-dir tmp/dry-run
# Multibranch / Jenkinsfile: use a local file instead of reading from SCM
gh actions-importer dry-run jenkins --source-url "$JENKINS_URL/job/myapp/" \
--source-file-path ./Jenkinsfile --output-dir tmp/dry-run
find tmp/dry-run -name "*.yml" -print -exec sed -n '1,40p' {} \;
Lesson 2, Module 7 created a multibranch job myapp-multibranch (and disabled the myapp); to view its builds, replace the URL with a branch, for example $JENKINS_URL/job/myapp-multibranch/job/main/.
4. Migrate (open a PR)
gh actions-importer migrate jenkins \ --target-url https://github.com/<owner>/myapp \ --source-url "$JENKINS_URL/job/myapp/" \ --output-dir tmp/migrate gh pr list -R <owner>/myapp
5. Manual mapping example: myapp's Jenkinsfile → GitHub Actions
# .github/workflows/ci.yml
name: ci
on:
push: { branches: [main] }
pull_request:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
container: python:3.12-slim
steps:
- uses: actions/checkout@v4
- run: pip install -r requirements.txt pytest
- run: pytest -q --junitxml=report.xml
- uses: actions/upload-artifact@v4
if: always()
with: { name: test-report, path: report.xml }
image:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: docker build -t myapp:${{ github.sha }} .
For the action's major version, follow the GitHub course and the current Marketplace version; for image push and OIDC login to cloud platforms, see GitHub course.
6. Manual mapping example: the same pipeline → Azure Pipelines
# azure-pipelines.yml
trigger: [main]
pr: [main]
stages:
- stage: Test
jobs:
- job: test
pool: { vmImage: ubuntu-latest }
container: python:3.12-slim
timeoutInMinutes: 30
steps:
- script: pip install -r requirements.txt pytest && pytest -q --junitxml=report.xml
- task: PublishTestResults@2
condition: always()
inputs: { testResultsFiles: report.xml }
- stage: Image
dependsOn: Test
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
jobs:
- job: build
pool: { vmImage: ubuntu-latest }
steps:
- script: docker build -t myapp:$(Build.SourceVersion) .
Lab: run an audit + dry-run against a local Jenkins
gh auth status is working properly; create a dedicated Jenkins API token (revoke it when the lab ends); prepare a test repository on GitHub (it can be a lab/myapp GitHub mirror of it, or an empty repository).docker run --rm curlimages/curl -s -o /dev/null -w "%{http_code}\n" http://host.docker.internal:8080/loginfaultbox,myapp etc., inventory the jobs, and read audit_summary.md 's “Manual tasks” section, and list the Secrets and runner labels that need to be created manually.myapp, and compare it with the manual version in section 5 of “Commands”: which steps were converted into run? Credential references turned into what? agent { label 'linux' } turned into what runs-on?tmp/ and .env.local; close the test PR.Case 1: the “real migration cost” revealed by audit
A company had 600 jobs. The audit results were 45% successful, 30% partially successful and 25% unsupported (mainly Scripted Pipeline and an in-house plugin). Based on this, they split the work into three batches: the first, fully automated, was migrated directly with migrate; the second, partially successful, was reviewed PR by PR by each team; the third first rewrote Scripted Pipelines as Declarative or kept them on a smaller Jenkins.
Case 2: forecast prevented a runner capacity incident
forecast showed a weekday peak of 85 concurrent jobs at 10 a.m., while only 20 self-hosted runners were planned. The team switched to GitHub-hosted runners plus a few self-hosted runners with dedicated network access, and set up concurrency.
Case 3: a gradual route to Azure Pipelines
For a team whose code is in Azure Repos and whose deployment approvals are already in Azure DevOps, first use JenkinsQueueJob@2 to have Azure Pipelines orchestrate and trigger the existing Jenkins builds, then rewrite the stages one by one as native YAML, decommission Jenkins three months later, and keep the release process uninterrupted in the meantime.
Case 4: the cron time zone trap
Jenkins’ H 2 * * * (controller time zone set to Toronto) was changed directly to 0 2 * * *, so the nightly job ran at 9 p.m. local time (2 a.m. UTC) and affected the database during the day. Lesson: When migrating scheduled triggers, explicitly convert the times to UTC and add a comment.
Common errors and fixes
Importer fails to connect to Jenkins (connection refused / timeout)
Cause: The Importer runs in a container,127.0.0.1 points to the container itself. Fix: Use an address reachable from the container (see section 1 of “Commands”); check the firewall and the Jenkins reverse proxy. Error wording may vary, so refer to the actual output.
Many jobs show “Unsupported” or “Failed” in the audit
Cause: Scripted Pipeline, unknown plugins, or the token lacks access to some folders (when folders do not inherit permissions, explicit authorization is required). Diagnosis: Check the error stack and network response for each job in the output directory.
forecast is slow or times out
Cause: The Paginated Builds plugin is not installed, and the job build history is too large. Fix: Install the paginated-builds plugin and retry.
The converted workflow run fails: secret not found / runner stays queued
Cause: The Secrets and self-hosted runner labels listed under Manual tasks in the audit must be created manually. Fix: Create the Secrets in the repository / organization; register a runner with the matching label, or change runs-on to a GitHub-hosted runner (the queued-runner symptom is similar to Jenkins’ “There are no nodes with the label”).
migrate cannot create a PR
Cause: The GitHub PAT is missing the repo / workflow scope, or the organization has enabled SSO and the token is not authorized. Fix: Regenerate the classic PAT and authorize SSO for the organization.
1. Run an audit on the Jenkins instance and write the results to tmp/audit.
Reference answer
gh actions-importer audit jenkins --output-dir tmp/audit
2. Write the Jenkins post { failure { … } } conditions in GitHub Actions and Azure Pipelines, respectively.
Reference answer
# GitHub Actions (step or job) if: failure() # Azure Pipelines condition: failed()
Scenario analysis question: The CTO wants to “migrate everything to GitHub Actions” within one quarter. What plan and risks would you propose?
Reference answer
Weeks 1–2: audit + forecast; batch the work by conversion result and business importance; decide the runner strategy (hosted / self-hosted / network access) and the secrets approach (OIDC preferred). Weeks 3–8: migrate + review for the auto-convertible batches; rewrite Shared Libraries as reusable workflows; teams fill the gaps in the partially successful batches. Weeks 9–12: run in parallel and compare, gradually turn off Jenkins triggers, and archive the build history. Risks: Scripted Pipeline and in-house plugins, deployment targets on isolated networks, cron time zones, approval workflow changes, concurrency peaks and billing; keep a smaller Jenkins to handle jobs that cannot be migrated yet.
Instructional video (title and channel verified via YouTube oEmbed, 2026-11-16)
Official documentation
- Migrating from Jenkins with GitHub Actions Importer
- Manually migrating from Jenkins to GitHub Actions
- github/gh-actions-importer
- Migrate from Jenkins to Azure Pipelines
- Paginated Builds plugin
Video storyboard script (supplementary)
Narration: Migration is a process, not a single command.
Narration: The audit tells you the real migration cost and what must be prepared by hand.
Narration: The concepts map one to one, but cron, approvals and plugins require human judgment.
Module 8 · Mixed-failure blind box
~/jenkinslab (or kind lab) open the blind box for real- Faced with an unknown failure, use the five-layer localization method to identify the layer within 2 minutes, and provide the evidence (verbatim) and the fix.
- Be proficient with this lesson's toolchain:
why.sh,consoleText, queue / node API, read-only Script Console queries, controller logs, Script Approval, plugin alerts. - Write a five-part incident record: “symptom → evidence → root cause → fix → prevention”.
The 8 failures in the blind box
| # | Failure | Layer | First symptom | Key evidence (verbatim) | Fix |
|---|---|---|---|---|---|
| F1 | Mistyped label | ② Queue | Build shows “running” but does not move | There are no nodes with the label ‘linux-dokcer’ | Change back to linux |
| F2 | Agent offline (Compose) / Pod quota (kind) | ②③ | Same as above | All nodes of label ‘linux’ are offline; kind: exceeded quota Event | Start the agent / delete the quota |
| F3 | Executors exhausted | ② Queue | Same as above | Waiting for next available executor on ‘linux’, busy = total | End placeholder builds / restore the executor count |
| F4 | Concurrency disabled | ② Queue (blocked) | New builds queue greyed out | Build #N is already in progress (ETA: …) | Wait / abort the previous / abortPrevious |
| F5 | Non-serializable object | ④ Engine | Build failed, Java stack trace | java.io.NotSerializableException: java.util.regex.Matcher | @NonCPS / set to null |
| F6 | Sandbox rejected | ④ Engine | Build failed | RejectedAccessException: Scripts not permitted to use staticMethod … execute java.lang.String | switch to sh(returnStdout: true) |
| F7 | Dependency plugin disabled | Cross-cutting (plugin) | Build failed + red warning in Manage Jenkins | No such property: docker for class: groovy.lang.Binding; Required plugin is disabled: Docker Commons (docker-commons) | Enable the plugin and restart |
| F8 | Misspelled method name | ④ Engine | Build failed | MissingMethodException: No signature of method: java.lang.String.toUppercase() | toUpperCase() |
Blind box rules
- Do not look at
.fault-answer, do not look atfaultbox's configuration (in a real incident you usually don't know what was changed). - First write down your diagnosed layer and the reasoning, then gather evidence; change only one thing at a time and verify.
- Timing: 2 minutes per question in the simulator; 10 minutes per failure in the real environment.
- After finishing, write the five-part record; use
./reset.shto restore, then open the next one.
Summary of preventive measures
- Treat labels as an API; unify their
agentdeclaration in the Shared Library (F1). - Alert on agent health and queue wait time; align Kubernetes quotas with Pod template requests (F2, F3).
- Give all Pipelines a
timeout,inputso that waiting does not occupy an executor (F3, F4). - The Shared Library provides @NonCPS utility methods and unit tests; the Declarative Linter runs as a PR check (F5, F8).
- Changes to Script Approval go through review; do not approve dangerous signatures (F6).
- Plugin manifest as code + staging environment (F7).
Quick diagnosis from symptom to layer
In-browser blind box simulator
Click “Open blind box” to draw a failure at random. Read the symptoms and evidence, then choose the failure type you think it is. Scores are saved only in this browser.
Blind box toolkit (in order of use)
cd ~/jenkinslab/faults && source env.sh
./inject.sh random # open blind box
./why.sh # queue / nodes / recent builds / plugin failures, all in one view
J(){ curl -fsS -u "$JENKINS_USER:$JENKINS_TOKEN" "$@"; }
J "$JENKINS_URL/job/faultbox/lastBuild/consoleText" | grep -nE "Exception|Error|waiting|offline|label|progress" | head
docker compose -f "$COMPOSE_FILE" ps # is agent1 running?
docker compose -f "$COMPOSE_FILE" logs --since 10m jenkins | grep -E "SEVERE|Failed" | head
kubectl -n jenkins get events --sort-by=.lastTimestamp | tail # kind route
J --data-urlencode 'script=org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().pendingSignatures.each{ println it.signature }' "$JENKINS_URL/scriptText"
./reset.sh # restore
Five-part incident record template
## Incident: faultbox build #12 did not run - Symptom: build showed running for 9 minutes, log stuck at Still waiting to schedule task - Evidence: /queue/api/json → why = "There are no nodes with the label ‘linux-dokcer’" - Root cause: agent label misspelled in the Jenkinsfile (layer: ② Queue) - Fix: changed to label 'linux', reran #13 SUCCESS (took 32 seconds) - Prevention: the Shared Library provides standardAgent(); add a label allowlist check to PR checks
Lab: real-environment blind box challenge
./reset.sh after faultbox is green../inject.sh random, start the 10-minute timer. Do not look at .fault-answer.why.sh and the build log to gather evidence, and write down the layer and the verbatim evidence.faultbox to verify it turns green. F7 requires restarting the controller, about 1 minute.cat .fault-answer Verify, and write the five-part record../reset.sh, complete at least 4 rounds, covering at least 3 different layers (queue, engine, plugin).jenkins namespace a ResourceQuota, so be sure to reset.sh delete it.Case: a real “Monday morning”
09:05 several teams reported that “builds are not starting”. The on-call engineer checked the queue first: every entry's reason was Jenkins is about to shut down—the Friday evening plugin upgrade runbook had only run Prepare for shutdown, and the restart was postponed. After canceling quiet down, the queue recovered (M2). At 09:20 another team reported No such property: docker—Friday's upgrade disabled the old version of Docker Commons but the new version was not installed, and a warning appeared at the top of Manage Jenkins Required plugin is disabled (M4). After installing it and restarting safely, everything recovered by 09:40. Prevention items from the postmortem: add two mandatory steps to the upgrade runbook, “cancel quiet down / check plugin warnings”; and put quietingDown and the number of plugin load failures under monitoring.
This case shows that multiple symptoms may have multiple independent root causes; rule them out layer by layer, and do not assume “it's all the same problem”.
Interactive troubleshooting tree
Start from a symptom, answer the questions step by step, and get the diagnostic commands and fix suggestions. Covers the main failures in M1–M7 of this lesson.
1. Determine with one command faultbox whether the build is “queued” or “failed”.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" "$JENKINS_URL/job/faultbox/api/json?tree=inQueue,lastBuild[number,building,result]" | jq -c .
2. List all sandbox signatures currently pending approval.
Reference answer
curl -fsS -u "admin:$JENKINS_TOKEN" --data-urlencode 'script=org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().pendingSignatures.each{ println it.signature }' "$JENKINS_URL/scriptText"Scenario analysis question: The build log only contains groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding, and the Jenkinsfile has not changed in a month. Which layer is the root cause most likely in? How would you prove it?
Reference answer
The Jenkinsfile did not change, yet the global variable docker disappeared, which means the Docker Pipeline plugin that provides it did not load—the root cause is in the plugin layer (M4). Proof: the dependency error warning at the top of Manage Jenkins,pluginManager.failedPlugins the output of Failed to load: Docker Pipeline … in the controller log, as well as recent plugin change records. Fix the dependency (enable / upgrade Docker Commons) and restart.
Instructional video (title and channel verified via YouTube oEmbed, 2026-11-16)
No verified video on the “Jenkins failure blind box / comprehensive troubleshooting” topic was found; please refer to the documentation for each module of this lesson and the storyboard script below.
Video storyboard script
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: Question one: did it fail, or never start at all?
Narration: If it never started, check the queue reason; it usually tells you the answer directly.
Narration: If it failed, look at the exception class name: serialization, sandbox, method not found, property not found; each belongs to its own layer.
Narration: After fixing it, write down the evidence and prevention measures; that is the end point of troubleshooting.
Command cheat sheet
curl -u admin:$T $URL/job/JOB/lastBuild/consoleText | tail docker compose logs --since 15m jenkins kubectl -n jenkins logs jenkins-0 -c jenkins --previous curl -u admin:$T $URL/threadDump -o td.html # UI: /manage/log /manage/systemInfo Support (support-core) curl -u admin:$T --data-urlencode 'script=...' $URL/scriptText
curl -u admin:$T "$URL/queue/api/json?tree=items[why,stuck,blocked,task[name]]" curl -u admin:$T "$URL/computer/api/json?tree=busyExecutors,totalExecutors,computer[displayName,offline,offlineCauseReason]" curl -u admin:$T "$URL/label/linux/api/json" java -jar jenkins-cli.jar ... offline-node|online-node|connect-node agent1 java -jar jenkins-cli.jar ... cancel-quiet-down curl -X POST .../job/JOB/N/stop|term|kill
@NonCPS String f(String s) { /* Matcher etc. are only used here */ }
def out = sh(script: 'cmd', returnStdout: true).trim()
def cfg = readJSON file: 'x.json'
options { durabilityHint('PERFORMANCE_OPTIMIZED') }
// Linter: POST /pipeline-model-converter/validate -F jenkinsfile=<JenkinsfileJenkins.get().pluginManager.failedPlugins # Script Console
jenkins-plugin-cli --plugin-file plugins.txt --available-updates --no-download
java -jar jenkins-cli.jar ... disable-plugin|enable-plugin NAME -restart
ls $JENKINS_HOME/plugins/*.{disabled,bak}JAVA_OPTS: -XX:MaxRAMPercentage=50.0 -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError
-Xlog:gc*:file=/var/jenkins_home/logs/gc.log:utctime,level,tags:filecount=2,filesize=100M
jcmd PID VM.flags | GC.heap_info | Thread.print
options { buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')) }
post { cleanup { cleanWs() } }java -jar jenkins-cli.jar ... quiet-down -block -timeout 600000
tar czf jh.tgz -C /var/jenkins_home --exclude=./workspace --exclude=./caches .
tar tzf jh.tgz | grep secrets/master.key
retry(count: 2, conditions: [agent(), kubernetesAgent()]) { ... }gh extension install github/gh-actions-importer gh actions-importer update | configure gh actions-importer audit jenkins --output-dir tmp/audit gh actions-importer forecast jenkins --output-dir tmp/forecast gh actions-importer dry-run jenkins --source-url URL --output-dir tmp/dry-run gh actions-importer migrate jenkins --target-url https://github.com/O/R --source-url URL --output-dir tmp/migrate
cd ~/jenkinslab/faults ./inject.sh random # or F1..F8 ./why.sh ./reset.sh
Original error text → which module
| Original keywords | Module |
|---|---|
There are no nodes with the label · are offline · Waiting for next available executor · is already in progress · Jenkins is about to shut down · In the quiet period | M2 |
Ping started at … hasn't completed by · ChannelClosedException · seems to be removed or offline | M2 |
NotSerializableException · expected to call … but wound up catching · RejectedAccessException · MissingMethodException · No such DSL method | M3 |
Failed to load · Update required · or higher required · Required plugin is disabled · Plugin is missing | M4 |
OutOfMemoryError · OOMKilled · No space left on device | M5 |
Capstone lab + final quiz
You have just taken over the company's Jenkins platform. The team complains: ① builds “often mysteriously don't start”; ② plugin upgrades keep causing problems; ③ management asks “how long until the controller recovers if it goes down?”; ④ some teams want to migrate to GitHub Actions. Complete the tasks below on the ~/jenkinslab (or kind lab) and deliver a report.
faults/ script and M1's why.sh,faultbox and confirm it is green../inject.sh random At least 4 rounds (covering the queue, engine and plugin layers); fix each within 10 minutes and write a five-part record; accuracy ≥ 75% in the browser simulator./queue/api/json every minute, and for entries waiting more than 5 minutes outputs their name and why.
J "$JENKINS_URL/queue/api/json?tree=items[inQueueSince,why,task[name]]" | jq -r --argjson now "$(date +%s)000" '.items[] | select(($now - .inQueueSince) > 300000) | "\(.task.name)\t\(.why)"'
plugins.txt (pinned versions), then use jenkins-plugin-cli --available-updates to list upgradable items and write the plan for the next upgrade (rehearsal, backup, rollback).faultbox and myapp add buildDiscarder and cleanWs(); record the JENKINS_HOME size before and after.Open-ended self-check
1. Why might a Pipeline build show “running” while it is actually queued?
The Pipeline first runs on the controller using a flyweight executor,node / agent block then requests an agent executor as a separate queue item (part of … #N); when the log stops at Still waiting to schedule task, the problem is in the second item.
2. List the four stages of a queue item and one original reason for each stage.
waiting: In the quiet period. Expires in …; blocked: Build #N is already in progress / Jenkins is about to shut down; buildable: There are no nodes with the label / All nodes of label … are offline / Waiting for next available executor; pending → left: executor assigned.
3. Why does NotSerializableException appear only at certain times?
It fails only when program state is persisted at a step boundary while a non-serializable object is in scope; different code paths and persistence levels expose it at different times.
4. When a sandbox rejection occurs, why is “approve” usually not the best choice?
Approval is global: dangerous signatures (execute, Jenkins.instance, etc.) would give everyone who can modify the Jenkinsfile controller-level permissions; prefer rewriting with steps, or put the logic in a trusted global Shared Library.
5. Why is it recommended that the controller heap not exceed about 16 GB?
A large heap brings longer GC pauses and slower startup / recovery; beyond this size, one controller usually carries too many jobs, and splitting it reduces risk and impact radius more effectively.
6. What can't the Importer do for you when migrating to GitHub Actions?
Scripted Pipeline, secrets, self-hosted runners and unknown plugins must be handled manually; matrix, parameters, input and options are not supported; you still need to judge cron time zones, approval flows, concurrency and costs by hand, and plan parallel runs and decommissioning.
Sources and version notes
| Topic | Verification conclusion | Source (verification date) |
|---|---|---|
| Jenkins version | LTS 2.580.2 (2026-10-28, tested with JDK 21 / 25); 2.580.1 (2026-09-30); weekly 2.590; Java 17 is not supported from 2.555.1 onward | LTS Changelog, updates.jenkins.io latestCore (2026-11-16) |
| Original queue reason: | Queue.LabelHasNoNodes,Queue.AllNodesOffline,Queue.NodeOffline,Queue.WaitingForNextAvailableExecutorOn,Queue.InQuietPeriod,Queue.HudsonIsAboutToShutDown,Node.BecauseNodeIsReserved,BlockedBecauseOfBuildInProgress.shortDescription (Build #{0} is already in progress{1}); CauseOfBlockage Class structure | core hudson/model/Messages.properties, jenkins/model/Messages.properties, CauseOfBlockage.java (master branch, 2026-11-16) |
| Throttle plugin | Already running {0} builds across all nodes / on node; version 625.vc8b_e469e9a_b_c | throttle-concurrent-builds-plugin Messages.properties; plugins.jenkins.io (2026-11-16) |
| ping thread | ChannelPinger default timeout 240 seconds, interval 300 seconds; system property …ChannelPinger.pingTimeoutSeconds / pingIntervalSeconds; remoting PingThread message Ping started at … hasn't completed by … | jenkinsci/jenkins ChannelPinger.java, jenkinsci/remoting PingThread.java (2026-11-16) |
| Pipeline waiting for node | … seems to be removed or offline …; will wait for … for it to come back online; default 5 minutes, property org.jenkinsci.plugins.workflow.support.pickles.ExecutorPickle.timeoutForNodeMillis; Timeout waiting for agent to come back; Still waiting to schedule task | workflow-durable-task-step-plugin DurableTaskStep.java, ExecutorStepExecution.java (2026-11-16) |
| CPS mismatch | Message format expected to call X but wound up catching Y; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/; five scenarios and toSorted examples | workflow-cps CpsVmExecutorService.java;CPS method mismatches(2026-11-16) |
| DSL / sandbox | No such DSL method '…' found among steps (NoSuchMethodError); Scripts not permitted to use {type} {details}; original approval prompt text | workflow-cps DSL.java; script-security RejectedAccessException.java, scripts/Messages.properties (2026-11-16) |
| Plugin load failure | Failed to load,Update required … to be updated to … or higher,Jenkins ({1}) or higher required,Required plugin is disabled,Plugin is missing; administrative monitor Some plugins could not be loaded due to unsatisfied dependencies… | core hudson/Messages.properties, PluginWrapper.java, PluginWrapperAdministrativeMonitor/message.properties (2026-11-16) |
| Plugin versions | workflow-cps 4403.v471713a_cea_19 (core ≥ 2.568.1); script-security 1436.v1082791135e4; support-core 1876.va_195a_b_645f3f; docker-workflow 653.v2f2c08eff0ec (docker-commons ≥ 477.v289085a_b_6896); git 5.11.0 (git-client ≥ 6.5.0); credentials 1514.vb_01eb_014e7d4 (core ≥ 2.555.3); prometheus 873.v054598e6e84d; kubernetes 4560.vc25b_83890c34; configuration-as-code 2147.v8a_8d38668c72; thinBackup 2.1.5; ws-cleanup 0.49; paginated-builds 1.083.v5f614a_e66715 | plugins.jenkins.io API (2026-11-16) |
| Tools and chart | Plugin Installation Manager Tool 2.16.0 (--available-updates,--no-download,--war,--output,--hide-security-warnings); jenkinsci Helm chart 5.13.3 (controller.javaOpts,installPlugins,installLatestPlugins) | GitHub releases and README / values.yaml (2026-11-16) |
| Hardware and JVM | controller memory 200 MB to 70 GB+; each agent connection uses 2–3 threads, about 2 MB; executors are not recommended on the controller; JVM parameter set, heap 2 / 4 / 16 GB, RAMPercentage 50 | Hardware Recommendations;CloudBees KB Prepare Jenkins for Support(2026-11-16) |
| Build retention | BuildDiscarderProperty (Discard old builds), and the “Project Build Discarder” / “Specific Build Discarder” of Global Build Discarders | core Messages.properties (2026-11-16) |
| GitHub Actions Importer | Prerequisites (Docker, gh, Jenkins API token, classic PAT workflow, forecast requires paginated-builds); commands configure / update / audit / forecast (default 7 days) / dry-run / migrate; environment variables; support table (docker and stage supported; agent, environment, stages, steps, triggers, when partially; inputs, matrix, options, parameters not supported); --source-file-path,--config-file-path; output audit_summary.md,workflow_usage.csv | GitHub Docs: Jenkins migration(2026-11-16) |
Video verification notes
All the videos below were checked via the YouTube oEmbed API (https://www.youtube.com/oembed?url=…&format=json, 2026-11-16), with titles and channels verified: DevOps Journey “Learn Jenkins! Complete Jenkins Course - Zero to Hero” (6YZvp2GwT0A); TechWorld with Nana “Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4” (pMO26j2OUME) and “Complete Jenkins Pipeline Tutorial | Jenkinsfile explained” (7KCS70sCoK0); Simplilearn “Jenkins Full Course …” (FX322RVNGj4) and “What Is Jenkins? …” (LFDrDnKPOTg); freeCodeCamp.org “Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course)” (f4idgaq2VqA); Ethan Dennis “Jenkins migrations powered by GitHub Actions Importer” (WqiGP6h4fa0, link from GitHub Community discussion #48913). Durations, upload dates and content details were not verified one by one. For topics in each module with no directly matching video, the module states “no verified video found” and provides a storyboard script.
Audio narration notes
The “Audio” tab reads the narration script aloud using the browser's Web Speech API (en-US), with English terms pronounced in en-US; results depend on the speech packs installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; the narration script can be used directly as a recording script.
Known limitations
- None of the commands in this lesson were actually run in this environment; the build numbers, timestamps, PIDs, sizes and durations in the “expected output” are sample values.
- The original error texts are taken from the source message templates; combined output (for example, in the Pipeline log
Still waiting to schedule taskthe layout of the reason line, the prefix lines of the plugin load failure log, the stack details of NotSerializableException,Possible solutionslines, and the full format of ChannelClosedException) are written in common forms and marked “verify against actual output”. - The menu location of Support Core,
disableConcurrentBuilds(abortPrevious: true)the availability ofretryand theconditionsbehavior, and the label key names the Kubernetes plugin applies to Pods, vary between versions; refer to the documentation for the version in use. - The JVM parameters come from the CloudBees knowledge base (which applies to its commercial distribution and is also widely used for open-source Jenkins); jenkins.io does not give an equivalent specific parameter table; the heap ranges are recommended values, not hard limits.
- The RTO / RPO figures in the HA / DR plans and the M5 disk estimation formula are illustrative teaching examples, not official data. CloudBees CI's HA capabilities are mentioned only briefly; refer to the vendor documentation for details.
- How the GitHub Actions Importer reaches the host's Jenkins over the network on Linux depends on the Docker network configuration; this lesson only outlines the approach.
- The injection methods for F3 / F7 rely on Script Console and plugin file operations, and their behavior may differ across Jenkins versions and Helm chart configurations (such as
overwritePlugins), so behavior may differ. - Lessons 1–6 and 8 were written in parallel with this lesson; cross-lesson references follow the course-wide conventions (
~/jenkinslab,agent1, kindlab, namespacejenkins) take precedence.