Jenkins Hour 7: Deep Troubleshooting, Optimization, and Advanced Topics

From “the build is stuck / the Pipeline fails for no clear reason / the controller won't start after a plugin upgrade” to “a fast and stable controller”: systematic troubleshooting, queue mechanics, CPS and sandbox errors, plugin dependencies, JVM and retention policies, high availability and disaster recovery, and migrating to GitHub Actions / Azure Pipelines
Jenkins LTS 2.580.2Queue · Executor · CPSSupport Core · Script ConsoleGitHub Actions ImporterVerified against official docs and source code · 2026-11-16
Overall Learning Objectives
  • 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 down and 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, sandbox RejectedAccessException: 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

#TimeModuleCore ContentAnimation / InteractionLab
0Before ClassPreparation: Fault-Injection EnvironmentReuse ~/jenkinslab (or kind lab), API tokens,faults/ fault-injection scripts, baseline job faultbox—Get a green baseline
100–06Troubleshooting MethodologyFive evidence layers, build log, controller log, Log Recorder, System Information, thread dump, Support Bundle, Script Console“Evidence ladder” step-by-step animationUse scriptText the API to write a diagnostic script why.sh
206–13Stuck BuildsQueue state machine, label matching, executor exhaustion, agent disconnects, ping thread, throttling and quiet downQueue diagnosis simulator (core animation)Reproduce 4 queueing causes
313–21Pipeline ErrorsCPS transformation and program.dat, CPS mismatch, NotSerializableException, @NonCPS, sandbox approval, MissingMethodCPS persistence animation (bad code vs fix)Reproduce and fix 3 kinds of errors
421–28Plugin Dependencies and UpgradesDependency graph, load failure messages, upgrade assessment, rollback, pinned versions in plugins.txtDependency conflict resolverDisable a dependency plugin and restore it
528–35PerformanceController sizing, heap / G1GC / GC logs, build retention, workspace cleanup, durability levelJENKINS_HOME capacity and heap estimatorAdd JVM options and read GC logs
635–42ReliabilityHA options, backup and restore, secrets, RTO/RPO, multiple controllersFailure recovery timeline simulationBackup → delete → restore drill
742–50MigrationGitHub Actions Importer, Jenkinsfile → Actions / Azure Pipelines mappingSyntax mapperImporter audit + dry-run
850–60Mixed Fault Mystery BoxRandom injection of 8 fault types + interactive troubleshooting treeMystery box simulator + troubleshooting treeOpen the mystery box in a real environment
—After ClassCheat Sheet · Capstone LabFault mystery box + performance health report + DR drillFinal quiz: 12 questionsAcceptance checklist: 12 items

Knowledge Coverage Matrix

Target SkillModuleKey Commands / SettingsLabProduction Case
Evidence CollectionM1consoleText,/manage/log,/manage/systemInfo,/threadDump, Support Bundle✓✓
Script Console and APIM1 · M2POST /scriptText,/queue/api/json,/computer/api/json✓✓
queue reasonsM2why,stuck,blocked, label expressions, executor count✓✓
agent connectionM2hudson.slaves.ChannelPinger.pingIntervalSeconds / pingTimeoutSeconds, agent log✓✓
CPS and serializationM3@NonCPS,program.dat,durabilityHint✓✓
sandbox and approvalM3In-process Script Approval,ScriptApproval✓✓
plugin dependenciesM4jenkins-plugin-cli,plugins.txt,*.jpi.disabled, Downgrade✓✓
JVM tuningM5JAVA_OPTS,controller.javaOpts,-Xlog:gc*,jcmd✓✓
retention and cleanupM5buildDiscarder(logRotator(...)), Global Build Discarders,cleanWs()✓✓
backup and disaster recoveryM6tar JENKINS_HOME (including secrets/), ThinBackup, JCasC✓✓
migrationM7gh actions-importer audit/forecast/dry-run/migrate jenkins✓✓
Comprehensive troubleshootingM8All✓✓

Content Not Covered in This Lesson

TopicReasonWhere to Learn
Jenkins installation, agent connection, first JenkinsfileCovered in Lesson 1Lesson 1
Declarative syntax, Multibranch, Webhook, Shared Library usageCovered 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 agentsCovered in Lesson 5Lesson 5
Authorization matrix and the security model of Script Security approvalsCovered in Lesson 6; this lesson only covers troubleshootingLesson 6
GitHub Actions syntax and runnersTopics in the GitHub courseGitHub 8-hour course
Azure Pipelines YAML and agent poolsTopics in the Azure DevOps courseAzure DevOps 8-hour course
Kubernetes Pod scheduling and resource quotasTopics in the Kubernetes courseKubernetes 8 + 1-hour course

How to Use These Materials

10 pages per module
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.
Learning Progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (key name jenkins60-part7-progress-v1).
Two Lab Paths
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.
Version Notes This lesson uses the versions verified on 2026-11-16: Jenkins LTS 2.580.2 (2026-10-28, tested with JDK 21 / 25; Java 17 is no longer supported since 2.555.1), weekly 2.590; Pipeline: Groovy (workflow-cps) 4403.v471713a_cea_19; Script Security 1436.v1082791135e4; Support Core 1876.va_195a_b_645f3f; Prometheus metrics 873.v054598e6e84d; ThinBackup 2.1.5; Jenkins Helm chart 5.13.3. Error messages quoted in the text come from the message files in the Jenkins core and plugin source code (see the sources page); a few combined outputs are formatted in a common form and marked “verify against your actual output”.

Module 0 · Preparation: Fault-Injection Environment

Reuse ~/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
Before class ≈ 15 minutescurl · python3 · docker compose or kubectl
Prerequisites
  • Completed Lessons 1 and 2: ~/jenkinslab/compose.yaml contains jenkins (127.0.0.1:8080),agent1 (label linux docker),gitea (127.0.0.1:3000, repository lab/myapp); admin user admin.
  • or completed Lesson 5: kind cluster lab, namespace jenkins, Helm release jenkins (official jenkinsci chart, controller Pod jenkins-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)

NameValueSource
Lab directory / Compose file~/jenkinslab / compose.yaml (services jenkins,agent1,gitea)Lesson 1
controller addresshttp://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 / labelagent1 (inbound agent, secret in .env of AGENT1_SECRET, 2 executors, mounting docker.sock) / linux dockerLesson 1
Image / API tokenjenkins/jenkins:2.580.2-jdk21 / ~/jenkinslab/.secrets/jenkins-tokenLesson 1
credential IDgitea-myapp,registry-credsLessons 1, 2
Application and Pipelinemyapp (Flask, port 5000,/healthz), Gitea repository lab/myapp, job myappLessons 1, 2
Created in this lessondirectory ~/jenkinslab/faults/; Pipeline job faultbox,faultbox-hogthis 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 /scriptText require Overall/Administer; the API token belongs to admin,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.sh Restore all faults; delete after class faultbox* 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
}
TipnumExecutors: 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
Notes In F5, the regex is passed through three layers of quoting (bash → Groovy string → XML) and has many backslashes; if your shell produces a different result, open 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

00:00 – 06:00 · First determine “which layer is broken,” then collect evidence along the evidence ladder: build log → controller log → system information and thread dump → Support Bundle → Script Console
6 minconsoleText · Log Recorder · Support Core★★★★★ Foundation for all later modules
Learning Objectives
  • 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 /scriptText the API to run read-only diagnostic scripts, understanding their risks and audit requirements.
Prerequisites: Lesson 1 (controller / agent / executor / queue). Importance:★★★★★

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.

LayerTypical symptomWhere to find evidenceCommon tools
① Job definitionNo trigger after push, Jenkinsfile compile error (WorkflowScript: 12: …)Start of the build log, Multibranch's Scan Log, Webhook delivery logReplay, Pipeline Syntax, Declarative Linter
② QueueThe build stays queued in grey, or the Pipeline log shows Still waiting to schedule taskhovering over a queue entry shows the reason (why),/queue/api/jsonall of M2
③ Agent / connectionAgent 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 engineNotSerializableException,RejectedAccessException, CPS mismatchJava stack trace in the build logM3, Script Approval
⑤ Steps and toolsscript returned exit code 1The output of that step in the build logManually reproduce the same command on the agent
Cross-cutting: the controller itselfSlow UI, frequent Full GC, plugin load failurescontroller log, GC log, top-of-page alerts in Manage JenkinsM4, 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)

  1. 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 level jobs/ or branches/).
  2. 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.
  3. 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.
  4. System Information and thread dumps: /manage/systemInfo lists system properties, environment variables, plugins, and memory; /threadDump shows 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.
  5. 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.
  6. Script Console: /manage/script or POST /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

① Job definitionTrigger · SCM · Compilation ② QueueLabel · executor · throttling ③ Agent / connectionRemoting · ping · workspace ④ Pipeline engineCPS · serialization · sandbox ⑤ Steps and toolssh · docker · git Scan Log · WebhookCompilation errors at the start of the log Queue reason (why) · node page Log · agent log/queue/api/json · /computer/api/json Build log consoleText · Pipeline StepsJava stack · exit code · Script Approval Across all layers: the controller itself (JVM memory / GC, plugin loading, disk)controller log · System Information · thread dump · GC log · Support Bundle · Script Console (read-only)
Figure 1-1: problems in the first three layers often leave “nothing in the build log”; layers ④ and ⑤ are where you typically “read the log”

Evidence in JENKINS_HOME

$JENKINS_HOME/ jobs/<job>/builds/<n>/log · build.xml · program.dat nodes/<agent>/config.xml plugins/*.jpi · *.jpi.disabled · *.bak logs/ (job logs, slaves/, etc., varies by version) support/ (content generated by Support Core) Sensitive!secrets/ (master.key, etc.)credentials.xml (encrypted storage)Build logs may contain business dataRedact before sharing
Figure 1-2: in the Pipeline build directory, 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.

Build logconsoleText Queue reason (why)/queue/api/json Node status/computer/api/json Controller logcompose logs / kubectl logs Log Recorderhudson.slaves.* Thread dump/threadDump Support BundleTicket attachment Script ConsoleRead-only query Root cause + fixChange one thing, rerun to verify
Ready. Click “Play.”

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'
Note In the official image, the Jenkins Java process is usually not PID 1 (PID 1 is tini), so first use 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

Inject a simple fault: a label typo.
cd ~/jenkinslab/faults && ./inject.sh F1 && sleep 10
Level 1: build log. Note that the Pipeline itself has already “started”; what is stuck is 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’
Write the diagnostic script: print the queue, nodes, recent builds, and plugin failure information in one go.
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 plugins
Create a Log Recorder: following Section 5 of “Commands,” for hudson.model.Queue create a FINE-level recorder, observe the queue maintenance logs, then delete it.
(Optional) Generate a Support Bundle: after installing Support Core, generate a bundle, unzip it, and open about.md and the node directory, and list the 3 types of information you think need redaction.
Cleanup: ./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).

Command-line questions

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)

▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · duration and upload date not verified · purpose: review where the controller, agents, build logs, and admin interface are located

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.

Shot 1 · 0:00–0:20
Visual: Five boxes light up from left to right: job definition, queue, agent, Pipeline engine, steps; a red bar at the bottom reads “controller itself.”
Narration: The first step in troubleshooting is not digging through logs, but figuring out which layer is broken.
Shot 2 · 0:20–0:50
Visual: In the terminal, consoleText shows only “Still waiting to schedule task”; the shot cuts to the hover tooltip of the queue entry, “There are no nodes with the label.”
Narration: The build log has no errors, so the problem is in the queue; the queue entry tells you what it is waiting for.
Shot 3 · 0:50–1:20
Visual: A new recorder is created in System Log; the /threadDump page scrolls, highlighting a stuck thread.
Narration: When you need more detail, raise the log level for only one subsystem; for global slowness, capture thread dumps repeatedly.
Shot 4 · 1:20–1:45
Visual: The Script Console runs a read-only Groovy snippet; a red warning “equivalent to root” appears in the corner of the screen.
Narration: The Script Console can see everything and change everything; production is read-only, and write operations go through code review.
or score ≥ 70% on the quiz

Module 2 · Stuck Builds: Queues, Executors, and Agent Disconnects

06:00 – 13:00 · Understand every “why hasn’t it started yet” the queue reports, and handle agent disconnects, ping timeouts, and Pipeline waits for node recovery
7 minQueue · CauseOfBlockage · ChannelPinger★★★★★ Core animation
Learning Objectives
  • 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 ChannelPinger default 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.
Prerequisites: Lesson 1 (labels, executors), Lesson 5 (Kubernetes Pod agents). Importance:★★★★★

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:

  1. 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.
  2. blocked: the job itself or a plugin says “it cannot run now.” For example, with the Pipeline option disableConcurrentBuilds() the reason is Build #41 is already in progress (ETA: 3 min 12 sec); the Throttle Concurrent Builds plugin gives Already running 1 builds across all nodes; when the controller is in Prepare for shutdown (quiet down), it is Jenkins is about to shut down.
  3. 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).
  4. 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

CauseOriginal queue reason text (Jenkins core / plugin messages)First step
No matching labelThere 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 offlineAll nodes of label ‘linux’ are offline / ‘agent1’ is offlinenode page Log; whether the agent process is running; network and port 50000 / WebSocket
Executor exhaustionWaiting for next available executor on ‘linux’Who is holding the executor? /computer/api/json busy/total; are there any hung builds
Throttling / blockingBuild #41 is already in progress (ETA: …),Already running 1 builds across all nodes,Jenkins is about to shut downjob 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). offlineCauseReason The 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 property hudson.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 node block 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,Linux and linux are different; label expressions support &&,||,!.

Queue state machine and reason sources

TriggerSCM · Scheduled · Manual waitingquiet period blockedConcurrency · Throttling · Shutdown buildableLabel · Online · Executor pending → leftAssign executor In the quiet period.Expires in … Build #N is already in progressAlready running N builds …Jenkins is about to shut down There are no nodes with the labelAll nodes of label … are offlineWaiting for next available executor Reason providersJob#getCauseOfBlockage (e.g., disableConcurrentBuilds) · QueueTaskDispatcher (throttling, lock, and other plugins)Label / Node#canTake · Computer online status · idle Executor
Figure 2-1: reason text comes directly from Jenkins core's Messages.properties and plugin messages; once you understand them, you know where to look

Two-level queuing in Pipeline

faultbox #7 (flyweight)Pipeline interpreted on the controller part of faultbox #7queue entry for agent { label 'linux' } agent1's executorRunning on agent1 in …/workspace/faultbox Log: Still waiting to schedule task+ queue reason
Figure 2-2: the build shows “running,” but the node block's queue entry is waiting

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 .

① Trigger → enter queue ② Is the controller preparing to shut down? ③ Is the same job already running? ④ Is the throttle category full? ⑤ Is there a node with this label? ⑥ Is a matching node online? ⑦ Is there an idle executor? agent1labels: linux docker executor #0 idle executor #1 idle ● Online (Remoting channel healthy) Queue entry status — Click “Trigger build”
Conditions

Label expression in the Jenkinsfile:

Select conditions, then click “Trigger build.”

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
Tip The label key names that the Kubernetes plugin applies to agent Pods vary by plugin version,-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

No matching label (F1)
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).

Agent offline (F2): the Compose path stops 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
Executor exhaustion (F3): the script changes agent1's executor count to 1 and lets 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
Throttling / concurrency blocking (F4): the baseline job has 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
(Optional) Prepare for shutdown: Manage Jenkins → Prepare for Shutdown, then trigger 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.

Command-line questions

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)

▶
Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4 — TechWorld with Nana
English · duration and upload date not verified · purpose: review the Jenkins and agent environment in containers (corresponds to the Compose path in this lesson)

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

Video storyboard script

This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0:00–0:25
Visual: A dot starts at “Trigger,” passes through the 7 checkpoints in turn, and finally lands on agent1's idle executor.
Narration: Every build must pass the same checks: shutdown, concurrency, throttling, label, online, executor.
Shot 2 · 0:25–0:55
Visual: The label is changed to linux-dokcer; the dot stops at the 5th checkpoint and turns red; a “There are no nodes with the label” message pops up.
Narration: The queue reason is the answer: no node has this label.
Shot 3 · 0:55–1:25
Visual: Two executors turn orange, “busy”; the dot stops at the 7th checkpoint: Waiting for next available executor.
Narration: The nodes are online but all busy: find out who is holding the executors, rather than adding executors to the controller.
Shot 4 · 1:25–1:50
Visual: agent1 disconnects; the terminal shows “Ping started at … hasn't completed by …”; the Pipeline log shows “will wait for 5 min 0 sec.”
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.
or score ≥ 70% on the quiz

Module 3 · Pipeline Errors: CPS, Serialization, and Sandbox Rejections

13:00 – 21:00 · Pipeline Groovy is not “ordinary Groovy”: it is interpreted on the controller in CPS style, each step may write program state to disk, and it runs in a sandbox by default — the four most common runtime errors all stem from this
8 minworkflow-cps · script-security★★★★★ High-frequency interview topic
Learning Objectives
  • 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 example java.util.regex.Matcher, JsonSlurper's LazyMap).
  • Understand the CPS mismatch warning expected to call … but wound up catching … 's meaning, and use @NonCPS correctly.
  • 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 method from compile errors MultipleCompilationErrorsException.
Prerequisites: Lesson 2 (Declarative Pipeline, Shared Library), Lesson 6 (Script Security). Importance:★★★★★

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

ErrorRoot causeActual error message (verbatim)Preferred fix
Not serializableAt a step boundary, an object that is not serializable is in scopejava.io.NotSerializableException: java.util.regex.MatcherDo 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 mismatchNon-CPS code (native Groovy / Java methods,@NonCPS methods, constructors,toString) calls back a CPS-transformed closure or methodexpected 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 rejectionBy default the sandbox only allows whitelisted methods / constructors / fieldsorg.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.StringUse 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 existTypo, mismatched parameter types, or the plugin is not installed or not loadedgroovy.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.BindingFix the spelling / parameters; confirm the plugin that provides this step or global variable is installed and loaded (M4)

How: correct usage of @NonCPS

  • @NonCPS The 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 @NonCPS method must be written outside the pipeline { } block (at file top level), or moved into a Shared Library.
  • The sandbox still applies: @NonCPS does 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 (sh etc.) 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.instance and 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

controller (JVM) JenkinsfileCompile + CPS transform CPS VM threadInterpret Groovy · sandbox checks program.datSerialize call stack and local variables @NonCPS method: plain Groovy, runs to completion without pausing, cannot call stepsCan use non-serializable objects such as Matcher; returns only simple values agent1Actual sh / bat processesWorkspace · tools · output returned(does not run the Pipeline's Groovy) Steps controller restarts → read program.dat → restore call stack → reconnect to still-running sh processes (durable task)
Figure 3-1: step boundary = persistence point. If even one non-serializable object is in scope, writing program.dat fails

Sandbox decision flow

Method call'ls'.execute() GroovySandbox interceptsSignature: staticMethod … Whitelisted / approved→ allowed RejectedAccessExceptionRecorded in Script Approval as pending Admin: approve / rewrite / movetrusted Shared Library
Figure 3-2: the sandbox decides by “signature”: method / staticMethod / new / field + class name + method name + parameter types

Step-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
  }
}
Compile + CPS transformcontroller CPS VM executionSandbox checks each call Local variablesm : Matcher Serializeprogram.dat agent1: shecho major=1 java.io.NotSerializableExceptionjava.util.regex.Matcher Resume executionSUCCESS
Ready. Click “Play”.

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

NotSerializableException (F5)
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.

Sandbox rejection (F6)
./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().

MissingMethodException (F8)
./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.

Observe the CPS mismatch: in Replay, add the code below; the build will succeed, but the log shows a CPS mismatch warning, and the official docs state that this pattern gives wrong results (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.

Clean up: ./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.

Command-line exercise

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)

▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · duration and upload date not verified · purpose: review Jenkinsfile structure, script blocks, and where Groovy fits

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

Video storyboard script

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: The Jenkinsfile text is squeezed by a “transformer” into a series of pausable small blocks and sent to the controller; an arrow for sh points to the agent.
Narration: The Pipeline's Groovy runs on the controller in CPS style; only steps run on the agent.
Shot 2 · 0:25–0:55
Visual: When it reaches sh, the local-variables box is packed and written to program.dat; the Matcher gets stuck in the packer, and a red NotSerializableException appears.
Narration: At every step boundary the program state is written to disk; a single non-serializable object in scope makes it fail.
Shot 3 · 0:55–1:25
Visual: The @NonCPS method swallows the Matcher and outputs only the string "1"; packing succeeds, and sh runs successfully.
Narration: Keep the non-serializable computation inside an @NonCPS method, and return only simple values.
Shot 4 · 1:25–1:50
Visual:'hostname'.execute() hits the sandbox wall; the sh(returnStdout: true) next to it passes.
Narration: When the sandbox rejects something, first check whether a step can do the job instead of clicking Approve.
or score ≥ 70% on the “Quiz”

Module 4 · Plugin dependency conflicts and upgrade failures

21:00 – 28:00 · Almost all of Jenkins' capabilities come from plugins, and most “upgrade incidents” are dependency graph problems: read load-failure messages, assess before upgrading, roll back after an incident, and treat the plugin list as code
7 minPluginWrapper · jenkins-plugin-cli★★★★☆
Learning objectives
  • 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-cli and plugins.txt / Helm controller.installPlugins to pin versions and avoid “latest drift”.
Prerequisites: Lesson 1 (plugin management), Lesson 5 (JCasC and Helm). Importance:★★★★☆

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 templateMeaningTypical 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 requiredThe plugin requires a newer coreOnly 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 higherDependency plugin version is too lowOnly the plugin that depends on it was upgraded
Required plugin is disabled: {display name} ({short name})A dependency plugin was disabledSomeone disabled a plugin that “looked unused”
Plugin is missing: {short name} ({version})The dependency plugin does not exist at allThe .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

  1. 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.
  2. Rehearse: using the same plugins.txt + new core to build the image in a staging environment (or kind lab) and start it; check for “Manage Jenkins” warnings and run a set of smoke-test Pipelines.
  3. Back up: snapshot of JENKINS_HOME (at least plugins/,config.xml,jobs/*/config.xml,secrets/, M6).
  4. Upgrade together: core and plugins are released as one versioned set (image tag); do not piecemeal click “Update All” in the UI.
  5. 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 .bak file 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 .bak have a downgrade button; a plugin whose data format was migrated by a newer version may be incompatible when downgraded.

Dependency graph and cascading failures

Jenkins core2.580.2 LTS Pipeline: Groovyworkflow-cps · core ≥ 2.568.1 Docker Commonsdocker-commons 477.v289… Git clientgit-client 6.7.1 Pipeline: Declarativepipeline-model-definition Docker Pipelinedocker-workflow 653 → commons ≥ 477 Gitgit 5.11.0 → git-client ≥ 6.5.0
Figure 4-1: arrow = “depends on”. If a lower-level plugin fails (or core is too old), every upper-level plugin that depends on it becomes an “indirect failure”. (The Declarative → Docker Commons link is only illustrative, showing that dependencies can span branches; check each plugin's page for actual dependencies.)

Upgrade pipeline

PR: plugins.txt+ core image tag Build imagejenkins-plugin-cli Staging environmentWarnings + smoke-test Pipeline Backup + releaseMaintenance window Verify / roll backPrevious image + backup
Figure 4-2: treat core + plugins as one immutable release unit

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.

Jenkins core2.580.2 Pipeline: Groovy4403.v471713a_cea_19 Docker Commons477.v289085a_b_6896 Git client6.7.1 Pipeline: DeclarativeDepends on workflow-cps Docker PipelineDepends on commons + workflow-cps GitDepends on git-client ≥ 6.5.0
Select one of the scenarios above.

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
Tip Parameter names follow 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
Note Check the image tag format against the actual tags on Docker Hub 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)

Export the plugin list (“Commands” section 2) and commit it to your ~/jenkinslab Git repository as the baseline.
Inject the fault: the script, in 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)
Check the UI warnings: a warning appears at the top of Manage Jenkins: Some plugins could not be loaded due to unsatisfied dependencies., record the two groups, Dependency errors and Indirectly dependent plugins.
Check the build symptoms:
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).

Restore: ./reset.sh (delete .disabled file and restart), confirm the warning is gone and faultbox turns green.
(Optional) core too old: on the kind route, start a temporary release using an old LTS image tag (e.g. 2.555.x) plus the latest workflow-cps, and observe 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).

Command-line exercise

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)

▶
Jenkins Full Course | Jenkins Tutorial For Beginners | Jenkins Tutorial | Simplilearn — Simplilearn
English · duration and upload date not verified, UI may be outdated · purpose: review the plugin management interface

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

Video storyboard script

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: Plugin dependency graph with core at the bottom; one lower-level plugin turns red, the failure spreads upward, and three upper-level plugins turn gray one after another.
Narration: Plugins load according to the dependency graph; if one lower-level plugin fails, every plugin above it fails too.
Shot 2 · 0:25–0:55
Visual: Red warning at the top of Manage Jenkins; zoom in on Dependency errors and Indirectly dependent plugins.
Narration: Fix the “direct” errors first; the indirect failures disappear on their own.
Shot 3 · 0:55–1:25
Visual: Diff of plugins.txt in the Git repository; CI builds the image, and it is released after the staging smoke tests pass.
Narration: Release core and plugins together as one image version; rolling back means switching back to the previous tag.
or score ≥ 70% on the “Quiz”

Module 5 · Performance: controller sizing, JVM, and build retention

28:00 – 35:00 · The controller is the scheduler and Pipeline interpreter, not a build machine: give it a suitable heap and GC logging, move builds onto agents, and control the growth of JENKINS_HOME
7 minG1GC · -Xlog:gc · Build Discarder · cleanWs★★★★☆
Learning objectives
  • 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 / Helm controller.javaOpts): G1GC, GC logging, a heap dump on OOM, and a heap size set as a percentage of container memory.
  • Use GC logs,jcmd and thread dumps to determine whether “slowness” comes from GC or from a plugin.
  • Configure build retention (job-level buildDiscarder and Global Build Discarders) and workspace cleanup (cleanWs()), and understand how the Pipeline durability level affects I/O.
Prerequisites: M1 (thread dumps), Lesson 5 (Helm values). Importance:★★★★☆

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

BottleneckSymptomEvidenceRemedy
Insufficient heap / GC pressurePeriodic UI lag, high CPU, eventually java.lang.OutOfMemoryError: Java heap space or the container OOMKilledFrequent long pauses in the GC log,jcmd GC.heap_infotune the heap, find memory hogs (heap dump), reduce retained builds
Builds running on the controllerUI slows during builds; security riskbuilt-in node executors > 0Set executors to 0; use agents for everything
JENKINS_HOME I/OSlow startup, slow job loading, long gaps between Pipeline stepsDisk latency, number of build directoriesFast storage, build retention,durabilityHint
heavy computation in PipelinesHigh-CPU threads whose names include CPS VMThread dumpmove the computation to sh
Massive logs / large artifactsDisk grows fast; Console Output will not opendu builds directoryTrim logs; store artifacts in an external repository
SCM polling and scanningBackground threads busy; many Git processesThread dump, Multibranch Scan LogSwitch 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) or deleteDir() (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

Container memory (e.g. 8 Gi limit) Java heap ≈ 50%MaxRAMPercentage=50Build record objects · queueCPS programs · plugin cachesmanaged by G1GC Metaspace · code cachegrows with the number of plugins Thread stacks · direct memory2–3 threads per agent JENKINS_HOME disk jobs/*/builds/Logs + artifacts + test reportsusually 80%+→ Build Discarder plugins/ · WAR extraction logs/ · gc.log agent workspaces are not here → cleanWs() / one-off pods
Figure 5-1: the heap is only part of container memory; build records are the bulk of controller disk usage

How to read G1GC logs

Healthy: sawtooth pattern, falling back to a stable baseline after GC Unhealthy: the baseline keeps rising after GC → leak or over-retention → frequent Full GC heap used
Figure 5-2: watch two things — whether the post-GC “baseline” keeps rising, and how long individual pauses last (Pause Young / Pause Full)

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.

Build record disk (GB) No retention policy (30 days) With retention policy Heap recommendation

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
Note The CloudBees article also includes -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

Baseline: record numExecutors (should be 0),du -sh /var/jenkins_home,jcmd … GC.heap_info.
Add JVM options: following section 2 of “Commands”, edit compose.yaml,docker compose up -d jenkins, and use VM.flags to confirm it takes effect.
Generate load: trigger 20 times in a row 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.)

Add a retention policy: in 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.
Configure global retention: Manage Jenkins → System → Global Build Discarders → add Project Build Discarder, then save.
(Optional) heap dump drill: in the lab environment, use 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.

Command-line exercise

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)

▶
Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course) — freeCodeCamp.org
English · duration and upload date not verified · purpose: the overall environment for running Jenkins and agents in Docker (corresponds to the container parameter settings in this module)

No verified video specifically covering Jenkins JVM tuning and build retention was found; please refer to the documents and storyboard script below.

Official documentation

Video storyboard script

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: An 8Gi container box; the heap takes up only the left half, with metaspace and thread stacks on the right.
Narration: The heap is only part of container memory; set it as a percentage and leave headroom.
Shot 2 · 0:25–0:55
Visual: Two heap curves: a healthy sawtooth and a baseline that keeps climbing.
Narration: When reading the GC log, look at only two things: whether the post-GC baseline keeps rising, and how long each pause lasts.
Shot 3 · 0:55–1:25
Visual: A pie chart of JENKINS_HOME with builds at 80%; after adding a retention policy, it shrinks quickly.
Narration: The most effective way to control disk usage is build retention; workspace cleanup happens on the agent.
or score ≥ 70% on the “Quiz”

Module 6 · Reliability: high availability, disaster recovery, and large-scale Jenkins

35:00 – 42:00 · An open-source Jenkins controller is a single process with a single JENKINS_HOME: high availability relies on “fast recovery + rebuildability”, disaster recovery relies on “backing up the right things + rehearsing”, and scaling relies on “multiple small controllers”
7 minJENKINS_HOME · secrets/ · JCasC · RTO/RPO★★★★☆ Frequently asked in architecture interviews
Learning objectives
  • 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/ and credentials.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,retry conditions).
Prerequisites: Lesson 5 (Helm, JCasC, Kubernetes agents), M5. Importance:★★★★☆

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

OptionMechanismTypical RTOCost / 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 remountedminutes (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 DNStens of minutes to hoursyou must ensure the old primary is stopped; rehearse the switchover
Rebuildable controllerJCasC + plugins.txt + Job DSL / Organization Folder: configuration and jobs all come from Gittime 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 HAFor example, CloudBees CI provides active/active high availabilityrefer to the vendor documentationLicense fees; not part of open-source Jenkins

How: what to back up

PathRequired?Notes
secrets/ (includes master.key,hudson.util.Secret , etc.)RequiredWithout 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.xmlRequiredGlobal configuration, credentials (encrypted)
jobs/Required (at least config.xml)build records: whether to back up in full depends on RPO requirements
users/,nodes/Requiredusers (including API tokens), static node definitions
plugins/*.jpiRecommendedor rebuild from plugins.txt
workspace/,caches/,war/,.cacheExcluderegenerable

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

A. Fast recovery on Kubernetes StatefulSet jenkins (1 replica) PVC jenkins (same availability zone) Node failure → reschedule → remount RTO: minutes · RPO: ≈0 (same disk) B. Primary / standby switchover Primary (running) Standby (stopped) Storage replication / periodic restore Confirm primary stopped → start standby → switch DNS RTO: tens of minutes+ · RPO: replication interval C. Rebuildable controller Git: values + JCasC + plugins.txt External secrets store → credentials helm install → Org Folder scan RTO: minutes · RPO: history can be lost
Figure 6-1: three open-source-viable “high availability” paths; in production, A + C + daily backups are often combined (RTO / RPO are illustrative)

Multi-controller architecture

Git: platform configuration repositoryvalues-*.yaml · JCasC · plugins.txt controller: team-webHelm release controller: team-dataHelm release controller: releaseStricter permissions Unified identity OIDC / SAML Shared Kubernetes agent cluster Prometheus metrics + backups
Figure 6-2: manage a set of small controllers with “the same template, different values”

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”.

Architecture
Failure
Select an architecture and a failure.

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
Security The backup includes 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
Tip The restored instance has the same configuration as the original (including agent definitions, webhooks, and scheduled jobs). During a rehearsal it may try to connect to the same agents or run scheduled builds — production rehearsals should run on an isolated network, or before startup use -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

Backup: following section 1 of “Commands”, complete one consistent backup and record the start and end times and the file size.
Verify backup contents:
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
Restore rehearsal: following section 2 of “Commands”, restore to 8081 and time it. The time from starting extraction until the login page returns 200 is the lower bound of your environment's RTO.
Counter-example: restore again, but delete the 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.
Write a runbook: one-page checklist: determine the failure → stop the old instance → restore data → start → verify (login, credentials, agents, one smoke build) → switch the entry point → notify.
Clean up: delete 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).

Command-line exercise

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)

▶
What Is Jenkins? | What Is Jenkins And How It Works? | Jenkins Tutorial For Beginners | Simplilearn — Simplilearn
English · duration and upload date not verified · Purpose: overview of controller / agent architecture (understanding that “the controller is a single point”)

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

Video storyboard script

This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: Two controllers point to the same disk; file icons flash in conflict and a red X appears.
Narration: In open-source Jenkins, each JENKINS_HOME can have only one controller.
Shot 2 · 0:25–0:55
Visual: The backup package expands, the secrets directory is highlighted, and the credential lock icon beside it opens.
Narration: The key to a backup is not the jobs but the secrets that can decrypt the credentials.
Shot 3 · 0:55–1:25
Visual: Three values files in a Git repository, each generating one controller.
Narration: When the scale grows, split it: same template, different configuration, so a failure or upgrade affects only a small group of people.
or score ≥ 70% in the “Quiz”

Module 7 · Migration: Jenkins to GitHub Actions / Azure Pipelines

42:00 – 50:00 · Inventory first, then forecast, then trial conversions, and finally migrate job by job: use GitHub Actions Importer to automate what can be automated, map the rest by hand, and decide which jobs should not be migrated at all
8 minutesgh actions-importer · audit / forecast / dry-run / migrate★★★★☆
Learning objectives
  • 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,stage supported; agent,environment,stages,steps,triggers,when partially supported; inputs,matrix,options,parameters not 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.
Prerequisites:GitHub course(Actions syntax),Azure DevOps course(Pipelines YAML). Importance:★★★★☆

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 migrationConsider keeping Jenkins
Code already in GitHub / Azure Repos; Declarative Pipeline with simple logic; you want to reduce controller operations and plugin upgrade burdenHeavy 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)

  1. 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 (workflow scope; creating a PR also requires repo); forecast Install 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.
  2. configure: interactive write .env.local (JENKINS_ACCESS_TOKEN,JENKINS_INSTANCE_URL,JENKINS_USERNAME,GITHUB_ACCESS_TOKEN,GITHUB_INSTANCE_URL, optional JENKINSFILE_ACCESS_TOKEN); update pull the latest Importer container image.
  3. 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 as workflow_usage.csv.
  4. forecast: estimates GitHub Actions usage (job count, duration, concurrency) based on builds completed in the last 7 days (default).
  5. 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-path to specify a local file.
  6. 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,options are 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

auditInventory · conversion rate forecastUsage · concurrency dry-runLocal YAML Manual completionSecrets · runners · plugins migrateOpen PR · review Parallel run → decommissionCompare · archive gh actions-importer (Docker container) — reads the Jenkins API (JENKINS_INSTANCE_URL + API token) — writes local files / opens PRs on GitHubforecast requires the Paginated Builds plugin on Jenkins
Figure 7-1: the Importer automates “the parts that can be automated”; people handle review and completion

Conceptual mapping

JenkinsGitHub ActionsAzure Pipelines
controller + agent (labels)GitHub-hosted runner / self-hosted runner (labels)Microsoft-hosted agent / self-hosted agent pool (demands)
stagejobs.<id> (needs order of expression)stages / jobs
shrunscript / bash
environmentenvvariables
Credentials + withCredentialsSecrets / OIDCsecret variables, variable groups, service connections
whenifcondition
post { always / failure }if: always() / failure()condition: always() / failed()
inputEnvironment required reviewersEnvironment approvals and checks
archiveArtifacts / stashactions/upload-artifact / download-artifactPipeline artifacts (publish / download)
Shared Libraryreusable workflows, composite actionsTemplates (template / extends)
parametersworkflow_dispatch.inputsRuntime 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.

Jenkinsfile
GitHub Actions
Azure Pipelines
Select a structure.

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
Note The Importer runs in a Docker container,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

Setup: confirm Docker is running and 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).
configure + update: complete it following section 1 of “Commands”. Confirm the Jenkins URL is reachable from inside the container:
docker run --rm curlimages/curl -s -o /dev/null -w "%{http_code}\n" http://host.docker.internal:8080/login
audit: for faultbox,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.
dry-run: convert 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?
(Optional) forecast: install the Paginated Builds plugin, run forecast, record the estimated job count and total duration, and compare them against the GitHub course's Actions billing rules.
(Optional) migrate: run migrate against the test repository, review the PR, add the Secrets and merge, then watch the workflow run.
Cleanup: revoke the Jenkins and GitHub tokens; delete 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.

Command-line exercise

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)

▶
Jenkins migrations powered by GitHub Actions Importer — Ethan Dennis
English · duration and upload date not verified · Source: demo video linked in GitHub Community discussion #48913 (GitHub Actions Importer GA announcement) · Purpose: full demonstration of audit / dry-run / migrate
▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · Purpose: understanding the Jenkinsfile structures to be migrated

Official documentation

Video storyboard script (supplementary)

Shot 1 · 0:00–0:25
Visual: Six blocks: audit, forecast, dry-run, manual completion, migrate, parallel decommission.
Narration: Migration is a process, not a single command.
Shot 2 · 0:25–0:55
Visual: Pie chart in audit_summary.md: successful, partially successful, unsupported; the Manual tasks list highlights Secrets and runners.
Narration: The audit tells you the real migration cost and what must be prepared by hand.
Shot 3 · 0:55–1:25
Visual: On the left, the Jenkinsfile post failure block; on the right, it becomes if: failure() and condition: failed(), respectively.
Narration: The concepts map one to one, but cron, approvals and plugins require human judgment.
or score ≥ 70% on the “Quiz”

Module 8 · Mixed-failure blind box

50:00 – 60:00 · 8 random failures injected: first practice “read the symptoms, identify the layer” in the browser simulator, then ~/jenkinslab (or kind lab) open the blind box for real
10 minutes8 failures · interactive troubleshooting tree★★★★★ Tests the first 7 modules
Learning objectives
  • 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”.
Prerequisites: M1–M7. Importance:★★★★★

The 8 failures in the blind box

#FailureLayerFirst symptomKey evidence (verbatim)Fix
F1Mistyped label② QueueBuild shows “running” but does not moveThere are no nodes with the label ‘linux-dokcer’Change back to linux
F2Agent offline (Compose) / Pod quota (kind)②③Same as aboveAll nodes of label ‘linux’ are offline; kind: exceeded quota EventStart the agent / delete the quota
F3Executors exhausted② QueueSame as aboveWaiting for next available executor on ‘linux’, busy = totalEnd placeholder builds / restore the executor count
F4Concurrency disabled② Queue (blocked)New builds queue greyed outBuild #N is already in progress (ETA: …)Wait / abort the previous / abortPrevious
F5Non-serializable object④ EngineBuild failed, Java stack tracejava.io.NotSerializableException: java.util.regex.Matcher@NonCPS / set to null
F6Sandbox rejected④ EngineBuild failedRejectedAccessException: Scripts not permitted to use staticMethod … execute java.lang.Stringswitch to sh(returnStdout: true)
F7Dependency plugin disabledCross-cutting (plugin)Build failed + red warning in Manage JenkinsNo such property: docker for class: groovy.lang.Binding; Required plugin is disabled: Docker Commons (docker-commons)Enable the plugin and restart
F8Misspelled method name④ EngineBuild failedMissingMethodException: No signature of method: java.lang.String.toUppercase()toUpperCase()

Blind box rules

  1. Do not look at .fault-answer, do not look at faultbox 's configuration (in a real incident you usually don't know what was changed).
  2. First write down your diagnosed layer and the reasoning, then gather evidence; change only one thing at a time and verify.
  3. Timing: 2 minutes per question in the simulator; 10 minutes per failure in the real environment.
  4. After finishing, write the five-part record; use ./reset.sh to restore, then open the next one.

Summary of preventive measures

  • Treat labels as an API; unify their agent declaration 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,input so 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

Did the build fail (red)? Not failed, but not moving: check the queue whyF1 F2 F3 F4 Failed: check the exception class name in the logF5 F6 F7 F8 no nodes with the label → F1are offline → F2next available executor → F3 blocked=truealready in progress → F4 NotSerializable → F5RejectedAccess → F6MissingMethod → F8 MissingProperty docker+ plugin warning → F7(the root cause is not in the Pipeline)
Figure 8-1: the first question is always “did it fail, or never start at all?”

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.

Click “Open blind box” to start.

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

Confirm the baseline: ./reset.sh after faultbox is green.
Open blind box: ./inject.sh random, start the 10-minute timer. Do not look at .fault-answer.
Identify the layer: first answer “did it fail or never start?”, then use why.sh and the build log to gather evidence, and write down the layer and the verbatim evidence.
Fix: change only one thing (Replay, start the agent, enable the plugin, abort the placeholder build…), then rerun faultbox to verify it turns green. F7 requires restarting the controller, about 1 minute.
Verify and record: cat .fault-answer Verify, and write the five-part record.
Repeat: ./reset.sh, complete at least 4 rounds, covering at least 3 different layers (queue, engine, plugin).
Safety The blind box script modifies the controller configuration, stops containers and disables plugins, so run it only in a lab environment. On the kind route, F2 will create in the 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.

Command-line exercise

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)

▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · Purpose: comprehensive review of the components of Jenkins

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.

Shot 1 · 0:00–0:20
Visual: A gift box opens and pops up “faultbox #12 running for 9 minutes”.
Narration: Question one: did it fail, or never start at all?
Shot 2 · 0:20–0:50
Visual: The terminal runs why.sh; the why line of the queue entry is highlighted.
Narration: If it never started, check the queue reason; it usually tells you the answer directly.
Shot 3 · 0:50–1:20
Visual: Another box: a red build; NotSerializableException is circled in the log.
Narration: If it failed, look at the exception class name: serialization, sandbox, method not found, property not found; each belongs to its own layer.
Shot 4 · 1:20–1:45
Visual: The five-part record template is filled in line by line.
Narration: After fixing it, write down the evidence and prevention measures; that is the end point of troubleshooting.
or score ≥ 70% on the “Quiz”

Command cheat sheet

All diagnostic and fix commands in this lesson, grouped by scenario
Evidence collection (M1)
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
Queue and nodes (M2)
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
Pipeline errors (M3)
@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=<Jenkinsfile
Plugins (M4)
Jenkins.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}
Performance (M5)
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() } }
Reliability (M6)
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()]) { ... }
Migration (M7)
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
Blind box (M8)
cd ~/jenkinslab/faults
./inject.sh random   # or F1..F8
./why.sh
./reset.sh

Original error text → which module

Original keywordsModule
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 periodM2
Ping started at … hasn't completed by · ChannelClosedException · seems to be removed or offlineM2
NotSerializableException · expected to call … but wound up catching · RejectedAccessException · MissingMethodException · No such DSL methodM3
Failed to load · Update required · or higher required · Required plugin is disabled · Plugin is missingM4
OutOfMemoryError · OOMKilled · No space left on deviceM5

Capstone lab + final quiz

Blind box challenge + controller performance health check report + disaster recovery drill + migration assessment
About 90–120 minutesCost: 0 (local)
Scenario

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.

Tools and baseline: complete the Module 0's faults/ script and M1's why.sh,faultbox and confirm it is green.
Blind box challenge: ./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 monitoring: write a script that checks /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)"'
Plugin governance: export 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).
Performance health check: controller executor = 0; add JVM parameters and GC logging; for faultbox and myapp add buildDiscarder and cleanWs(); record the JENKINS_HOME size before and after.
Disaster recovery drill: consistent backup → restore on 8081 → measure RTO; verify the credentials can be decrypted; write a one-page runbook.
Migration assessment: run the Importer's audit and dry-run against myapp, compare with the manual version, and list the manual tasks.
Deliverable report: “Jenkins Platform Health Report”: blind box records → current status and improvements for the queue / plugins / performance / disaster recovery → migration recommendations and risks.
Acceptance checklist

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

Basis for verifying all technical facts in this lesson (verification date: 2026-11-16)
TopicVerification conclusionSource (verification date)
Jenkins versionLTS 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 onwardLTS 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 structurecore hudson/model/Messages.properties, jenkins/model/Messages.properties, CauseOfBlockage.java (master branch, 2026-11-16)
Throttle pluginAlready running {0} builds across all nodes / on node; version 625.vc8b_e469e9a_b_cthrottle-concurrent-builds-plugin Messages.properties; plugins.jenkins.io (2026-11-16)
ping threadChannelPinger 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 taskworkflow-durable-task-step-plugin DurableTaskStep.java, ExecutorStepExecution.java (2026-11-16)
CPS mismatchMessage format expected to call X but wound up catching Y; see: https://jenkins.io/redirect/pipeline-cps-method-mismatches/; five scenarios and toSorted examplesworkflow-cps CpsVmExecutorService.java;CPS method mismatches(2026-11-16)
DSL / sandboxNo such DSL method '…' found among steps (NoSuchMethodError); Scripts not permitted to use {type} {details}; original approval prompt textworkflow-cps DSL.java; script-security RejectedAccessException.java, scripts/Messages.properties (2026-11-16)
Plugin load failureFailed 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 versionsworkflow-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_e66715plugins.jenkins.io API (2026-11-16)
Tools and chartPlugin 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 JVMcontroller 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 50Hardware Recommendations;CloudBees KB Prepare Jenkins for Support(2026-11-16)
Build retentionBuildDiscarderProperty (Discard old builds), and the “Project Build Discarder” / “Specific Build Discarder” of Global Build Discarderscore Messages.properties (2026-11-16)
GitHub Actions ImporterPrerequisites (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.csvGitHub 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 task the layout of the reason line, the prefix lines of the plugin load failure log, the stack details of NotSerializableException,Possible solutions lines, 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 of retry and the conditions behavior, 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, kind lab, namespace jenkins) take precedence.