Add scripts

This commit is contained in:
Kirill Krasnov 2023-04-17 01:01:49 +02:00
parent a41cf6ca11
commit b824a0c23e
Signed by: krak
GPG Key ID: 26DAD4655460565C
12 changed files with 298 additions and 0 deletions

21
vars/buildUser.groovy Normal file
View File

@ -0,0 +1,21 @@
def call() {
script {
// // started by commit
// currentBuild.getBuildCauses('jenkins.branch.BranchEventCause')
// // started by timer
// currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause')
// // started by user
// currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
// // started by branch indexing
// currentBuild.getBuildCauses('jenkins.branch.BranchIndexingCause')
def userCause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
def upstreamCause = currentBuild.rawBuild.getCause(Cause.UpstreamCause)
if (userCause == null || upstreamCause != null) {
env.buildUser = "Jenkins"
} else {
def username = userCause.userName[0].split('@')
env.buildUser = username[0]
}
}
}
return this

14
vars/cmd.groovy Normal file
View File

@ -0,0 +1,14 @@
def call(command) {
if (command instanceof ArrayList)
command = concatCommandFromArray(command)
if (env.VERBOSE == "true")
echo command
if (isUnix()) {
sh "${command}"
} else {
bat(encoding: 'utf-8', script: "chcp 65001 > nul\n ${command}")
}
}

31
vars/getBuildUser.groovy Normal file
View File

@ -0,0 +1,31 @@
def call(build) {
if (build.getRawBuild() != null) {
rb = build.rawBuild
} else {
rb = build
}
def userCause = rb.getCause(Cause.UserIdCause)
def upstreamCause = rb.getCause(Cause.UpstreamCause)
println("User cause: " + userCause)
println("Upstream cause: " + upstreamCause)
if (userCause != null) {
userCause.getUserId()
} else if (upstreamCause != null) {
def upstreamProject = upstreamCause.getUpstreamProject()
def upstreamJob = Jenkins.getInstance().getItemByFullName(upstreamProject, hudson.model.Job.class)
if (upstreamJob != null) {
def upstreamBuild = upstreamJob.getBuildByNumber(upstreamCause.getUpstreamBuild())
if (upstreamBuild != null) {
call(upstreamBuild)
// def realUpstreamCause = upstreamBuild.getCause(Cause.UserIdCause)
// println("Upstream cause: " + realUpstreamCause)
// if (realUpstreamCause != null) {
// realUpstreamCause.getUserId()
// }
}
}
}
}

View File

@ -0,0 +1,33 @@
import com.cloudbees.groovy.cps.NonCPS
def triggeredBy = "---"
def iterateCause(build) {
println("build = " + build)
upstreamcause = build.getCause(hudson.model.Cause.UpstreamCause.class)
println("upstreamcause = " + upstreamcause)
if (upstreamcause != null) {
upstreamProject = upstreamcause.getUpstreamProject()
println("upstreamProject = " + upstreamProject)
job = Jenkins.getInstance().getItemByFullName(upstreamProject, hudson.model.Job.class)
println("job = " + job)
if (job != null) {
upstreamBuild = job.getBuildByNumber(upstreamcause.getUpstreamBuild())
println("upstreamBuild = " + upstreamBuild)
if (upstreamBuild != null) {
iterateBuild(upstreamBuild)
}
}
}
// usercause = build.getCause(hudson.model.Cause.UserIdCause.class)
// println("usercause = " + usercause)
// if (usercause != null) {
// triggeredBy = usercause.getUserName()
// }
return;
}
def call(build) {
iterateCause(build.getRawBuild())
}

33
vars/mmApi.groovy Normal file
View File

@ -0,0 +1,33 @@
// Copyright 2022 Kirill Krasnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import groovy.json.JsonOutput
def call(Map config=[:]) {
def channel = 'status'
if (config.channel) {
channel = config.channel
}
def username = 'Jenkins'
if (config.username) {
username = config.username
}
host = config.host
token = config.token
}

85
vars/mmSend.groovy Normal file
View File

@ -0,0 +1,85 @@
import groovy.json.JsonOutput
def call(Map config=[:]) {
def status = 'STARTED'
if (config.status) {
status = "${config.status}"
}
def emoji = ''
switch(status) {
case 'STARTED':
emoji = ':checkered_flag: '
break
case 'SUCCESSFUL':
emoji = ':circleacceptgreenmark: '
break
case 'ABORT':
emoji = ':large_blue_circle: '
break
case 'FAILURE':
emoji = ':circledenyredmark: '
break
default:
emoji = ''
break
}
def attachment = [
fallback: "You have new message Mattermost"
]
if (config.text) {
attachment["text"] = "${config.text}"
} else if (config.message) {
attachment["text"] = "${config.message}"
} else {
attachment["text"] = ""
}
def pretext = ""
if (config.pretext) {
pretext = "${config.pretext}"
} else {
pretext = emoji + "Job [${env.JOB_NAME} #${env.BUILD_NUMBER}](${env.BUILD_URL})"
}
attachment["pretext"] = "${pretext}"
if (config.color) {
attachment["color"] = "${config.color}"
}
if (config.title) {
attachment["title"] = "${config.title}"
}
if (config.footer) {
attachment["footer"] = "${config.footer}"
}
def channel = 'status'
if (config.channel) {
channel = config.channel
}
def username = 'Jenkins'
if (config.username) {
username = config.username
}
def data = [
channel: "${channel}",
username: "${username}",
attachments: [attachment]
]
def json = JsonOutput.toJson(data)
httpRequest (
customHeaders: [[name: 'User-Agent', value: 'Jenkins']],
url: "${config.endpoint}",
contentType: 'APPLICATION_JSON',
httpMode: 'POST', consoleLogResponseBody: true,
requestBody: json,
validResponseCodes: "100:599"
)
}

13
vars/runManually.groovy Normal file
View File

@ -0,0 +1,13 @@
def call() {
def userCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause)
if (userCause == null) {
if (env.VERBOSE == "true")
echo "Run automatic"
return false
} else {
if (env.VERBOSE == "true")
echo "Run manually"
return true
}
}

9
vars/sqlcmdBackup.groovy Normal file
View File

@ -0,0 +1,9 @@
def call(Map config=[:]) {
def srv = config.srv
def db = config.db
def file = config.file
def cmd = 'sqlcmd -S ' + srv + ' -E -Q "BACKUP DATABASE [' + db + "] TO DISK = N'" + file + "' WITH NOFORMAT, INIT, NAME = N'" +
db + "-Full Database Backup'" + ', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10"'
cmd( script: cmd )
}

13
vars/sqlcmdRestore.groovy Normal file
View File

@ -0,0 +1,13 @@
def call(Map config=[:]) {
def srv = config.srv
def oldDB = config.backupDB
def newDB = config.restoreDB
def file = config.backupFile
def dbPath = config.dbPath
def logPath = config.logPath
def script = 'sqlcmd -S ' + srv + ' -E -Q "ALTER DATABASE [' + newDB + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; RESTORE DATABASE [' +
newDB + "] FROM DISK = N'" + file + "' WITH FILE = 1, MOVE N'" + oldDB + "' TO N'" + dbPath + newDB + ".mdf', MOVE N'" +
oldDB + "_log' TO N'" + logPath + newDB + "_log.ldf', NOUNLOAD, REPLACE, STATS = 5; ALTER DATABASE [" + newDB + '] SET MULTI_USER"'
cmd(script: script)
}

17
vars/stepOneScript.groovy Normal file
View File

@ -0,0 +1,17 @@
void call(Map config) {
String scriptPath = config.scriptPath
String[] commandArgs = []
if (config.containsKey('args')) {
commandArgs += config.args
}
commandArgs -= null
String commandArgsStr = commandArgs.join(' ')
bat """
@chcp 65001 >nul
@echo oscript ${scriptPath} ${commandArgsStr}
@oscript -encoding=UTF-8 ${scriptPath} ${commandArgsStr}
"""
}

21
vars/update1C.groovy Normal file
View File

@ -0,0 +1,21 @@
def call() {
// "Сбрасываю все сеансы и блокирую бд %db1C%"
bat 'vrunner session kill --ras %srv1C% --db %db1C% --uccode %ucCode% --lockmessage "%lockMessage%" --v8version %ver1C%'
// Подключаюсь к хранилищу конфигураций %repo1c% в базе данных %db1C%
// bat 'vrunner bindrepo --ibconnection /S%conn1C% --BindAlreadyBindedUser --NotReplaceCfg --uccode %ucCode% --v8version %ver1C% %repoConn% "%repo_USR%" "%repo_PSW%"'
bat 'vrunner loadrepo --ibconnection /S%conn1C% --storage-name %repoConn% --storage-user "%repo_USR%" --storage-pwd "%repo_PSW%" --uccode %ucCode% --v8version %ver1C%'
// Применяю и обновляю конфигурацию %db1C%
bat 'vrunner updatedb --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Подключаюсь к хранилищу расширения %repoConnExt% в базе данных %db1C%
bat 'vrunner loadrepo --storage-name %repoConnExt% --storage-user "%repo_USR%" --storage-pwd "%repo_PSW%" --extension "%extT%" --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Применяю и обновляю %extT% %db1C%
bat 'vrunner updateext %extT% --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Применяю и обновляю конфигурацию %db1C%
bat 'vrunner updatedb --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Пробую открыть базу 1с %db1C%
bat 'vrunner run --command "ЗапуститьОбновлениеИнформационнойБазы;ЗавершитьРаботуСистемы;" --execute $runnerRoot\\epf\\ЗакрытьПредприятие.epf --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Пробую повторно открыть базу 1с %dbUpdate%
bat 'vrunner run --command "ЗапуститьОбновлениеИнформационнойБазы;ЗавершитьРаботуСистемы;" --execute $runnerRoot\\epf\\ЗакрытьПредприятие.epf --ibconnection /S%conn1C% --uccode %ucCode% --v8version %ver1C%'
// Разблокирую бд %db1C% и разрешаю вход в базу
bat 'vrunner session unlock --ras %srv1C% --db %db1C% --uccode %ucCode% --lockmessage "" --v8version %ver1C%'
}

8
vars/version1C.groovy Normal file
View File

@ -0,0 +1,8 @@
def call() {
// определение текущей версии 1С
def scriptToRun = """@echo off
c:\\GitSync\\print_vers_1c.cmd"""
env.ver1C = bat(returnStdout: true, script: scriptToRun).trim()
}