func-msg-notify
library实现即时消息推送
实现消息通知
由于发送消息通知属于通用的功能,因此有必要把消息通知抽象成为通用的功能。
devops.groovy
/**
* notificationSuccess
* @param project
* @param receiver
* @param credentialsId
* @param title
* @return
*/
static def notificationSuccess(String project, String receiver="dingTalk", String credentialsId="dingTalk", String title=""){
new Notification().init(project, receiver, credentialsId, title).notification("success")
}
/**
* notificationFailed
* @param project
* @param receiver
* @param credentialsId
* @param title
* @return
*/
static def notificationFailed(String project, String receiver="dingTalk", String credentialsId="dingTalk", String title=""){
new Notification().init(project, receiver, credentialsId, title).notification("failure")
}
新建Notification.groovy
文件:
package com.luffy.devops
/**
*
* @param type
* @param credentialsId
* @param title
* @return
*/
def init(String project, String receiver, String credentialsId, String title) {
this.project = project
this.receiver = receiver
this.credentialsId = credentialsId
this.title = title
return this
}
def notification(String type){
String msg ="😄👍 ${this.title} 👍😄"
if (this.title == "") {
msg = "😄👍 流水线成功啦 👍😄"
}
// failed
if (type == "failure") {
msg ="😖❌ ${this.title} ❌😖"
if (this.title == "") {
msg = "😖❌ 流水线失败了 ❌😖"
}
}
String title = msg
// rich notify msg
msg = genNotificationMessage(msg)
if( this.receiver == "dingTalk") {
try {
new DingTalk().markDown(title, msg, this.credentialsId)
} catch (Exception ignored) {}
}else if(this.receiver == "wechat") {
//todo
}else if (this.receiver == "email"){
//todo
}else{
error "no support notify type!"
}
}
/**
* get notification msg
* @param msg
* @return
*/
def genNotificationMessage(msg) {
// project
msg = "${msg} \n **项目名称**: ${this.project}"
// get git log
def gitlog = ""
try {
sh "git log --oneline -n 1 \> gitlog.file"
gitlog = readFile "gitlog.file"
} catch (Exception ignored) {}
if (gitlog != null && gitlog != "") {
msg = "${msg} \n **Git log**: ${gitlog}"
}
// get git branch
def gitbranch = env.BRANCH_NAME
if (gitbranch != null && gitbranch != "") {
msg = "${msg} \n **Git branch**: ${gitbranch}"
}
// build tasks
msg = "${msg} \n **Build Tasks**: ${env.BUILD_TASKS}"
// get buttons
msg = msg + getButtonMsg()
return msg
}
def getButtonMsg(){
String res = ""
def buttons = [
[
"title": "查看流水线",
"actionURL": "${env.RUN_DISPLAY_URL}"
],
[
"title": "代码扫描结果",
"actionURL": "http://sonar.luffy.com/dashboard?id=${this.project}"
]
]
buttons.each() {
if(res == ""){
res = " \n \>"
}
res = "${res} --- ["+it["title"]+"]("+it["actionURL"]+") "
}
return res
}
新建DingTalk.groovy
文件:
package com.luffy.devops
import groovy.json.JsonOutput
def sendRequest(method, data, credentialsId, Boolean verbose=false, codes="100:399") {
def reqBody = new JsonOutput().toJson(data)
withCredentials([usernamePassword(credentialsId: credentialsId, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
def response = httpRequest(
httpMode:method,
url: "https://oapi.dingtalk.com/robot/send?access_token=${PASSWORD}",
requestBody:reqBody,
validResponseCodes: codes,
contentType: "APPLICATION_JSON",
quiet: !verbose
)
}
}
def markDown(String title, String text, String credentialsId, Boolean verbose=false) {
def data = [
"msgtype": "markdown",
"markdown": [
"title": title,
"text": text
]
]
this.sendRequest("POST", data, credentialsId, verbose)
}
需要用到Http Request来发送消息,安装一下插件:http_request
jenkinsfile调用
@Library('luffy-devops') _
pipeline {
agent { label 'jnlp-slave'}
options {
timeout(time: 20, unit: 'MINUTES')
gitLabConnection('gitlab')
}
environment {
IMAGE_REPO = "172.21.65.226:5000/eladmin/eladmin-api"
IMAGE_CREDENTIAL = "credential-registry"
DINGTALK_CREDS = credentials('dingTalk')
}
stages {
stage('checkout') {
steps {
checkout scm
updateGitlabCommitStatus(name: env.STAGE_NAME, state: 'success')
}
}
stage('mvn package') {
steps {
container('tools') {
sh 'mvn clean package'
}
updateGitlabCommitStatus(name: env.STAGE_NAME, state: 'success')
}
}
stage('CI'){
failFast true
parallel {
stage('Unit Test') {
steps {
echo "Unit Test Stage Skip..."
}
}
stage('Code Scan') {
steps {
container('tools') {
script{
devops.scan().start()
}
}
}
}
}
}
stage('build-image') {
steps {
container('tools') {
script{
devops.docker(
"${IMAGE_REPO}",
"${GIT_COMMIT}",
IMAGE_CREDENTIAL
).build().push()
}
}
}
}
}
post {
success {
script{
devops.notificationSuccess("eladmin-api","dingTalk","dingTalk")
}
}
failure {
script{
devops.notificationFailed("eladmin-api","dingTalk","dingTalk")
}
}
}
}
企业微信群报警:
Wechat.groovy
package com.luffy.devops
import groovy.json.JsonSlurperClassic
import groovy.json.JsonOutput
def markDown(text, credentialsId, Boolean verbose=false) {
data = [
'msgtype': 'markdown',
'markdown': [
'content': "${text}"
],
]
this.sendMessage(data,credentialsId, verbose)
}
def sendMessage(data, credentialsId, Boolean verbose=false, codes="100:399") {
def reqBody = new JsonOutput().toJson(data)
withCredentials([usernamePassword(credentialsId: credentialsId, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
def response = httpRequest(
httpMode:'POST', url: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${PASSWORD}",
requestBody:reqBody,
validResponseCodes: codes,
contentType: "APPLICATION_JSON",
quiet: !verbose
)
def jsonSlurper = new JsonSlurperClassic()
def json = jsonSlurper.parseText(response.content)
echo "json response: ${json}"
return json
}
}
Notification.groovy
...
if( this.receiver == "dingTalk") {
try {
new DingTalk().markDown(title, msg, this.credentialsId)
} catch (Exception ignored) {}
}else if(this.receiver == "wechat") {
try {
new Wechat().markDown(msg, this.credentialsId)
} catch (Exception ignored) {}
}else if (this.receiver == "email"){
//todo
}else{
error "no support notify type!"
}
}
...
创建凭据wechat-bot-group
,测试
Jenkinsfile
...
post {
success {
script{
devops.notificationSuccess("eladmin-api","wechat","wechat-bot-group")
}
}
failure {
script{
devops.notificationFailed("eladmin-api","wechat","wechat-bot-group")
}
}
}
...