@@ -444,6 +444,64 @@ 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 manager/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+ writeFile file : ' /tmp/patch.json' , text : jsonLabels
474+
475+ bash '''
476+ set -eu
477+ set +x
478+
479+ SA=/var/run/secrets/kubernetes.io/serviceaccount
480+ [ -r "$SA/token" ] || { echo "not in k8s; skipping pod label"; exit 0; }
481+ NS=$(cat $SA/namespace)
482+ POD=${HOSTNAME}
483+ TOKEN=$(cat $SA/token)
484+ CA=$SA/ca.crt
485+
486+
487+ if curl -sS --fail \
488+ --cacert "$CA" \
489+ -H "Authorization: Bearer $TOKEN" \
490+ -H "Content-Type: application/merge-patch+json" \
491+ -X PATCH \
492+ "https://kubernetes.default.svc/api/v1/namespaces/\$ NS/pods/\$ POD" \
493+ --data-binary @/tmp/patch.json >/dev/null
494+ then
495+ echo "labeled for pod $NS/$POD"
496+ else
497+ echo "pod label skipped for $NS/$POD"
498+ exit 0
499+ fi
500+ set -x
501+ '''
502+
503+ }
504+
447505/**
448506 * Run a lsstsw build.
449507 *
@@ -2522,6 +2580,7 @@ def void nodeWrap(Closure run) {
25222580def void nodeWrap (String label , Closure run ) {
25232581 node(label) {
25242582 printK8sVars()
2583+ labelPod()
25252584 run()
25262585 }
25272586}
0 commit comments