Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lepffm/4531a8e9a87e0e28472a4f3a6ed1fd4b to your computer and use it in GitHub Desktop.
Save lepffm/4531a8e9a87e0e28472a4f3a6ed1fd4b to your computer and use it in GitHub Desktop.
site healthcheck to slack notification pipeline
/*
* site healthcheck to slack notification pipeline
*
*/
pipeline {
agent any
triggers {
pollSCM('H/10 * * * *') // every 10 min
}
environment {
NOTRACE = '#!/bin/sh -e\n'
slack_webhook = 'https://hooks.slack.com/services/XXXXX/YYYY/XXXX' //
channel = "#your_channnel"
RUN_STATUS = "RUNNING"
}
parameters{
string(defaultValue: 'http://your_site_healthcheck_url/', name: 'url', description: 'server health check url')
}
stages {
stage("get previous healthcheck"){
steps{
script{
if(fileExists('health.txt')){
prevStatus = readFile "health.txt"
}else{ // init
prevStatus = RUN_STATUS
}
println "prevStatus: $prevStatus"
}
}
}
stage("run healthcheck crowd"){
steps {
script{
changed = false
curStatus = 'FAILURE'
try{
txt = sh(returnStdout: true, script: NOTRACE + "curl -s --connect-timeout 3 $params.url").trim()
if(txt.contains(RUN_STATUS)){
curStatus = RUN_STATUS
RESULT = "returned $RUN_STATUS"
}else{
println txt
def matcher = txt =~ /(?ms).*<title>(.*)<\/title>.*/
if( matcher.matches()){
RESULT = "${matcher[0][1]}"
}else{
RESULT = txt
}
}
}catch(exc){
println exc
if(exc.message.contains("exit code 28")){ // curl timeout error code https://ec.haxx.se/usingcurl-returns.html
RESULT = "connection timeout"
}else{
RESULT = exc.message
}
}
println "curStatus: $curStatus"
if(!curStatus.equals(prevStatus)){
changed = true
}
}
}
}
}//stages
post {
always {
script{
if(changed){
msg = "site status . $params.url ${RESULT}"
title = "site status is $curStatus"
payload="payload={ \"channel\": \"$channel\", \"text\": \"$title \n$msg\" }"
println payload
writeFile file: 'health.txt', text: curStatus
sh( script: NOTRACE+"curl -s -X POST -i $SLACK_WEBHOOK -d '$payload'" )
}//if
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment