Files
demo/jenkins/site.groovy
Pavel Guzaev 431b4f5cfd all demo
2024-03-09 17:36:50 +05:00

257 lines
7.8 KiB
Groovy
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.text.SimpleDateFormat
import groovy.transform.Field
@Field List props = []
pipeline {
agent none
parameters {
choice(
name: 'ACTION',
choices: ['ALL','PROG','DOC','WORK','MOVE'],
description: 'Выбор бэкапа'
)
}
options {
disableConcurrentBuilds()
timestamps()
buildDiscarder(logRotator(numToKeepStr: '10'))
skipDefaultCheckout()
timeout(time: 2400, unit: 'MINUTES')
}
environment {
BUILD_USER = getBuildUser()
CURRENT_DATE = new Date().format( 'dd.MM.yy_HH:mm' )
}
triggers{
parameterizedCron('''
00 01 * * 6 %ACTION=ALL
''')
}
stages {
stage('Prepare_MASTER') {
agent {label "master"}
steps {
deleteDir()
gitClone("master")
}
}
stage('Prepare_SITE') {
agent {label "net"}
steps {
deleteDir()
gitClone("master")
}
}
/////
stage('Backup_WORK') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'WORK'; environment name: 'ACTION', value: 'ALL'}
}
steps {
pwsh script: "./site/site_session.ps1 WORK $env.JOB_NAME"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: 'WORK backup success!!!', chatId: 648920818)
}
}
/////
/////
stage('Backup_PROG') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'PROG'; environment name: 'ACTION', value: 'ALL'}
}
steps {
pwsh script: "./site/site_session.ps1 PROG $env.JOB_NAME"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: 'PROG backup success!!!', chatId: 648920818)
}
}
/////
stage('Backup_DOC') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'DOC'; environment name: 'ACTION', value: 'ALL'}
}
steps {
pwsh script: "./site/site_session.ps1 DOC $env.JOB_NAME"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: 'DOC backup success!!!', chatId: 648920818)
}
}
////
stage('Move_del') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'MOVE'; environment name: 'ACTION', value: 'ALL'}
}
steps {
sh '''
mv /srv/SITE/*.7z /srv/1CSRV/
find /srv/1CSRV/ -name "*.7z" -mtime +6 -exec rm -f {} \\;
'''
telegramSend(message: 'ALL MOVE success!!!', chatId: 648920818)
}
}
////
}
post {
success {
node ("master") {
jabberNotify notificationStrategy: 'success', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Сетевые диски успешно сбэкапированы, можно забирать', targets: 'user@domen'
}
}
aborted {
node ("master") {
jabberNotify notificationStrategy: 'aborted', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Пришлось остановить', targets: 'user@domen'
}
}
failure {
node ("master") {
jabberNotify notificationStrategy: 'failure', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Бэкап сетевых дисков завершился с ошибкой', targets: 'user@domen'
}
}
}
}
def getBuildUser() {
return currentBuild.rawBuild.getCause(Cause.UserIdCause)?.getUserId()
}
def updateDesc(ACTION)
{
def d = [ACTION: '', BACKUP_DATE: '', END_TIME: '']
END_TIME = new Date().format( 'dd.MM.yy_HH:mm' )
d.ACTION = "${ACTION}"
d.BACKUP_DATE = "${CURRENT_DATE}"
d.END_TIME = "${END_TIME}"
d1 = d.clone()
props << d1
println d1
d.clear()
println props
println d
println "${END_TIME}"
def item = Jenkins.instance.getItemByFullName("${JOB_NAME}")
item.setDescription("${getDescTemplate(props)}")
}
def sendME(ACTION,STATUS)
{
emailext body: "${STATUS}",
subject: "${ACTION}",
to: 'therion@nasda.ru'
}
def gitClone(String stand) {
checkout poll: false, scm: [
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
userRemoteConfigs: [[url: 'git@gitlab.domen:user/sys.git']]
]
}
def scriptDir = getClass().protectionDomain.codeSource.location.path
println "${scriptDir}"
String currentDir = new File(".").getAbsolutePath()
def getDescTemplate(List props) {
return """
<?xml version="1.0" encoding="UTF-8"?><html>
<body>
<b>Задача бэкапирует сетевые диски</b>
<div style="font-wight:bold;">
Если сборка не прошла, звонить :)
</div>
<style>
.backup_table { margin:15px 0; border:none; border-collapse:collapse; border-spacing:0; font-size:100%; width: 100%;}
.backup_table th, .stand_table td { padding:3px 4px; border: 1px solid #cdcdcd; }
.backup_table th { text-align:center; font-weight:bold; border: 1px solid #cdcdcd; background:#f9efcf; }
.backup_table .last_update { text-align:right; font-size:75%; border:none; }
.backup_table .stand:hover { background:#f6faf2; }
.backup_table .col_title { width:120px; }
</style>
<table class="backup_table">
<tr>
<th colspan="8" style="text-align:left;">Задания бэкапа:</th>
</tr>
<tr>
<th abbr="ACTION">Бэкапирование</th>
<th abbr="BACKUP_DATE">Дата выполнения</th>
<th abbr="END_TIME">Время завершения</th>
</tr>
${props.collect { prop ->
def idx = props.findIndexOf { it.equals(prop) }
return """ <tr class="mail">
<td abbr="ACTION">${prop.ACTION}</td>
<td abbr="BACKUP_DATE">${prop.BACKUP_DATE}</td>
<td abbr="END_TIME">${prop.END_TIME}</td>
</tr>"""
}.join('')}
</table>
<br/>
<br/>
<br/>При запуске необходимо указать параметры:
<br/>
<ul>
<li>
<b>ACTION</b> - выполняемое действие (ALL, 1CDB, WORK)
<ul>
<li>
<b>ALL</b> - Выполнение всех задач, планировщик делает по умолчанию в выходной
</li>
<li>
<b>WORK</b> - Бэкап сетевого диска W (WORK)
</li>
<li>
<b>PROG</b> - Бэкап сетевого диска K (PROG)
</li>
<li>
<b>DOC</b> - Бэкап сетевого диска V (DOC)
</li>
<li>
<b>MOVE</b> - Перенос бэкапов в папку на сервере 1CSRV, удаление старых
</li>
</ul>
</li>
<li>
<b>Бэкапы тут</b> - <a href="\\\\1CSRV.domen\\Backup">\\\\1CSRV.domen\\Backup</a>
</li>
</ul>
</body>
</html>
"""
}