Skip to content

Commit 80af42e

Browse files
committed
Label auto-pods with job name and number
1 parent a6409ea commit 80af42e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

pipelines/lib/util.groovy

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,66 @@ def saveCache(
444444
}
445445

446446

447+
def labelPod(){
448+
if (env.NODE_NAME && (env.NODE_NAME =~ /(manager|snowflake)/)) {
449+
echo "Skipping pod label: ${env.NODE_NAME} is a static/snowflake node."
450+
return
451+
}
452+
453+
def JOB = env.JOB_NAME ? env.JOB_NAME.replace('/', '.') : "unknown"
454+
def BUILD_NUMBER = env.BUILD_NUMBER ? env.BUILD_NUMBER.toString() : "unknown"
455+
456+
def labels = [
457+
"jenkins-job": JOB,
458+
"jenkins-build": BUILD_NUMBER
459+
]
460+
461+
def upstream = currentBuild.upstreamBuilds
462+
def upstreamFields = ""
463+
if (upstream) {
464+
def tJob = upstream[0].projectName.replace('/', '.')
465+
def tNum = upstream[0].number.toString()
466+
echo "Upstream Trigger: ${tJob} #${tNum}"
467+
labels["triggered-by"] = tJob
468+
labels["triggered-build"] = tNum
469+
}
470+
471+
def jsonLabels = groovy.json.JsonOutput.toJson([metadata: [labels: labels]])
472+
echo "jsonLabels: ${jsonLabels}"
473+
474+
bash """
475+
set -eu
476+
set +x
477+
478+
SA=/var/run/secrets/kubernetes.io/serviceaccount
479+
[ -r "\$SA/token" ] || { echo "not in k8s; skipping pod label"; exit 0; }
480+
NS=\$(cat \$SA/namespace)
481+
POD=\${HOSTNAME}
482+
TOKEN=\$(cat \$SA/token)
483+
CA=\$SA/ca.crt
484+
485+
cat <<EOF > /tmp/patch.json
486+
${jsonLabels}
487+
EOF
488+
489+
if curl -sS --fail \\
490+
--cacert "\$CA" \\
491+
-H "Authorization: Bearer \$TOKEN" \\
492+
-H "Content-Type: application/merge-patch+json" \\
493+
-X PATCH \\
494+
"https://kubernetes.default.svc/api/v1/namespaces/\$NS/pods/\$POD" \\
495+
--data-binary @/tmp/patch.json >/dev/null
496+
then
497+
echo "labeled for pod \$NS/\$POD"
498+
else
499+
echo "pod label skipped for \$NS/\$POD"
500+
exit 0
501+
fi
502+
set -x
503+
"""
504+
505+
}
506+
447507
/**
448508
* Run a lsstsw build.
449509
*
@@ -2522,6 +2582,7 @@ def void nodeWrap(Closure run) {
25222582
def void nodeWrap(String label, Closure run) {
25232583
node(label) {
25242584
printK8sVars()
2585+
labelPod()
25252586
run()
25262587
}
25272588
}

0 commit comments

Comments
 (0)