blob: c7afbb07dc42f2c65e8a1472e2295600845f68fa [file] [log] [blame]
chnydaf14ea2a2017-05-26 15:07:47 +02001package com.mirantis.mk
2
3/**
Denis Egorenko6fd79ac2018-09-12 13:28:21 +04004 * Setup Docker to run some tests. Returns true/false based on
5 were tests successful or not.
6 * @param config - LinkedHashMap with configuration params:
7 * dockerHostname - (required) Hostname to use for Docker container.
azvyagintsevabcf42e2018-10-05 20:40:27 +03008 * distribRevision - (optional) Revision of packages to use (default proposed).
Denis Egorenko6fd79ac2018-09-12 13:28:21 +04009 * runCommands - (optional) Dict with closure structure of body required tests. For example:
10 * [ '001_Test': { sh("./run-some-test") }, '002_Test': { sh("./run-another-test") } ]
11 * Before execution runCommands will be sorted by key names. Alpabetical order is preferred.
12 * runFinally - (optional) Dict with closure structure of body required commands, which should be
13 * executed in any case of test results. Same format as for runCommands
14 * updateRepo - (optional) Whether to run common repo update step.
15 * dockerContainerName - (optional) Docker container name.
16 * dockerImageName - (optional) Docker image name
17 * dockerMaxCpus - (optional) Number of CPUS to use in Docker.
18 * dockerExtraOpts - (optional) Array of Docker extra opts for container
19 * envOpts - (optional) Array of variables that should be passed as ENV vars to Docker container.
20 * Return true | false
21 */
22
23def setupDockerAndTest(LinkedHashMap config) {
24 def common = new com.mirantis.mk.Common()
25 def TestMarkerResult = false
26 // setup options
27 def defaultContainerName = 'test-' + UUID.randomUUID().toString()
28 def dockerHostname = config.get('dockerHostname', defaultContainerName)
azvyagintsevabcf42e2018-10-05 20:40:27 +030029 def distribRevision = config.get('distribRevision', 'proposed')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +040030 def runCommands = config.get('runCommands', [:])
31 def runFinally = config.get('runFinally', [:])
32 def baseRepoPreConfig = config.get('baseRepoPreConfig', true)
33 def dockerContainerName = config.get('dockerContainerName', defaultContainerName)
azvyagintseve716a452018-11-25 13:41:52 +020034 // def dockerImageName = config.get('image', "mirantis/salt:saltstack-ubuntu-xenial-salt-2017.7")
35 // FIXME /PROD-25244
Denis Egorenkoc2a88522019-05-17 16:44:44 +040036 def dockerImageName = config.get('image', "docker-prod-local.artifactory.mirantis.com/mirantis/salt:saltstack-ubuntu-xenial-salt-2017.7")
Denis Egorenko6fd79ac2018-09-12 13:28:21 +040037 def dockerMaxCpus = config.get('dockerMaxCpus', 4)
38 def dockerExtraOpts = config.get('dockerExtraOpts', [])
39 def envOpts = config.get('envOpts', [])
azvyagintsevabcf42e2018-10-05 20:40:27 +030040 envOpts.add("DISTRIB_REVISION=${distribRevision}")
Denis Egorenko6fd79ac2018-09-12 13:28:21 +040041 def dockerBaseOpts = [
42 '-u root:root',
43 "--hostname=${dockerHostname}",
44 '--ulimit nofile=4096:8192',
45 "--name=${dockerContainerName}",
46 "--cpus=${dockerMaxCpus}"
47 ]
Denis Egorenko649cf7d2018-10-18 16:36:33 +040048 def dockerOptsFinal = (dockerBaseOpts + dockerExtraOpts).join(' ')
Denis Egorenko5cea1412018-10-18 16:40:11 +040049 def extraReposConfig = null
50 if (baseRepoPreConfig) {
51 // extra repo on mirror.mirantis.net, which is not supported before 2018.11.0 release
52 def extraRepoSource = "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/extra/xenial xenial main"
Denis Egorenko7269cf32019-03-27 19:12:06 +040053 def releaseVersionQ4 = '2018.11.0'
54 def oldRelease = false
Denis Egorenko5cea1412018-10-18 16:40:11 +040055 try {
56 def releaseNaming = 'yyyy.MM.dd'
57 def repoDateUsed = new Date().parse(releaseNaming, distribRevision)
Denis Egorenko7269cf32019-03-27 19:12:06 +040058 def extraAvailableFrom = new Date().parse(releaseNaming, releaseVersionQ4)
Denis Egorenko5cea1412018-10-18 16:40:11 +040059 if (repoDateUsed < extraAvailableFrom) {
azvyagintsevb9afd232019-02-11 14:22:31 +020060 extraRepoSource = "deb http://apt.mcp.mirantis.net/xenial ${distribRevision} extra"
Denis Egorenko7269cf32019-03-27 19:12:06 +040061 oldRelease = true
Denis Egorenko5cea1412018-10-18 16:40:11 +040062 }
63 } catch (Exception e) {
64 common.warningMsg(e)
azvyagintsevb9afd232019-02-11 14:22:31 +020065 if (!(distribRevision in ['nightly', 'proposed', 'testing'])) {
azvyagintsev62c97742019-01-02 17:53:54 +020066 extraRepoSource = "deb [arch=amd64] http://apt.mcp.mirantis.net/xenial ${distribRevision} extra"
Denis Egorenko7269cf32019-03-27 19:12:06 +040067 oldRelease = true
Denis Egorenko5cea1412018-10-18 16:40:11 +040068 }
69 }
70
71 def defaultExtraReposYaml = """
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000072---
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000073aprConfD: |-
74 APT::Get::AllowUnauthenticated 'true';
75 APT::Get::Install-Suggests 'false';
76 APT::Get::Install-Recommends 'false';
77repo:
78 mcp_saltstack:
Denis Egorenko395aa212018-10-11 15:11:28 +040079 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/saltstack-2017.7/xenial xenial main"
Denis Egorenkoe02a1b22018-10-19 17:47:53 +040080 pin:
81 - package: "libsodium18"
82 pin: "release o=SaltStack"
83 priority: 50
84 - package: "*"
85 pin: "release o=SaltStack"
86 priority: "1100"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000087 mcp_extra:
Denis Egorenko3c752a52018-10-12 12:21:29 +040088 source: "${extraRepoSource}"
Denis Egorenko395aa212018-10-11 15:11:28 +040089 mcp_saltformulas:
azvyagintsev058c1f42018-12-14 18:32:33 +020090 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/salt-formulas/xenial xenial main"
91 repo_key: "http://mirror.mirantis.com/${distribRevision}/salt-formulas/xenial/archive-salt-formulas.key"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000092 ubuntu:
Denis Egorenko395aa212018-10-11 15:11:28 +040093 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial main restricted universe"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000094 ubuntu-upd:
Denis Egorenko395aa212018-10-11 15:11:28 +040095 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial-updates main restricted universe"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000096 ubuntu-sec:
Denis Egorenko395aa212018-10-11 15:11:28 +040097 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial-security main restricted universe"
98"""
Denis Egorenko5cea1412018-10-18 16:40:11 +040099 // override for now
100 def extraRepoMergeStrategy = config.get('extraRepoMergeStrategy', 'override')
101 def extraRepos = config.get('extraRepos', [:])
azvyagintsev561ec872019-05-15 16:07:26 +0300102 def updateSaltFormulas = config.get('updateSaltFormulas', true).toBoolean()
Denis Egorenko5cea1412018-10-18 16:40:11 +0400103 def defaultRepos = readYaml text: defaultExtraReposYaml
azvyagintsev561ec872019-05-15 16:07:26 +0300104 // Don't check for magic, if set explicitly
105 if (updateSaltFormulas) {
Denis Egorenko0686f1b2019-11-18 20:52:04 +0400106 def updateSaltFormulasRev = config.get('updateSaltFormulasRev', distribRevision)
azvyagintsev561ec872019-05-15 16:07:26 +0300107 if (!oldRelease && distribRevision != releaseVersionQ4) {
108 defaultRepos['repo']['mcp_saltformulas_update'] = [
Denis Egorenko0686f1b2019-11-18 20:52:04 +0400109 'source' : "deb [arch=amd64] http://mirror.mirantis.com/update/${updateSaltFormulasRev}/salt-formulas/xenial xenial main",
110 'repo_key': "http://mirror.mirantis.com/update/${updateSaltFormulasRev}/salt-formulas/xenial/archive-salt-formulas.key"
azvyagintsev561ec872019-05-15 16:07:26 +0300111 ]
112 }
Denis Egorenko7269cf32019-03-27 19:12:06 +0400113 }
Denis Egorenko5cea1412018-10-18 16:40:11 +0400114 if (extraRepoMergeStrategy == 'merge') {
115 extraReposConfig = common.mergeMaps(defaultRepos, extraRepos)
116 } else {
117 extraReposConfig = extraRepos ? extraRepos : defaultRepos
118 }
119 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400120 def img = docker.image(dockerImageName)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000121
Oleksii Zhurbaed8709c2019-07-18 10:50:04 -0500122 def pull_enabled = config.get('dockerPull', true)
123
124 if ( pull_enabled ) {
125 img.pull()
126 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400127
128 try {
129 img.inside(dockerOptsFinal) {
130 withEnv(envOpts) {
131 try {
azvyagintsev4a8ccfa2019-04-08 16:25:08 +0300132 sh('printenv |sort -u')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400133 // Currently, we don't have any other point to install
134 // runtime dependencies for tests.
135 if (baseRepoPreConfig) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000136 // Warning! POssible point of 'allow-downgrades' issue
137 // Probably, need to add such flag into apt.prefs
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400138 sh("""#!/bin/bash -xe
139 echo "Installing extra-deb dependencies inside docker:"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000140 echo > /etc/apt/sources.list
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400141 rm -vf /etc/apt/sources.list.d/* || true
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400142 rm -vf /etc/apt/preferences.d/* || true
Aleksey Zvyagintsevc5453342018-10-05 15:03:59 +0000143 """)
Denis Egorenko5cea1412018-10-18 16:40:11 +0400144 common.debianExtraRepos(extraReposConfig)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000145 sh('''#!/bin/bash -xe
146 apt-get update
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400147 apt-get install -y python-netaddr
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000148 ''')
149
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400150 }
151 runCommands.sort().each { command, body ->
152 common.warningMsg("Running command: ${command}")
153 // doCall is the closure implementation in groovy, allow to pass arguments to closure
154 body.call()
155 }
156 // If we didn't dropped for now - test has been passed.
157 TestMarkerResult = true
158 }
159 finally {
160 runFinally.sort().each { command, body ->
161 common.warningMsg("Running ${command} command.")
162 // doCall is the closure implementation in groovy, allow to pass arguments to closure
163 body.call()
164 }
165 }
166 }
167 }
168 }
169 catch (Exception er) {
170 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
171 }
172
173 try {
Hanna Arhipovae0bcfbc2019-11-15 19:54:09 +0200174 timeout(time: 30, unit: 'SECONDS') {
175 if (sh(script: "docker inspect ${dockerContainerName}", returnStatus: true) == 0) {
176 common.warningMsg("Verify that container is not running. Ignore further docker-daemon errors")
177 sh(script: "set -x; test \$(docker inspect -f '{{.State.Running}}' ${dockerContainerName} 2>/dev/null) = 'true' && docker kill ${dockerContainerName}", returnStdout: true)
178 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
179 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400180 }
181 }
182 catch (Exception er) {
Hanna Arhipovae0bcfbc2019-11-15 19:54:09 +0200183 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force! Message:\n" + er.toString())
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400184 }
185
186 if (TestMarkerResult) {
187 common.infoMsg("Test finished: SUCCESS")
188 } else {
189 common.warningMsg("Test finished: FAILURE")
190 }
191 return TestMarkerResult
192}
193
194/**
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000195 * Wrapper around setupDockerAndTest, to run checks against new Reclass version
196 * that current model is compatible with new Reclass.
197 *
198 * @param config - LinkedHashMap with configuration params:
199 * dockerHostname - (required) Hostname to use for Docker container.
200 * distribRevision - (optional) Revision of packages to use (default proposed).
201 * extraRepo - (optional) Extra repo to use to install new Reclass version. Has
202 * high priority on distribRevision
203 * targetNodes - (required) List nodes to check pillar data.
Denis Egorenkob090a762018-09-12 19:25:41 +0400204 */
205def compareReclassVersions(config) {
206 def common = new com.mirantis.mk.Common()
207 def salt = new com.mirantis.mk.Salt()
208 common.infoMsg("Going to test new reclass for CFG node")
209 def distribRevision = config.get('distribRevision', 'proposed')
210 def venv = config.get('venv')
211 def extraRepo = config.get('extraRepo', '')
212 def extraRepoKey = config.get('extraRepoKey', '')
213 def targetNodes = config.get('targetNodes')
214 sh "rm -rf ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
215 sh "mkdir -p ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
216 def configRun = [
azvyagintsevabcf42e2018-10-05 20:40:27 +0300217 'distribRevision': distribRevision,
azvyagintsevb9afd232019-02-11 14:22:31 +0200218 'dockerExtraOpts': [
Denis Egorenkob090a762018-09-12 19:25:41 +0400219 "-v /srv/salt/reclass:/srv/salt/reclass:ro",
220 "-v /etc/salt:/etc/salt:ro",
221 "-v /usr/share/salt-formulas/:/usr/share/salt-formulas/:ro"
222 ],
azvyagintsevb9afd232019-02-11 14:22:31 +0200223 'envOpts' : [
Denis Egorenkob090a762018-09-12 19:25:41 +0400224 "WORKSPACE=${env.WORKSPACE}",
225 "NODES_LIST=${targetNodes.join(' ')}"
226 ],
azvyagintsevb9afd232019-02-11 14:22:31 +0200227 'runCommands' : [
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000228 '001_Update_Reclass_package' : {
229 sh('apt-get update && apt-get install -y reclass')
Denis Egorenkob090a762018-09-12 19:25:41 +0400230 },
231 '002_Test_Reclass_Compatibility': {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000232 sh('''
Denis Egorenkob090a762018-09-12 19:25:41 +0400233 reclass-salt -b /srv/salt/reclass -t > ${WORKSPACE}/new/inventory || exit 1
234 for node in $NODES_LIST; do
235 reclass-salt -b /srv/salt/reclass -p $node > ${WORKSPACE}/new/$node || exit 1
236 done
237 ''')
238 }
239 ]
240 ]
241 if (extraRepo) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000242 // FIXME
Denis Egorenkob090a762018-09-12 19:25:41 +0400243 configRun['runCommands']['0001_Additional_Extra_Repo_Passed'] = {
244 sh("""
245 echo "${extraRepo}" > /etc/apt/sources.list.d/mcp_extra.list
246 [ "${extraRepoKey}" ] && wget -O - ${extraRepoKey} | apt-key add -
247 """)
248 }
Denis Egorenkob090a762018-09-12 19:25:41 +0400249 }
250 if (setupDockerAndTest(configRun)) {
251 common.infoMsg("New reclass version is compatible with current model: SUCCESS")
252 def inventoryOld = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -t", true, null, true).get("return")[0].values()[0]
253 // [0..-31] to exclude 'echo Salt command execution success' from output
254 writeFile(file: "${env.WORKSPACE}/old/inventory", text: inventoryOld[0..-31])
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000255 for (String node in targetNodes) {
Denis Egorenkob090a762018-09-12 19:25:41 +0400256 def nodeOut = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -p ${node}", true, null, true).get("return")[0].values()[0]
257 writeFile(file: "${env.WORKSPACE}/old/${node}", text: nodeOut[0..-31])
258 }
259 def reclassDiff = common.comparePillars(env.WORKSPACE, env.BUILD_URL, '')
260 currentBuild.description = reclassDiff
261 if (reclassDiff != '<b>No job changes</b>') {
262 throw new RuntimeException("Pillars with new reclass version has been changed: FAILED")
263 } else {
264 common.infoMsg("Pillars not changed with new reclass version: SUCCESS")
265 }
266 } else {
267 throw new RuntimeException("New reclass version is not compatible with current model: FAILED")
268 }
269}
270
271/**
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400272 * Wrapper over setupDockerAndTest, to test CC model.
273 *
274 * @param config - dict with params:
275 * dockerHostname - (required) salt master's name
276 * clusterName - (optional) model cluster name
277 * extraFormulas - (optional) extraFormulas to install. DEPRECATED
278 * formulasSource - (optional) formulas source (git or pkg, default pkg)
279 * reclassVersion - (optional) Version of used reclass (branch, tag, ...) (optional, default master)
280 * reclassEnv - (require) directory of model
281 * ignoreClassNotfound - (optional) Ignore missing classes for reclass model (default false)
282 * aptRepoUrl - (optional) package repository with salt formulas
283 * aptRepoGPG - (optional) GPG key for apt repository with formulas
284 * testContext - (optional) Description of test
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000285 Return: true\exception
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400286 */
287
288def testNode(LinkedHashMap config) {
289 def common = new com.mirantis.mk.Common()
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400290 def dockerHostname = config.get('dockerHostname')
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400291 def domain = config.get('domain')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400292 def reclassEnv = config.get('reclassEnv')
293 def clusterName = config.get('clusterName', "")
294 def formulasSource = config.get('formulasSource', 'pkg')
295 def extraFormulas = config.get('extraFormulas', 'linux')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400296 def ignoreClassNotfound = config.get('ignoreClassNotfound', false)
297 def aptRepoUrl = config.get('aptRepoUrl', "")
298 def aptRepoGPG = config.get('aptRepoGPG', "")
299 def testContext = config.get('testContext', 'test')
Denis Egorenko66876fc2019-03-07 15:57:56 +0400300 def nodegenerator = config.get('nodegenerator', false)
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400301 config['envOpts'] = [
302 "RECLASS_ENV=${reclassEnv}", "SALT_STOPSTART_WAIT=5",
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400303 "HOSTNAME=${dockerHostname}", "CLUSTER_NAME=${clusterName}",
304 "DOMAIN=${domain}", "FORMULAS_SOURCE=${formulasSource}",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400305 "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400306 "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}", "DEBUG=1",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400307 "APT_REPOSITORY=${aptRepoUrl}", "APT_REPOSITORY_GPG=${aptRepoGPG}"
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400308 ]
309
310 config['runCommands'] = [
311 '001_Clone_salt_formulas_scripts': {
azvyagintsev62c97742019-01-02 17:53:54 +0200312 sh(script: 'git clone http://gerrit.mcp.mirantis.com/salt-formulas/salt-formulas-scripts /srv/salt/scripts', returnStdout: true)
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400313 },
314
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000315 '002_Prepare_something' : {
azvyagintsevb9afd232019-02-11 14:22:31 +0200316 sh('''#!/bin/bash -x
317 rsync -ah ${RECLASS_ENV}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400318 echo "127.0.0.1 ${HOSTNAME}.${DOMAIN}" >> /etc/hosts
azvyagintsevb9afd232019-02-11 14:22:31 +0200319 if [ -f '/srv/salt/reclass/salt_master_pillar.asc' ] ; then
320 mkdir -p /etc/salt/gpgkeys
321 chmod 700 /etc/salt/gpgkeys
322 GNUPGHOME=/etc/salt/gpgkeys gpg --import /srv/salt/reclass/salt_master_pillar.asc
323 fi
Alexander Evseev4983dec2018-10-25 15:49:39 +0200324 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
325 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400326 ''')
327 },
328
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400329 '003_Install_Reclass_package' : {
330 sh('apt-get install -y reclass')
331 },
332
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000333 '004_Run_tests' : {
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400334 def testTimeout = 40 * 60
335 timeout(time: testTimeout, unit: 'SECONDS') {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000336 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400337 source /srv/salt/scripts/bootstrap.sh
338 cd /srv/salt/scripts
339 source_local_envs
340 configure_salt_master
341 configure_salt_minion
342 install_salt_formula_pkg
343 source /srv/salt/scripts/bootstrap.sh
344 cd /srv/salt/scripts
345 saltservice_restart''')
346
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000347 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400348 source /srv/salt/scripts/bootstrap.sh
349 cd /srv/salt/scripts
350 source_local_envs
351 saltmaster_init''')
352
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000353 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400354 source /srv/salt/scripts/bootstrap.sh
355 cd /srv/salt/scripts
356 verify_salt_minions''')
357 }
358 }
359 ]
360 config['runFinally'] = [
361 '001_Archive_artefacts': {
362 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
363 archiveArtifacts artifacts: "nodesinfo.tar.gz"
364 }
365 ]
Denis Egorenko66876fc2019-03-07 15:57:56 +0400366 // this tool should be tested in master branch only
367 // and not for all jobs, as pilot will be used cc-reclass-chunk
368 if (nodegenerator) {
369 config['runCommands']['005_Test_new_nodegenerator'] = {
370 try {
371 sh('''#!/bin/bash
372 new_generated_dir=/srv/salt/_new_generated
373 mkdir -p ${new_generated_dir}
374 nodegenerator -b /srv/salt/reclass/classes/ -o ${new_generated_dir} ${CLUSTER_NAME}
375 diff -r /srv/salt/reclass/nodes/_generated ${new_generated_dir} > /tmp/nodegenerator.diff
376 tar -czf /tmp/_generated.tar.gz /srv/salt/reclass/nodes/_generated/
377 tar -czf /tmp/_new_generated.tar.gz ${new_generated_dir}/
378 tar -czf /tmp/_model.tar.gz /srv/salt/reclass/classes/cluster/*
379 ''')
380 } catch (Exception e) {
381 print "Test new nodegenerator tool is failed: ${e}"
382 }
383 }
384 config['runFinally']['002_Archive_nodegenerator_artefact'] = {
385 sh(script: "cd /tmp; [ -f nodegenerator.diff ] && tar -czf ${env.WORKSPACE}/nodegenerator.tar.gz nodegenerator.diff _generated.tar.gz _new_generated.tar.gz _model.tar.gz", returnStatus: true)
386 if (fileExists('nodegenerator.tar.gz')) {
387 archiveArtifacts artifacts: "nodegenerator.tar.gz"
388 }
389 }
390 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400391 testResult = setupDockerAndTest(config)
392 if (testResult) {
393 common.infoMsg("Node test for context: ${testContext} model: ${reclassEnv} finished: SUCCESS")
394 } else {
395 throw new RuntimeException("Node test for context: ${testContext} model: ${reclassEnv} finished: FAILURE")
396 }
397 return testResult
398}
399
400/**
chnydaf14ea2a2017-05-26 15:07:47 +0200401 * setup and test salt-master
402 *
azvyagintsevb4e0c442018-09-12 17:00:04 +0300403 * @param masterName salt master's name
404 * @param clusterName model cluster name
405 * @param extraFormulas extraFormulas to install. DEPRECATED
406 * @param formulasSource formulas source (git or pkg)
407 * @param reclassVersion Version of used reclass (branch, tag, ...) (optional, default master)
408 * @param testDir directory of model
409 * @param formulasSource Salt formulas source type (optional, default pkg)
410 * @param formulasRevision APT revision for formulas (optional default stable)
Petr Michalec6414aa52017-08-17 14:32:52 +0200411 * @param ignoreClassNotfound Ignore missing classes for reclass model
azvyagintsevb4e0c442018-09-12 17:00:04 +0300412 * @param dockerMaxCpus max cpus passed to docker (default 0, disabled)
413 * @param legacyTestingMode do you want to enable legacy testing mode (iterating through the nodes directory definitions instead of reading cluster models)
414 * @param aptRepoUrl package repository with salt formulas
415 * @param aptRepoGPG GPG key for apt repository with formulas
azvyagintsev28fa9d92018-06-26 14:31:49 +0300416 * Return true | false
chnydaf14ea2a2017-05-26 15:07:47 +0200417 */
418
azvyagintsevb4e0c442018-09-12 17:00:04 +0300419def setupAndTestNode(masterName, clusterName, extraFormulas = '*', testDir, formulasSource = 'pkg',
Vasyl Saienko369ed902018-07-23 11:49:32 +0000420 formulasRevision = 'stable', reclassVersion = "master", dockerMaxCpus = 0,
azvyagintsev28fa9d92018-06-26 14:31:49 +0300421 ignoreClassNotfound = false, legacyTestingMode = false, aptRepoUrl = '', aptRepoGPG = '', dockerContainerName = false) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300422 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300423 // TODO
424 common.errorMsg('You are using deprecated function!Please migrate to "setupDockerAndTest".' +
425 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
426 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300427 // timeout for test execution (40min)
428 def testTimeout = 40 * 60
429 def TestMarkerResult = false
430 def saltOpts = "--retcode-passthrough --force-color"
431 def workspace = common.getWorkspace()
432 def img = docker.image("mirantis/salt:saltstack-ubuntu-xenial-salt-2017.7")
433 img.pull()
chnydaf14ea2a2017-05-26 15:07:47 +0200434
azvyagintsev635affb2018-09-13 13:02:54 +0300435 if (formulasSource == 'pkg') {
436 if (extraFormulas) {
437 common.warningMsg("You have passed deprecated variable:extraFormulas=${extraFormulas}. " +
438 "\n It would be ignored, and all formulas would be installed anyway")
439 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300440 }
441 if (!dockerContainerName) {
442 dockerContainerName = 'setupAndTestNode' + UUID.randomUUID().toString()
443 }
444 def dockerMaxCpusOpt = "--cpus=4"
445 if (dockerMaxCpus > 0) {
446 dockerMaxCpusOpt = "--cpus=${dockerMaxCpus}"
447 }
448 try {
449 img.inside("-u root:root --hostname=${masterName} --ulimit nofile=4096:8192 ${dockerMaxCpusOpt} --name=${dockerContainerName}") {
azvyagintsev635affb2018-09-13 13:02:54 +0300450 withEnv(["FORMULAS_SOURCE=${formulasSource}", "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
azvyagintsevb4e0c442018-09-12 17:00:04 +0300451 "DISTRIB_REVISION=${formulasRevision}",
452 "DEBUG=1", "MASTER_HOSTNAME=${masterName}",
453 "CLUSTER_NAME=${clusterName}", "MINION_ID=${masterName}",
454 "RECLASS_VERSION=${reclassVersion}", "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}",
455 "APT_REPOSITORY=${aptRepoUrl}", "SALT_STOPSTART_WAIT=5",
456 "APT_REPOSITORY_GPG=${aptRepoGPG}"]) {
457 try {
458 // Currently, we don't have any other point to install
459 // runtime dependencies for tests.
460 sh("""#!/bin/bash -xe
azvyagintsev1bfe6842018-08-09 18:40:17 +0200461 echo "Installing extra-deb dependencies inside docker:"
462 echo "APT::Get::AllowUnauthenticated 'true';" > /etc/apt/apt.conf.d/99setupAndTestNode
463 echo "APT::Get::Install-Suggests 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
464 echo "APT::Get::Install-Recommends 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
465 rm -vf /etc/apt/sources.list.d/* || true
466 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial main restricted universe' > /etc/apt/sources.list
467 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial-updates main restricted universe' >> /etc/apt/sources.list
468 apt-get update
469 apt-get install -y python-netaddr
470 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300471 sh(script: "git clone https://github.com/salt-formulas/salt-formulas-scripts /srv/salt/scripts", returnStdout: true)
472 sh("""rsync -ah ${testDir}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Alexander Evseev4983dec2018-10-25 15:49:39 +0200473 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
474 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
azvyagintsev1bfe6842018-08-09 18:40:17 +0200475 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300476 // FIXME: should be changed to use reclass from mcp_extra_nigtly?
477 sh("""for s in \$(python -c \"import site; print(' '.join(site.getsitepackages()))\"); do
azvyagintsev1bfe6842018-08-09 18:40:17 +0200478 sudo -H pip install --install-option=\"--prefix=\" --upgrade --force-reinstall -I \
479 -t \"\$s\" git+https://github.com/salt-formulas/reclass.git@${reclassVersion};
480 done""")
azvyagintsevb4e0c442018-09-12 17:00:04 +0300481 timeout(time: testTimeout, unit: 'SECONDS') {
482 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200483 source /srv/salt/scripts/bootstrap.sh
484 cd /srv/salt/scripts
485 source_local_envs
486 configure_salt_master
487 configure_salt_minion
488 install_salt_formula_pkg
489 source /srv/salt/scripts/bootstrap.sh
490 cd /srv/salt/scripts
491 saltservice_restart''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300492 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200493 source /srv/salt/scripts/bootstrap.sh
494 cd /srv/salt/scripts
495 source_local_envs
496 saltmaster_init''')
497
azvyagintsevb4e0c442018-09-12 17:00:04 +0300498 if (!legacyTestingMode.toBoolean()) {
499 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200500 source /srv/salt/scripts/bootstrap.sh
501 cd /srv/salt/scripts
502 verify_salt_minions
503 ''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300504 }
505 }
506 // If we didn't dropped for now - test has been passed.
507 TestMarkerResult = true
508 }
509
510 finally {
511 // Collect rendered per-node data.Those info could be simply used
512 // for diff processing. Data was generated via reclass.cli --nodeinfo,
513 /// during verify_salt_minions.
514 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
515 archiveArtifacts artifacts: "nodesinfo.tar.gz"
516 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200517 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200518 }
chnydaf14ea2a2017-05-26 15:07:47 +0200519 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300520 catch (Exception er) {
521 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
522 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300523
azvyagintsevb4e0c442018-09-12 17:00:04 +0300524 if (legacyTestingMode.toBoolean()) {
525 common.infoMsg("Running legacy mode test for master hostname ${masterName}")
526 def nodes = sh(script: "find /srv/salt/reclass/nodes -name '*.yml' | grep -v 'cfg*.yml'", returnStdout: true)
527 for (minion in nodes.tokenize()) {
528 def basename = sh(script: "set +x;basename ${minion} .yml", returnStdout: true)
529 if (!basename.trim().contains(masterName)) {
530 testMinion(basename.trim())
531 }
532 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300533 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300534
azvyagintsevb4e0c442018-09-12 17:00:04 +0300535 try {
536 common.warningMsg("IgnoreMe:Force cleanup slave.Ignore docker-daemon errors")
537 timeout(time: 10, unit: 'SECONDS') {
538 sh(script: "set -x; docker kill ${dockerContainerName} || true", returnStdout: true)
539 }
540 timeout(time: 10, unit: 'SECONDS') {
541 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
542 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300543 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300544 catch (Exception er) {
545 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force!Message:\n" + er.toString())
azvyagintsev28fa9d92018-06-26 14:31:49 +0300546 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300547
azvyagintsevb4e0c442018-09-12 17:00:04 +0300548 if (TestMarkerResult) {
549 common.infoMsg("Test finished: SUCCESS")
550 } else {
551 common.warningMsg("Test finished: FAILURE")
552 }
553 return TestMarkerResult
azvyagintsev28fa9d92018-06-26 14:31:49 +0300554
chnydaf14ea2a2017-05-26 15:07:47 +0200555}
556
557/**
558 * Test salt-minion
559 *
azvyagintsev28fa9d92018-06-26 14:31:49 +0300560 * @param minion salt minion
chnydaf14ea2a2017-05-26 15:07:47 +0200561 */
562
azvyagintsev28fa9d92018-06-26 14:31:49 +0300563def testMinion(minionName) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300564 sh(script: "bash -c 'source /srv/salt/scripts/bootstrap.sh; cd /srv/salt/scripts && verify_salt_minion ${minionName}'", returnStdout: true)
Jakub Joseffa6ad8d2017-06-26 18:29:55 +0200565}
azvyagintsev2b279d82018-08-07 17:22:54 +0200566
azvyagintsev2b279d82018-08-07 17:22:54 +0200567/**
568 * Wrapper over setupAndTestNode, to test exactly one CC model.
azvyagintsevb4e0c442018-09-12 17:00:04 +0300569 Whole workspace and model - should be pre-rendered and passed via MODELS_TARGZ
570 Flow: grab all data, and pass to setupAndTestNode function
571 under-modell will be directly mirrored to `model/{cfg.testReclassEnv}/* /srv/salt/reclass/*`
azvyagintsev2b279d82018-08-07 17:22:54 +0200572 *
573 * @param cfg - dict with params:
azvyagintsevb4e0c442018-09-12 17:00:04 +0300574 MODELS_TARGZ http link to arch with (models|contexts|global_reclass)
575 modelFile
576 DockerCName directly passed to setupAndTestNode
577 EXTRA_FORMULAS directly passed to setupAndTestNode
578 DISTRIB_REVISION directly passed to setupAndTestNode
579 reclassVersion directly passed to setupAndTestNode
azvyagintsev2b279d82018-08-07 17:22:54 +0200580
azvyagintsevb4e0c442018-09-12 17:00:04 +0300581 Return: true\exception
azvyagintsev2b279d82018-08-07 17:22:54 +0200582 */
583
584def testCCModel(cfg) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300585 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300586 common.errorMsg('You are using deprecated function!Please migrate to "testNode".' +
587 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
588 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300589 sh(script: 'find . -mindepth 1 -delete || true', returnStatus: true)
590 sh(script: "wget --progress=dot:mega --auth-no-challenge -O models.tar.gz ${cfg.MODELS_TARGZ}")
591 // unpack data
592 sh(script: "tar -xzf models.tar.gz ")
593 common.infoMsg("Going to test exactly one context: ${cfg.modelFile}\n, with params: ${cfg}")
594 content = readFile(file: cfg.modelFile)
595 templateContext = readYaml text: content
596 clusterName = templateContext.default_context.cluster_name
597 clusterDomain = templateContext.default_context.cluster_domain
azvyagintsev2b279d82018-08-07 17:22:54 +0200598
azvyagintsevb4e0c442018-09-12 17:00:04 +0300599 def testResult = false
600 testResult = setupAndTestNode(
601 "cfg01.${clusterDomain}",
602 clusterName,
603 '',
604 cfg.testReclassEnv, // Sync into image exactly one env
605 'pkg',
606 cfg.DISTRIB_REVISION,
607 cfg.reclassVersion,
608 0,
609 false,
610 false,
611 '',
612 '',
613 cfg.DockerCName)
614 if (testResult) {
615 common.infoMsg("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: SUCCESS")
616 } else {
617 throw new RuntimeException("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: FAILURE")
618 }
619 return testResult
azvyagintsev2b279d82018-08-07 17:22:54 +0200620}