This commit is contained in:
Pavel Guzaev
2024-03-09 17:36:50 +05:00
commit 431b4f5cfd
44 changed files with 3239 additions and 0 deletions

235
jenkins/1cdb.groovy Normal file
View File

@@ -0,0 +1,235 @@
import java.text.SimpleDateFormat
import groovy.transform.Field
@Field List props = []
pipeline {
agent none
parameters {
choice(
name: 'ACTION',
choices: ['DAY','WEEK'],
description: 'Выбор бэкапа'
)
}
options {
disableConcurrentBuilds()
timestamps()
buildDiscarder(logRotator(numToKeepStr: '10'))
skipDefaultCheckout()
timeout(time: 360, unit: 'MINUTES')
}
environment {
BUILD_USER = getBuildUser()
CURRENT_DATE = new Date().format( 'dd.MM.yy_HH:mm' )
}
triggers{
parameterizedCron('''
30 19 * * 1,2,3,4 %ACTION=DAY
30 19 * * 5 %ACTION=WEEK
''')
}
stages {
stage('Prepare_MASTER') {
agent {label "master"}
steps {
deleteDir()
gitClone("master")
}
}
stage('Prepare_SITE') {
agent {label "net"}
steps {
deleteDir()
gitClone("master")
}
}
/////
stage('1CDB') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'DAY'; environment name: 'ACTION', value: 'WEEK'}
}
steps {
pwsh script: "./site/1cdb_session.ps1 1CDB"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: '1C backup success!!!', chatId: 648920818)
}
}
////
stage('Move_day') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'MOVE'; environment name: 'ACTION', value: 'DAY'}
}
steps {
sh '''
mv /srv/SITE/1CDB*.7z /srv/SITE/1CDB/
find /srv/SITE/1CDB/ -name "*.7z" -mtime +10 -exec rm -f {} \\;
'''
telegramSend(message: 'Day 1CDB MOVE success!!!', chatId: 648920818)
}
}
////
////
stage('Move_week') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'MOVE'; environment name: 'ACTION', value: 'WEEK'}
}
steps {
sh '''
mv /srv/SITE/1CDB*.7z /srv/1CSRV/1CDB/
find /srv/1CSRV/1CDB/ -name "*.7z" -mtime +60 -exec rm -f {} \\;
'''
telegramSend(message: 'WEEK 1CDB MOVE success!!!', chatId: 648920818)
}
}
////
}
post {
success {
node ("master") {
jabberNotify notificationStrategy: 'success', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Бэкап 1С завершен успешно', targets: 'user@domen'
}
}
aborted {
node ("master") {
jabberNotify notificationStrategy: 'aborted', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Бэкап 1С пришлось остановить', targets: 'user@domen'
}
}
failure {
node ("master") {
jabberNotify notificationStrategy: 'failure', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'Бэкап 1С завершился с ошибкой', 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> - выполняемое действие (DAY, WEEK)
<ul>
<li>
<b>DAY</b> - Ежедневный бэкап 1С, автоматически делается в 19:30 с понедельника по четверг, архивы в C:\\Backup\\1CDB на сервере SITE
</li>
<li>
<b>WEEK</b> - Еженедельный бэкап 1С, автоматически делается в 19:30 в пятницу, архивы в C:\\Backup\\1CDB на сервере 1CSRV
</li>
</ul>
</li>
</ul>
</body>
</html>
"""
}

10
jenkins/1cdb_session.ps1 Normal file
View File

@@ -0,0 +1,10 @@
$Action=$args[0]
Write-Host $Action
$Cred = New-Object System.Management.Automation.PSCredential ('user', (ConvertTo-SecureString 'passwd' -AsPlainText -Force))
Invoke-Command -ComputerName 192.16.0.1 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Remove-Item "D:\SRV\1CDB\*.bak"}
Invoke-Command -ComputerName 192.16.0.1 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Backup-SqlDatabase -ServerInstance "." -Database "KD" -BackupFile "D:\SRV\1CDB\KD.bak"}
Invoke-Command -ComputerName 192.16.0.1 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Backup-SqlDatabase -ServerInstance "." -Database "IP" -BackupFile "D:\SRV\1CDB\IP.bak"}
Invoke-Command -ComputerName 192.16.0.1 -Credential $Cred -Authentication Negotiate -ScriptBlock {..\.jenkins\workspace\1cdb_backup\site\site_backup.ps1 $Using:Action}

218
jenkins/1csrv.groovy Normal file
View File

@@ -0,0 +1,218 @@
import java.text.SimpleDateFormat
import groovy.transform.Field
@Field List props = []
pipeline {
agent none
parameters {
choice(
name: 'ACTION',
choices: ['ALL','1CDB','KD'],
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 23 * * 5 %ACTION=KD
''')
}
stages {
stage('Prepare_MASTER') {
agent {label "master"}
steps {
deleteDir()
gitClone("master")
}
}
stage('Prepare_1CSRV') {
agent {label "mssql"}
steps {
deleteDir()
gitClone("master")
}
}
/////
stage('Backup_KD') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'KD'; environment name: 'ACTION', value: 'ALL'}
}
steps {
pwsh script: "./1csrv/1csrv_session.ps1 KD $env.JOB_NAME"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: 'KD backup success!!!', chatId: 648920818)
}
}
/////
stage('Backup_1C_MSSQL') {
agent {label "master"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: '1CDB'; environment name: 'ACTION', value: 'ALL'}
}
steps {
pwsh script: "./1csrv/1csrv_session.ps1 1CDB $env.JOB_NAME"
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","Backup success!!!")
telegramSend(message: '1C backup success!!!', chatId: 648920818)
}
}
}
post {
success {
node ("master") {
jabberNotify notificationStrategy: 'success', extraMessage: 'MSSQL и Сетевые диски успешно сбэкапированы, можно забирать', 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>Задача бэкапирует базы данных 1С</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>1CDB</b> - Бэкап Баз Данных 1С, после выполнения, архив доступен для скачки по ссылке
</li>
<li>
<b>KD</b> - Бэкап Конструкторской документации
</li>
</ul>
</li>
<li>
<b>Бэкапы тут</b> - <a href="\\\\1CSRV.domen\\Backup">\\\\1CSRV.domen\\Backup</a>
</li>
</ul>
</body>
</html>
"""
}

20
jenkins/1csrv_session.ps1 Normal file
View File

@@ -0,0 +1,20 @@
$Action=$args[0]
$Job=$args[1]
Write-Host $Action
Write-Host $Job
$Cred = New-Object System.Management.Automation.PSCredential ('user', (ConvertTo-SecureString 'password' -AsPlainText -Force))
if ( $Action -match '1CDB')
{
Invoke-Command -ComputerName 192.16.0.6 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Remove-Item "D:\1CDB\*.bak"}
Invoke-Command -ComputerName 192.16.0.6 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Backup-SqlDatabase -ServerInstance "." -Database "KD" -BackupFile "D:\1CDB\KD.bak"}
Invoke-Command -ComputerName 192.16.0.6 -Credential $Cred -Verbose -Authentication Negotiate -ScriptBlock {Backup-SqlDatabase -ServerInstance "." -Database "IP" -BackupFile "D:\1CDB\IP.bak"}
Invoke-Command -ComputerName 192.16.0.6 -Credential $Cred -Authentication Negotiate -ScriptBlock {..\.jenkins\workspace\1csrv_backup\1csrv\1csrv_backup.ps1 $Using:Action}
}
if ( $Action -match 'KD')
{
Invoke-Command -ComputerName 172.16.0.6 -Credential $Cred -Authentication Negotiate -ScriptBlock {..\.jenkins\workspace\1csrv_backup\1csrv\1csrv_backup.ps1 $Using:Action}
}

204
jenkins/astarot.groovy Normal file
View File

@@ -0,0 +1,204 @@
import java.text.SimpleDateFormat
import groovy.transform.Field
@Field List props = []
pipeline {
agent none
parameters {
choice(
name: 'ACTION',
choices: ['ALL','WEB','LINUX'],
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 21 * * 5 %ACTION=WEB
''')
}
stages {
stage('Prepare_ASTAROT') {
agent {label "site"}
steps {
deleteDir()
gitClone("master")
}
}
stage('WEB_BACKUP') {
agent {label "site"}
when { beforeAgent true
anyOf {environment name: 'ACTION', value: 'WEB'; environment name: 'ACTION', value: 'ALL'}
}
steps {
sh '''
rsync -avHAXxz --progress --delete --numeric-ids --exclude devpribor.ru/core/cache/* -e ssh intertest@188.120.241.91://var/www/intpribor/www /srv/archive/site/dev/
rsync -avHAXxz --progress --delete --numeric-ids --exclude interpribor.ru/core/cache/* -e ssh intertest@188.120.241.91://var/www/devtest/www /srv/archive/site/test/
rsync -avHAXxz --progress --delete --numeric-ids --exclude interpribor.ru/core/cache/* -e ssh interbase@82.146.55.174://var/www/intpribor/www /srv/archive/site/prod/
ssh interbase@82.146.55.174 "mysqldump --host 127.0.0.1 --port 3307 --column-statistics=0 --no-tablespaces -ucarpribor -p1L5n0E7Ah8A9 carpribor | gzip -9" > /srv/archive/site/prod/carpribor_$(date +%d%m%Y).sql.gz
tar -zcvf /mnt/backup/site/site_prod_$(date +%d%m%Y).tar.gz /srv/archive/site/prod/
tar -zcvf /mnt/backup/site/site_dev_$(date +%d%m%Y).tar.gz /srv/archive/site/dev/www/devpribor.ru/
find /mnt/backup/site/ -name "*.gz" -mtime +27 -exec rm -f {} \\;
'''
updateDesc("${env.STAGE_NAME}")
sendME("${env.STAGE_NAME}","WEB Backup success!!!")
telegramSend(message: 'WEB BACKUP success!!!', chatId: 648920818)
}
}
////
}
post {
success {
node ("site") {
jabberNotify notificationStrategy: 'success', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'WEB BACKUP SUCCESS!!!', targets: 'user@domen'
}
}
aborted {
node ("site") {
jabberNotify notificationStrategy: 'aborted', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'WEB BACKUP ABORT!!!', targets: 'user@domen'
}
}
failure {
node ("site") {
jabberNotify notificationStrategy: 'failure', notifyCulprits: true, notifyFixers: true, notifySuspects: true, notifyUpstreamCommitters: true, extraMessage: 'WEB BACKUP ERROR!!!', 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>WEB</b> - Бэкап Продуктивного и тестового сайтов
</li>
<li>
<b>LINUX</b> - Бэкап Linux server with rsync
</li>
</ul>
</li>
<li>
<b>Бэкапы тут</b> - <a href="\\\\ASTAROT.domen\\Backup">\\\\ASTAROT.domen\\Backup</a>
</li>
</ul>
</body>
</html>
"""
}

405
jenkins/branch_ncc.groovy Normal file
View File

@@ -0,0 +1,405 @@
import java.text.SimpleDateFormat
import groovy.transform.Field
// import java.time.*
// import hudson.model.Computer.ListPossibleNames
@Field int NUMBER_OF_STANDS = 4
@Field String STAND_NAME_TEMPLATE = "nccbranch"
pipeline {
agent {
node {
label 'ncc-apps'
customWorkspace '/opt/ncc/'
}
}
parameters {
choice(
name: 'ACTION',
choices: ['Deploy', 'Prolong', 'Stop'],
description: 'Выбор действия'
)
choice(
name: 'STAND',
choices: "${getStandsNames()}",
description: 'Выбор стенда'
)
string(
name: 'VERSION',
defaultValue: '7.5',
description: 'Номер версии NCC'
)
string(
name: 'NOT_OFF',
defaultValue: getParamNotOff(),
description: 'Не выключать до указанного времени, например, "31/01 20-00"'
)
booleanParam(
name: 'clearDB',
defaultValue: false,
description: "Очистить базу данных"
)
}
options {
timestamps()
buildDiscarder(logRotator(numToKeepStr: '10'))
skipDefaultCheckout()
timeout(time: 40, unit: 'MINUTES')
}
environment {
BUILD_USER = getBuildUser()
CHAT_PORT = getPort("${STAND}")
DIR_STAND = "/opt/ncc/${STAND}"
CURRENT_DATE = new Date().format( 'dd.MM.yy_HHmm' )
COMPOSE_INTERACTIVE_NO_CLI = 1
COMPOSE_HTTP_TIMEOUT = 180
}
triggers{
parameterizedCron('''
02 3 * * * %STAND=nccbranch4;ACTION=Deploy;BUILD_USER=Jenkins
''')
}
stages {
stage('Stop') {
when {
beforeAgent true
environment name: 'ACTION', value: 'Stop'
}
steps {
dir("${DIR_STAND}/ncc-compose/") {
sh '''
docker version
docker-compose --ansi never version
docker-compose --ansi never ps && docker-compose --ansi never down --remove-orphans --volumes || exit 0
'''
}
}
}
stage('PrepareDB') {
when {
beforeAgent true
environment name: 'clearDB', value: 'false'
not { environment name: 'VERSION', value: '' }
environment name: 'ACTION', value: 'Deploy'
}
steps {
dir("${DIR_STAND}/ncc-compose/") {
sh '''
docker version
docker-compose --ansi never version
docker login -u user -p 123 sd-docker-registry2.naumen.ru
docker login -u pavykeka -p pesogane33145713 ncc-75.nau.team
rm -rf ./createdb/*.bak || true
'''
}
dir("${DIR_STAND}") {
sh '''
echo "BUILD_ID=${BUILD_ID}" > build.properties
echo "BUILD_USER=${BUILD_USER}" >> build.properties
echo "VERSION=${VERSION}" >> build.properties
echo "NOT_OFF=${NOT_OFF}" >> build.properties
'''
}
updateDesc()
}
}
stage('Prepare') {
when {
beforeAgent true
environment name: 'clearDB', value: 'true'
not { environment name: 'VERSION', value: '' }
environment name: 'ACTION', value: 'Deploy'
}
steps {
dir("${DIR_STAND}/ncc-compose/") {
sh '''
docker version
docker-compose --ansi never version
docker-compose --ansi never ps && docker-compose --ansi never down --remove-orphans --volumes || exit 0
docker login -u user -p 123 sd-docker-registry2.naumen.ru
docker login -u pavykeka -p pesogane33145713 ncc-75.nau.team
sudo chown -R administrator. ./
'''
}
dir("${DIR_STAND}") {
deleteDir()
gitClone("master")
sh '''
echo "BUILD_ID=${BUILD_ID}" > build.properties
echo "BUILD_USER=${BUILD_USER}" >> build.properties
echo "VERSION=${VERSION}" >> build.properties
echo "NOT_OFF=${NOT_OFF}" >> build.properties
mkdir ./ncc-compose/dbdata
sudo chown -R 100 ./ncc-compose/consul-data
sudo chown -R 777 ./ncc-compose/dbdata
sudo chown -R 777 ./ncc-compose/spool
sudo chown -R 777 ./ncc-compose/createdb
'''
}
updateDesc()
}
}
stage('Deploy') {
when {
beforeAgent true
not { environment name: 'VERSION', value: '' }
environment name: 'ACTION', value: 'Deploy'
}
steps {
script {
currentBuild.description = "${STAND} <- $VERSION <br> Не выключать до $NOT_OFF"
}
dir("${DIR_STAND}/ncc-compose/") {
writeFile file:".env_tmp", text:getEnvFile()
sh '''
cat .env_tmp > .env
docker-compose --ansi never config
docker-compose --ansi never up --build -d
sudo chown -R 777 spool
'''
}
dir("${DIR_STAND}/ncc-compose/") {
sh 'docker-compose --ansi never ps || exit 0'
}
}
}
stage('Prolong') {
when {
beforeAgent true
environment name: 'ACTION', value: 'Prolong'
}
steps {
script {
currentBuild.description = "${STAND} <- Prolong <br> Не выключать до $NOT_OFF"
}
dir("${DIR_STAND}") {
sh 'sed -i -r "s|(NOT_OFF=).*|\\1${NOT_OFF}|" build.properties'
}
}
}
}
post {
always {
updateDesc()
emailext (
subject: "${currentBuild.currentResult}: Pipeline ${currentBuild.fullDisplayName}",
body: "${currentBuild.currentResult} Pipeline: ${currentBuild.fullDisplayName}:\n${currentBuild.absoluteUrl}",
recipientProviders: [[$class: 'RequesterRecipientProvider']]
)
}
}
}
// def node = jenkins.model.Jenkins.instance.getNode( "ncc-ci" )
// def node_ip = node.computer.getChannel().call(new ListPossibleNames())
// println "${node_ip}"
def getParamNotOff() {
return new Date().plus(1).format( 'dd/MM ' ) + "20-00"
// LocalDateTime t = LocalDateTime.now();
// return t as String
}
def getBuildUser() {
return currentBuild.rawBuild.getCause(Cause.UserIdCause)?.getUserId()
}
def getProjectDirectory() {
return fileExists("${DIR_STAND}") ? "${DIR_STAND}" : "${DIR_STAND}"
}
def getPort(String stand) throws NumberFormatException {
int initialPort = 10000
return initialPort + (stand - STAND_NAME_TEMPLATE).toInteger()
}
def getEnvFile() {
String stand = "${STAND}"
int initialDbPort = 54320
int initalNCCPort = 10100
int initalNCCFPort = 10110
int initialCONSULPort = 8000
int initialWSPort = 10800
int NCCPort = initalNCCPort + (stand - STAND_NAME_TEMPLATE).toInteger()
int CONSULPort = initialCONSULPort + (stand - STAND_NAME_TEMPLATE).toInteger()
int NCCFPort = initalNCCFPort + (stand - STAND_NAME_TEMPLATE).toInteger()
int WSPort = initialWSPort + (stand - STAND_NAME_TEMPLATE).toInteger()
int dbPort = initialDbPort + (stand - STAND_NAME_TEMPLATE).toInteger()
return """
COMPOSE_PROJECT_NAME=${stand}
COMPOSE_FILE=docker-compose.yaml
chatOnSite=https://${stand}.nsd.naumen.ru/chatOnSite/
URL=https://${stand}.nsd.naumen.ru/workplace.html#/login
CHAT_PORT=${CHAT_PORT}
NCC_PORT=${NCCPort}
NCCF_PORT=${NCCFPort}
DB_PORT=${dbPort}
CONSUL_PORT=${CONSULPort}
WS_PORT=${WSPort}
"""
}
def gitClone(String stand) {
checkout poll: false, scm: [
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
userRemoteConfigs: [[url: 'git@gitsd.naumen.ru:ops/compose.git']]
]
}
def updateDesc() {
def d = [BUILD_ID: '', BUILD_USER: '', VERSION: '', NOT_OFF: '']
def props = []
for (int i = 1; i <= NUMBER_OF_STANDS; i++) {
prop = readProperties defaults: d, file: "/opt/ncc/nccbranch${i}/build.properties"
props << prop
}
println props
def item = Jenkins.instance.getItemByFullName("${JOB_NAME}")
item.setDescription("${getDescTemplate(props)}")
}
def nowTime() {
return new Date().format( 'yyyy-MM-dd HH:mm' )
}
def getStandStatus(String notOff) {
if (!(notOff =~ /^[0-9][0-9]?\/[0-9][0-9] [0-9][0-9]?[-:][0-9][0-9]/)) {
standStatus = ''
} else {
yy = new Date().format( 'yyyy' )
fullDate = yy + ' ' + notOff
till = new SimpleDateFormat("yyyy dd/MM HH-mm").parse(fullDate).getTime()
now = new Date().getTime()
standStatus = (till > now) ? 'stand_busy' : 'stand_free'
}
return standStatus
}
def getDescTemplate(List props) {
return """
<?xml version="1.0" encoding="UTF-8"?><html>
<body>
<b>Задача обновляет один из стендов из ветки</b>
<div style="font-wight:bold;">
Если сборка не прошла, то обращаться в ТПиВИ
</div>
<style>
.stand_table { margin:15px 0; /*border: 1px solid #cdcdcd;*/ border:none; border-collapse:collapse; border-spacing:0; font-size:100%; width: 90%;}
.stand_table th, .stand_table td { padding:3px 4px; border: 1px solid #cdcdcd; }
.stand_table th { text-align:center; font-weight:bold; border: 1px solid #cdcdcd; background:#f9efcf; }
.stand_table .last_update { text-align:right; font-size:75%; border:none; }
.stand_table .stand:hover { background:#f6faf2; }
.stand_table .col_title { width:120px; }
.stand_table .col_date { width:150px; }
.stand_table .col_link { width:120px; }
.stand_free { background:#B4EEA1; color:#349714; }
.stand_busy { background:#FF8282; color:#B21818; }
</style>
<table class="stand_table">
<tr>
<th colspan="8" style="text-align:left;">Стенды:</th>
</tr>
<tr>
<th abbr="stand">Стенд</th>
<th abbr="link">Административный интерфейс admin/admin</th>
<th abbr="chatOnSite">Чат на сайте</th>
<th abbr="buildnum">Номер сборки</th>
<th abbr="userid">Пользователь</th>
<th abbr="ip">Нода</th>
<th abbr="ncc_port">Порт шины</th>
<th abbr="fx_url">Файловое Хранилище</th>
<th abbr="consul_port">Порт консула</th>
<th abbr="notoff">Не отключать</th>
</tr>
${props.collect { prop ->
def idx = props.findIndexOf { it.equals(prop) }
return """ <tr class="stand">
<td abbr="stand">${idx+1}</td>
<td abbr="link">
<a href="https://nccbranch${idx+1}.nsd.naumen.ru/workplace.html#/login">https://nccbranch${idx+1}.nsd.naumen.ru/workplace.html#/login</a>
</td>
<td abbr="chatOnSite">
<a href="https://nccbranch${idx+1}.nsd.naumen.ru/chatOnSite/">https://nccbranch${idx+1}.nsd.naumen.ru/chatOnSite/</a>
</td>
<td abbr="buildnum">${prop.BUILD_ID}</td>
<td abbr="userid">${prop.BUILD_USER}</td>
<td abbr="ip">nccbranch${idx+1}.sd.naumen.ru</td>
<td abbr="ncc_port">1010${idx+1}</td>
<td abbr="fx_url">
<a href="https://nccbranch${idx+1}.nsd.naumen.ru/fx">https://nccbranch${idx+1}.nsd.naumen.ru/fx</a>
</td>
<td abbr="consul_port">800${idx+1}</td>
<td abbr="notoff" class="${getStandStatus(prop.NOT_OFF)}">${prop.NOT_OFF}</td>
</tr>"""
}.join('')}
<tr>
<td align="right" abbr="lastupd" COLSPAN="8" class="last_update">Last updated: ${nowTime()}</td>
</tr>
</table>
<br/>
<br/>
<br/>При запуске необходимо выбрать стенд для обновления и указать параметры:
<br/>
<ul>
<li>
<b>ACTION</b> - выполняемое действие (Deploy, Prolong, Stop)
<ul>
<li>
<b>Deploy</b> - развертывание стенда. Используемые параметры: VERSION, NOT_OFF, крыжик clearDB (пересоздаст с настройками по умолчанию)
</li>
<li>
<b>Prolong</b> - продление стенда. Используемые параметры: NOT_OFF
</li>
<li>
<b>Stop</b> - остановить стенд. По просьбе тестирования, для эмуляции сбоя. Последующий запускс стенда через Delpoy
</li>
</ul>
</li>
<li>
<b>STAND</b> - имя стенда
</li>
<li>
<b>VERSION</b> - версия системы, заложено на будущее, а настоящее время, интеграция тестировалась только на версии 7.5
</li>
<li>
<b>Не отключать</b> - указать время и дату, до которой нужен стенд (поле информативное, стенд не будет автоматически выключен)
</li>
<li>
<b>Нода</b> - данные указать в поле Адрес сервера при настройке интеграции со стороны NSD
</li>
<li>
<b>Порт шины</b> - данные для поля порт при настройке интеграции со стороны NSD
</li>
<li>
<b>Файловое хранилище</b> - Пишем в поле файлового хранилища при настроке интеграции со стороны NSD
</li>
<li>
<b>Логины к чату на сайте</b> - Логины в системе: <b>portal1...portal8</b> (под портальные бранчи), <b>test1...test4</b> (под ncc). Пароли для всех <b>123</b>. Менять, добавлять, логины к витринам: <b>http://nccbranch1.sd.naumen.ru:8001/</b>.
</li>
</ul>
</body>
</html>
"""
}
def getStandsNames() {
def standsNames = ''
for (int i = 1; i <= NUMBER_OF_STANDS; i++) {
standsNames += "nccbranch${i}"
standsNames += "${i.equals(NUMBER_OF_STANDS) ? "" : "\n"}"
}
return standsNames
}

237
jenkins/getmailbox.groovy Normal file
View File

@@ -0,0 +1,237 @@
import java.text.SimpleDateFormat
import groovy.transform.Field
// Misc manipulations
import java.nio.charset.StandardCharsets
pipeline {
agent {
node {
label 'mail_acc'
}
}
parameters {
choice(
name: 'ACTION',
choices: ['New-Mail', 'Delete-Mail', 'Get-Mail'],
description: 'Выбор действия, Get-Mail - только обновит список пользователей'
)
string(
name: 'email',
defaultValue: '@domain',
description: 'Желаемый email пользователя, если меняем пароль, выбираем из списка, при создании нового, выбрать свободное имя'
)
string(
name: 'MailPass',
defaultValue: '123qweASD',
description: 'Пароль пользователя, стандартный лучше не использовать, во избежании случайного подключения другого пользователя'
)
booleanParam(
name: 'NeedSharedMail',
defaultValue: false,
description: 'Нужны права на общий ящик: shared@domain'
)
}
options {
disableConcurrentBuilds()
timestamps()
buildDiscarder(logRotator(numToKeepStr: '10'))
skipDefaultCheckout()
timeout(time: 40, unit: 'MINUTES')
}
environment {
BUILD_USER = getBuildUser()
CURRENT_DATE = new Date().format('dd.MM.yy_HHmm')
DIR_MAIL = "./jenkins/ps1/"
username = "${BUILD_USER}"+"${BUILD_ID}"
}
stages {
stage('getmail') {
when {
beforeAgent true
environment name: 'ACTION', value: 'Get-Mail'
}
steps {
dir("${DIR_MAIL}") {
powershell '''
./getmailbox.ps1
'''
updateDesc('mailbox.nausd')
}
}
}
stage('newmail') {
when {
beforeAgent true
environment name: 'ACTION', value: 'New-Mail'
}
steps {
dir("${DIR_MAIL}") {
println "${username}"
println "${email}"
println "${MailPass}"
powershell script: "./newmailbox.ps1 $username $email $MailPass $NeedSharedMail"
updateDesc('mailbox.nausd')
}
}
}
stage('removemailbox') {
when {
beforeAgent true
environment name: 'ACTION', value: 'Delete-Mail'
}
steps {
dir("${DIR_MAIL}") {
println "${username}"
println "${email}"
println "${MailPass}"
powershell script: "./removemailbox.ps1 $email"
updateDesc('mailbox.nausd')
}
}
}
}
}
def updateDesc(String propertyFile) {
def keyMapping = [
DisplayName: 'UserName',
WindowsEmailAddress: 'EMail',
CustomAttribute1: 'Password',
]
def props = []
def mailInfo = [:]
readFile("${propertyFile}").split('\n').each { line ->
if (!line.isEmpty()) {
def fields = line.split(':').collect { it.trim() }
mailInfo.put(keyMapping.get(fields.first()), fields.last())
if (fields.first().equals(keyMapping.keySet().last())) {
props.add(mailInfo.clone())
mailInfo.clear()
}
} else {
return
}
}
int NUMBER_OF_MAILS = props.size();
println("NUMBER_OF_MAILS: ${NUMBER_OF_MAILS}")
props.each {
println("Mail Info <br />: ${it}")
}
def item = Jenkins.instance.getItemByFullName("${JOB_NAME}")
item.setDescription("${getDescTemplate(props)}")
}
def getBuildUser() {
return currentBuild.rawBuild.getCause(Cause.UserIdCause)?.getUserId()
}
/*
def gitClone(String stand) {
checkout poll: false, scm: [
$class : 'GitSCM',
branches : [[name: 'master']],
doGenerateSubmoduleConfigurations: false,
userRemoteConfigs : [[url: 'git@gitsd.naumen.ru:repo/scripts_tpivi.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>Задача управляет тестовым почтовым сервером <a href="https://naupp.naumen.ru/sd/operator/#uuid:hardware\$102717801">Exchange</a></b>
<div style="font-wight:bold;">
Если сборка не прошла, то обращаться в ТПиВИ
</div>
<style>
.mail_table { margin:15px 0; border:none; border-collapse:collapse; border-spacing:0; font-size:100%; width: 100%;}
.mail_table th, .stand_table td { padding:3px 4px; border: 1px solid #cdcdcd; }
.mail_table th { text-align:center; font-weight:bold; border: 1px solid #cdcdcd; background:#f9efcf; }
.mail_table .last_update { text-align:right; font-size:75%; border:none; }
.mail_table .stand:hover { background:#f6faf2; }
.mail_table .col_title { width:120px; }
</style>
<table class="mail_table">
<tr>
<th colspan="8" style="text-align:left;">Почтовые ящики:</th>
</tr>
<tr>
<th abbr="UserName">Имя пользователя</th>
<th abbr="EMail">Почтовый ящик пользователя</th>
<th abbr="Password">Пароль пользователя</th>
</tr>
${props.collect { prop ->
def idx = props.findIndexOf { it.equals(prop) }
return """ <tr class="mail">
<td abbr="UserName">${prop.UserName}</td>
<td abbr="EMail">${prop.EMail}</td>
<td abbr="Password">${prop.Password}</td>
</tr>"""
}.join('')}
</table>
<br/>
<br/>
<br/>При запуске необходимо указать параметры:
<br/>
<ul>
<li>
<b>ACTION</b> - выполняемое действие (New-Mail, Delete-Mail, Get-Mail)
<ul>
<li>
<b>New-Mail</b> - Создание нового ящика пользователя или обновление существующего
</li>
<li>
<b>Delete-Mail</b> - Удаление ящика пользователя в котором отпала необходимость ( попутно вычистит ящики к которым не было подключения более года )
</li>
<li>
<b>Get-Mail</b> - Обновит список почтовых ящиков с сервера
</li>
</ul>
</li>
<li>
<b>Имя пользователя</b> - Формируется из параметров сборки
</li>
<li>
<b>Почтовый ящик пользователя</b> - Должен быть в формате login@domain. Допускаются только символы латинского алфавита
</li>
<li>
<b>Пароль пользователя</b> - Не менее 8 сиволов разного регистра и цифры. Рекомендуется использовать пароль отличный от стандартного
</li>
<li>
<b>shared@domain</b> - Общий почтовый ящик, подключается галочкой в сборке при создании нового или изменениии параметров текущего почтового ящиков
</li>
<li>
<b>Веб интерфейс для доступа</b> - <a href="https://win2016-dc-exch.domain/owa/">https://win2016-dc-exch.domain/owa/</a>
</li>
</ul>
</body>
</html>
"""
}

8
jenkins/getmailbox.ps1 Normal file
View File

@@ -0,0 +1,8 @@
$username='adm_exch@domain'
$pwsd='superpass'
$password = ConvertTo-SecureString $pwsd -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ($username, $password)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://win2016-dc-exch.domain/powershell/ -Authentication Basic -AllowRedirection -Credential $Cred
Invoke-Command -Session $Session -ScriptBlock { Get-Mailbox -OrganizationalUnit domain/NSD -ResultSize Unlimited } | Format-List DisplayName, WindowsEmailAddress, CustomAttribute1 | Out-File -Encoding UTF8 mailbox.nausd
Remove-PSSession $Session

29
jenkins/newmailbox.ps1 Normal file
View File

@@ -0,0 +1,29 @@
$Cred = New-Object System.Management.Automation.PSCredential ('adm_exch@domain', (ConvertTo-SecureString 'superpass' -AsPlainText -Force))
$UserName=$args[0]
$Email=$args[1]
$MailPass=$args[2]
$NeedSharedMail=$args[3]
Write-Host $UserName
Write-Host $Email
Write-Host $MailPass
Write-Host $NeedSharedMail
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://win2016-dc-exch.domain/powershell/ -Authentication Basic -AllowRedirection -Credential $Cred
Import-PSSession $Session -DisableNameChecking -AllowClobber
if(Get-Mailbox $Email) { Write-Host "$Email is ALREADY create" }
else { New-Mailbox -Name "$UserName" -UserPrincipalName "$Email" -Password (ConvertTo-SecureString "$MailPass" -AsPlainText -Force) -DisplayName "$UserName" -OrganizationalUnit NSD }
Set-Mailbox "$Email" -CustomAttribute1 "$MailPass" -Password (ConvertTo-SecureString "$MailPass" -AsPlainText -Force) -Force -Confirm:$false
if($NeedSharedMail -eq "True")
{
Add-MailboxPermission -User "$Email" -AccessRights FullAccess -InheritanceType All Shared@domain
Add-ADPermission -Identity "CN=shared,OU=Shared,DC=nausd,DC=local" -User "$Email" -ExtendedRights "Send As"
Set-Mailbox Shared -GrantSendOnBehalfTo "$Email"
}
Get-Mailbox -OrganizationalUnit NSD -ResultSize Unlimited | Format-List DisplayName, WindowsEmailAddress, CustomAttribute1 | Out-File -Encoding UTF8 mailbox.nausd
Remove-PSSession $Session

19
jenkins/removemailbox.ps1 Normal file
View File

@@ -0,0 +1,19 @@
$Cred = New-Object System.Management.Automation.PSCredential ('adm_exch@domain', (ConvertTo-SecureString 'superpass' -AsPlainText -Force))
$Email=$args[0]
Write-Host $Email
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://win2016-dc-exch.domain/powershell/ -Authentication Basic -AllowRedirection -Credential $Cred
Import-PSSession $Session -DisableNameChecking -AllowClobber
#Invoke-Command -Session $Session -ScriptBlock { Remove-Mailbox -Identity "$Using:Email" -Permanent $true -Force -Confirm:$false }
#Invoke-Command -Session $Session -ScriptBlock { Get-Mailbox -OrganizationalUnit domain/NSD -ResultSize Unlimited } | Format-List DisplayName, WindowsEmailAddress, CustomAttribute1 | Out-File -Encoding UTF8 mailbox.nausd
# Remove email from jenkins
Remove-Mailbox -Identity "$Email" -Permanent $true -Force -Confirm:$false
# Remove Older then 360 days emails
Get-Mailbox -OrganizationalUnit domain/NSD -resultsize unlimited | Get-MailboxStatistics | ?{$_.LastLogonTime -lt (get-date).adddays(-360)} | Remove-Mailbox -Permanent $true -Force -Confirm:$false
Get-Mailbox -OrganizationalUnit NSD -ResultSize Unlimited | Format-List DisplayName, WindowsEmailAddress, CustomAttribute1 | Out-File -Encoding UTF8 mailbox.nausd
Remove-PSSession $Session

256
jenkins/site.groovy Normal file
View File

@@ -0,0 +1,256 @@
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>
"""
}

8
jenkins/site_session.ps1 Normal file
View File

@@ -0,0 +1,8 @@
$Action=$args[0]
$Job=$args[1]
Write-Host $Action
Write-Host $Job
$Cred = New-Object System.Management.Automation.PSCredential ('user', (ConvertTo-SecureString 'passwd' -AsPlainText -Force))
Invoke-Command -ComputerName 172.16.0.1 -Credential $Cred -Authentication Negotiate -ScriptBlock {..\.jenkins\workspace\site_backup\site\site_backup.ps1 $Using:Action}