blob: 893f10f9cc8288381111288ca56a26f9614a2865 [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
36 def dockerImageName = config.get('image', "docker-dev-virtual.docker.mirantis.net/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"
53 try {
54 def releaseNaming = 'yyyy.MM.dd'
55 def repoDateUsed = new Date().parse(releaseNaming, distribRevision)
56 def extraAvailableFrom = new Date().parse(releaseNaming, '2018.11.0')
57 if (repoDateUsed < extraAvailableFrom) {
Alexander Evseev4983dec2018-10-25 15:49:39 +020058 extraRepoSource = "deb http://apt.mcp.mirantis.net/xenial ${distribRevision} extra"
Denis Egorenko5cea1412018-10-18 16:40:11 +040059 }
60 } catch (Exception e) {
61 common.warningMsg(e)
62 if ( !(distribRevision in [ 'nightly', 'proposed', 'testing' ] )) {
Alexander Evseev4983dec2018-10-25 15:49:39 +020063 extraRepoSource = "deb http://apt.mcp.mirantis.net/xenial ${distribRevision} extra"
Denis Egorenko5cea1412018-10-18 16:40:11 +040064 }
65 }
66
67 def defaultExtraReposYaml = """
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000068---
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000069aprConfD: |-
70 APT::Get::AllowUnauthenticated 'true';
71 APT::Get::Install-Suggests 'false';
72 APT::Get::Install-Recommends 'false';
73repo:
74 mcp_saltstack:
Denis Egorenko395aa212018-10-11 15:11:28 +040075 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/saltstack-2017.7/xenial xenial main"
Denis Egorenkoe02a1b22018-10-19 17:47:53 +040076 pin:
77 - package: "libsodium18"
78 pin: "release o=SaltStack"
79 priority: 50
80 - package: "*"
81 pin: "release o=SaltStack"
82 priority: "1100"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000083 mcp_extra:
Denis Egorenko3c752a52018-10-12 12:21:29 +040084 source: "${extraRepoSource}"
Denis Egorenko395aa212018-10-11 15:11:28 +040085 mcp_saltformulas:
azvyagintsev058c1f42018-12-14 18:32:33 +020086 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/salt-formulas/xenial xenial main"
87 repo_key: "http://mirror.mirantis.com/${distribRevision}/salt-formulas/xenial/archive-salt-formulas.key"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000088 ubuntu:
Denis Egorenko395aa212018-10-11 15:11:28 +040089 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial main restricted universe"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000090 ubuntu-upd:
Denis Egorenko395aa212018-10-11 15:11:28 +040091 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial-updates main restricted universe"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +000092 ubuntu-sec:
Denis Egorenko395aa212018-10-11 15:11:28 +040093 source: "deb [arch=amd64] http://mirror.mirantis.com/${distribRevision}/ubuntu xenial-security main restricted universe"
94"""
Denis Egorenko5cea1412018-10-18 16:40:11 +040095 // override for now
96 def extraRepoMergeStrategy = config.get('extraRepoMergeStrategy', 'override')
97 def extraRepos = config.get('extraRepos', [:])
98 def defaultRepos = readYaml text: defaultExtraReposYaml
99 if (extraRepoMergeStrategy == 'merge') {
100 extraReposConfig = common.mergeMaps(defaultRepos, extraRepos)
101 } else {
102 extraReposConfig = extraRepos ? extraRepos : defaultRepos
103 }
104 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400105 def img = docker.image(dockerImageName)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000106
Oleksii Zhurba0c4dc2c2019-07-18 10:50:04 -0500107 def pull_enabled = config.get('dockerPull', true)
108
109 if ( pull_enabled ) {
110 img.pull()
111 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400112
113 try {
114 img.inside(dockerOptsFinal) {
115 withEnv(envOpts) {
116 try {
117 // Currently, we don't have any other point to install
118 // runtime dependencies for tests.
119 if (baseRepoPreConfig) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000120 // Warning! POssible point of 'allow-downgrades' issue
121 // Probably, need to add such flag into apt.prefs
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400122 sh("""#!/bin/bash -xe
123 echo "Installing extra-deb dependencies inside docker:"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000124 echo > /etc/apt/sources.list
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400125 rm -vf /etc/apt/sources.list.d/* || true
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400126 rm -vf /etc/apt/preferences.d/* || true
Aleksey Zvyagintsevc5453342018-10-05 15:03:59 +0000127 """)
Denis Egorenko5cea1412018-10-18 16:40:11 +0400128 common.debianExtraRepos(extraReposConfig)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000129 sh('''#!/bin/bash -xe
130 apt-get update
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400131 apt-get install -y python-netaddr
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000132 ''')
133
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400134 }
135 runCommands.sort().each { command, body ->
136 common.warningMsg("Running command: ${command}")
137 // doCall is the closure implementation in groovy, allow to pass arguments to closure
138 body.call()
139 }
140 // If we didn't dropped for now - test has been passed.
141 TestMarkerResult = true
142 }
143 finally {
144 runFinally.sort().each { command, body ->
145 common.warningMsg("Running ${command} command.")
146 // doCall is the closure implementation in groovy, allow to pass arguments to closure
147 body.call()
148 }
149 }
150 }
151 }
152 }
153 catch (Exception er) {
154 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
155 }
156
157 try {
Hanna Arhipovaa9132d02019-11-15 19:54:09 +0200158 timeout(time: 30, unit: 'SECONDS') {
159 if (sh(script: "docker inspect ${dockerContainerName}", returnStatus: true) == 0) {
160 common.warningMsg("Verify that container is not running. Ignore further docker-daemon errors")
161 sh(script: "set -x; test \$(docker inspect -f '{{.State.Running}}' ${dockerContainerName} 2>/dev/null) = 'true' && docker kill ${dockerContainerName}", returnStdout: true)
162 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
163 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400164 }
165 }
166 catch (Exception er) {
Hanna Arhipovaa9132d02019-11-15 19:54:09 +0200167 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force! Message:\n" + er.toString())
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400168 }
169
170 if (TestMarkerResult) {
171 common.infoMsg("Test finished: SUCCESS")
172 } else {
173 common.warningMsg("Test finished: FAILURE")
174 }
175 return TestMarkerResult
176}
177
178/**
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000179 * Wrapper around setupDockerAndTest, to run checks against new Reclass version
180 * that current model is compatible with new Reclass.
181 *
182 * @param config - LinkedHashMap with configuration params:
183 * dockerHostname - (required) Hostname to use for Docker container.
184 * distribRevision - (optional) Revision of packages to use (default proposed).
185 * extraRepo - (optional) Extra repo to use to install new Reclass version. Has
186 * high priority on distribRevision
187 * targetNodes - (required) List nodes to check pillar data.
Denis Egorenkob090a762018-09-12 19:25:41 +0400188 */
189def compareReclassVersions(config) {
190 def common = new com.mirantis.mk.Common()
191 def salt = new com.mirantis.mk.Salt()
192 common.infoMsg("Going to test new reclass for CFG node")
193 def distribRevision = config.get('distribRevision', 'proposed')
194 def venv = config.get('venv')
195 def extraRepo = config.get('extraRepo', '')
196 def extraRepoKey = config.get('extraRepoKey', '')
197 def targetNodes = config.get('targetNodes')
198 sh "rm -rf ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
199 sh "mkdir -p ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
200 def configRun = [
azvyagintsevabcf42e2018-10-05 20:40:27 +0300201 'distribRevision': distribRevision,
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000202 'dockerExtraOpts' : [
Denis Egorenkob090a762018-09-12 19:25:41 +0400203 "-v /srv/salt/reclass:/srv/salt/reclass:ro",
204 "-v /etc/salt:/etc/salt:ro",
205 "-v /usr/share/salt-formulas/:/usr/share/salt-formulas/:ro"
206 ],
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000207 'envOpts' : [
Denis Egorenkob090a762018-09-12 19:25:41 +0400208 "WORKSPACE=${env.WORKSPACE}",
209 "NODES_LIST=${targetNodes.join(' ')}"
210 ],
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000211 'runCommands' : [
212 '001_Update_Reclass_package' : {
213 sh('apt-get update && apt-get install -y reclass')
Denis Egorenkob090a762018-09-12 19:25:41 +0400214 },
215 '002_Test_Reclass_Compatibility': {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000216 sh('''
Denis Egorenkob090a762018-09-12 19:25:41 +0400217 reclass-salt -b /srv/salt/reclass -t > ${WORKSPACE}/new/inventory || exit 1
218 for node in $NODES_LIST; do
219 reclass-salt -b /srv/salt/reclass -p $node > ${WORKSPACE}/new/$node || exit 1
220 done
221 ''')
222 }
223 ]
224 ]
225 if (extraRepo) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000226 // FIXME
Denis Egorenkob090a762018-09-12 19:25:41 +0400227 configRun['runCommands']['0001_Additional_Extra_Repo_Passed'] = {
228 sh("""
229 echo "${extraRepo}" > /etc/apt/sources.list.d/mcp_extra.list
230 [ "${extraRepoKey}" ] && wget -O - ${extraRepoKey} | apt-key add -
231 """)
232 }
Denis Egorenkob090a762018-09-12 19:25:41 +0400233 }
234 if (setupDockerAndTest(configRun)) {
235 common.infoMsg("New reclass version is compatible with current model: SUCCESS")
236 def inventoryOld = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -t", true, null, true).get("return")[0].values()[0]
237 // [0..-31] to exclude 'echo Salt command execution success' from output
238 writeFile(file: "${env.WORKSPACE}/old/inventory", text: inventoryOld[0..-31])
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000239 for (String node in targetNodes) {
Denis Egorenkob090a762018-09-12 19:25:41 +0400240 def nodeOut = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -p ${node}", true, null, true).get("return")[0].values()[0]
241 writeFile(file: "${env.WORKSPACE}/old/${node}", text: nodeOut[0..-31])
242 }
243 def reclassDiff = common.comparePillars(env.WORKSPACE, env.BUILD_URL, '')
244 currentBuild.description = reclassDiff
245 if (reclassDiff != '<b>No job changes</b>') {
246 throw new RuntimeException("Pillars with new reclass version has been changed: FAILED")
247 } else {
248 common.infoMsg("Pillars not changed with new reclass version: SUCCESS")
249 }
250 } else {
251 throw new RuntimeException("New reclass version is not compatible with current model: FAILED")
252 }
253}
254
255/**
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400256 * Wrapper over setupDockerAndTest, to test CC model.
257 *
258 * @param config - dict with params:
259 * dockerHostname - (required) salt master's name
260 * clusterName - (optional) model cluster name
261 * extraFormulas - (optional) extraFormulas to install. DEPRECATED
262 * formulasSource - (optional) formulas source (git or pkg, default pkg)
263 * reclassVersion - (optional) Version of used reclass (branch, tag, ...) (optional, default master)
264 * reclassEnv - (require) directory of model
265 * ignoreClassNotfound - (optional) Ignore missing classes for reclass model (default false)
266 * aptRepoUrl - (optional) package repository with salt formulas
267 * aptRepoGPG - (optional) GPG key for apt repository with formulas
268 * testContext - (optional) Description of test
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000269 Return: true\exception
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400270 */
271
272def testNode(LinkedHashMap config) {
273 def common = new com.mirantis.mk.Common()
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400274 def dockerHostname = config.get('dockerHostname')
275 def reclassEnv = config.get('reclassEnv')
276 def clusterName = config.get('clusterName', "")
277 def formulasSource = config.get('formulasSource', 'pkg')
278 def extraFormulas = config.get('extraFormulas', 'linux')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400279 def ignoreClassNotfound = config.get('ignoreClassNotfound', false)
280 def aptRepoUrl = config.get('aptRepoUrl', "")
281 def aptRepoGPG = config.get('aptRepoGPG', "")
282 def testContext = config.get('testContext', 'test')
283 config['envOpts'] = [
284 "RECLASS_ENV=${reclassEnv}", "SALT_STOPSTART_WAIT=5",
285 "MASTER_HOSTNAME=${dockerHostname}", "CLUSTER_NAME=${clusterName}",
286 "MINION_ID=${dockerHostname}", "FORMULAS_SOURCE=${formulasSource}",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400287 "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400288 "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}", "DEBUG=1",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400289 "APT_REPOSITORY=${aptRepoUrl}", "APT_REPOSITORY_GPG=${aptRepoGPG}"
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400290 ]
291
292 config['runCommands'] = [
293 '001_Clone_salt_formulas_scripts': {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000294 sh(script: 'git clone https://github.com/salt-formulas/salt-formulas-scripts /srv/salt/scripts', returnStdout: true)
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400295 },
296
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000297 '002_Prepare_something' : {
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400298 sh('''rsync -ah ${RECLASS_ENV}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Alexander Evseev4983dec2018-10-25 15:49:39 +0200299 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
300 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 +0400301 ''')
302 },
303
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400304 '003_Install_Reclass_package' : {
305 sh('apt-get install -y reclass')
306 },
307
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000308 '004_Run_tests' : {
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400309 def testTimeout = 40 * 60
310 timeout(time: testTimeout, unit: 'SECONDS') {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000311 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400312 source /srv/salt/scripts/bootstrap.sh
313 cd /srv/salt/scripts
314 source_local_envs
315 configure_salt_master
316 configure_salt_minion
317 install_salt_formula_pkg
318 source /srv/salt/scripts/bootstrap.sh
319 cd /srv/salt/scripts
320 saltservice_restart''')
321
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000322 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400323 source /srv/salt/scripts/bootstrap.sh
324 cd /srv/salt/scripts
325 source_local_envs
326 saltmaster_init''')
327
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000328 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400329 source /srv/salt/scripts/bootstrap.sh
330 cd /srv/salt/scripts
331 verify_salt_minions''')
332 }
333 }
334 ]
335 config['runFinally'] = [
336 '001_Archive_artefacts': {
337 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
338 archiveArtifacts artifacts: "nodesinfo.tar.gz"
339 }
340 ]
341 testResult = setupDockerAndTest(config)
342 if (testResult) {
343 common.infoMsg("Node test for context: ${testContext} model: ${reclassEnv} finished: SUCCESS")
344 } else {
345 throw new RuntimeException("Node test for context: ${testContext} model: ${reclassEnv} finished: FAILURE")
346 }
347 return testResult
348}
349
350/**
chnydaf14ea2a2017-05-26 15:07:47 +0200351 * setup and test salt-master
352 *
azvyagintsevb4e0c442018-09-12 17:00:04 +0300353 * @param masterName salt master's name
354 * @param clusterName model cluster name
355 * @param extraFormulas extraFormulas to install. DEPRECATED
356 * @param formulasSource formulas source (git or pkg)
357 * @param reclassVersion Version of used reclass (branch, tag, ...) (optional, default master)
358 * @param testDir directory of model
359 * @param formulasSource Salt formulas source type (optional, default pkg)
360 * @param formulasRevision APT revision for formulas (optional default stable)
Petr Michalec6414aa52017-08-17 14:32:52 +0200361 * @param ignoreClassNotfound Ignore missing classes for reclass model
azvyagintsevb4e0c442018-09-12 17:00:04 +0300362 * @param dockerMaxCpus max cpus passed to docker (default 0, disabled)
363 * @param legacyTestingMode do you want to enable legacy testing mode (iterating through the nodes directory definitions instead of reading cluster models)
364 * @param aptRepoUrl package repository with salt formulas
365 * @param aptRepoGPG GPG key for apt repository with formulas
azvyagintsev28fa9d92018-06-26 14:31:49 +0300366 * Return true | false
chnydaf14ea2a2017-05-26 15:07:47 +0200367 */
368
azvyagintsevb4e0c442018-09-12 17:00:04 +0300369def setupAndTestNode(masterName, clusterName, extraFormulas = '*', testDir, formulasSource = 'pkg',
Vasyl Saienko369ed902018-07-23 11:49:32 +0000370 formulasRevision = 'stable', reclassVersion = "master", dockerMaxCpus = 0,
azvyagintsev28fa9d92018-06-26 14:31:49 +0300371 ignoreClassNotfound = false, legacyTestingMode = false, aptRepoUrl = '', aptRepoGPG = '', dockerContainerName = false) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300372 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300373 // TODO
374 common.errorMsg('You are using deprecated function!Please migrate to "setupDockerAndTest".' +
375 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
376 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300377 // timeout for test execution (40min)
378 def testTimeout = 40 * 60
379 def TestMarkerResult = false
380 def saltOpts = "--retcode-passthrough --force-color"
381 def workspace = common.getWorkspace()
382 def img = docker.image("mirantis/salt:saltstack-ubuntu-xenial-salt-2017.7")
383 img.pull()
chnydaf14ea2a2017-05-26 15:07:47 +0200384
azvyagintsev635affb2018-09-13 13:02:54 +0300385 if (formulasSource == 'pkg') {
386 if (extraFormulas) {
387 common.warningMsg("You have passed deprecated variable:extraFormulas=${extraFormulas}. " +
388 "\n It would be ignored, and all formulas would be installed anyway")
389 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300390 }
391 if (!dockerContainerName) {
392 dockerContainerName = 'setupAndTestNode' + UUID.randomUUID().toString()
393 }
394 def dockerMaxCpusOpt = "--cpus=4"
395 if (dockerMaxCpus > 0) {
396 dockerMaxCpusOpt = "--cpus=${dockerMaxCpus}"
397 }
398 try {
399 img.inside("-u root:root --hostname=${masterName} --ulimit nofile=4096:8192 ${dockerMaxCpusOpt} --name=${dockerContainerName}") {
azvyagintsev635affb2018-09-13 13:02:54 +0300400 withEnv(["FORMULAS_SOURCE=${formulasSource}", "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
azvyagintsevb4e0c442018-09-12 17:00:04 +0300401 "DISTRIB_REVISION=${formulasRevision}",
402 "DEBUG=1", "MASTER_HOSTNAME=${masterName}",
403 "CLUSTER_NAME=${clusterName}", "MINION_ID=${masterName}",
404 "RECLASS_VERSION=${reclassVersion}", "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}",
405 "APT_REPOSITORY=${aptRepoUrl}", "SALT_STOPSTART_WAIT=5",
406 "APT_REPOSITORY_GPG=${aptRepoGPG}"]) {
407 try {
408 // Currently, we don't have any other point to install
409 // runtime dependencies for tests.
410 sh("""#!/bin/bash -xe
azvyagintsev1bfe6842018-08-09 18:40:17 +0200411 echo "Installing extra-deb dependencies inside docker:"
412 echo "APT::Get::AllowUnauthenticated 'true';" > /etc/apt/apt.conf.d/99setupAndTestNode
413 echo "APT::Get::Install-Suggests 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
414 echo "APT::Get::Install-Recommends 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
415 rm -vf /etc/apt/sources.list.d/* || true
416 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial main restricted universe' > /etc/apt/sources.list
417 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial-updates main restricted universe' >> /etc/apt/sources.list
418 apt-get update
419 apt-get install -y python-netaddr
420 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300421 sh(script: "git clone https://github.com/salt-formulas/salt-formulas-scripts /srv/salt/scripts", returnStdout: true)
422 sh("""rsync -ah ${testDir}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Alexander Evseev4983dec2018-10-25 15:49:39 +0200423 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
424 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 +0200425 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300426 // FIXME: should be changed to use reclass from mcp_extra_nigtly?
427 sh("""for s in \$(python -c \"import site; print(' '.join(site.getsitepackages()))\"); do
azvyagintsev1bfe6842018-08-09 18:40:17 +0200428 sudo -H pip install --install-option=\"--prefix=\" --upgrade --force-reinstall -I \
429 -t \"\$s\" git+https://github.com/salt-formulas/reclass.git@${reclassVersion};
430 done""")
azvyagintsevb4e0c442018-09-12 17:00:04 +0300431 timeout(time: testTimeout, unit: 'SECONDS') {
432 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200433 source /srv/salt/scripts/bootstrap.sh
434 cd /srv/salt/scripts
435 source_local_envs
436 configure_salt_master
437 configure_salt_minion
438 install_salt_formula_pkg
439 source /srv/salt/scripts/bootstrap.sh
440 cd /srv/salt/scripts
441 saltservice_restart''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300442 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200443 source /srv/salt/scripts/bootstrap.sh
444 cd /srv/salt/scripts
445 source_local_envs
446 saltmaster_init''')
447
azvyagintsevb4e0c442018-09-12 17:00:04 +0300448 if (!legacyTestingMode.toBoolean()) {
449 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200450 source /srv/salt/scripts/bootstrap.sh
451 cd /srv/salt/scripts
452 verify_salt_minions
453 ''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300454 }
455 }
456 // If we didn't dropped for now - test has been passed.
457 TestMarkerResult = true
458 }
459
460 finally {
461 // Collect rendered per-node data.Those info could be simply used
462 // for diff processing. Data was generated via reclass.cli --nodeinfo,
463 /// during verify_salt_minions.
464 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
465 archiveArtifacts artifacts: "nodesinfo.tar.gz"
466 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200467 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200468 }
chnydaf14ea2a2017-05-26 15:07:47 +0200469 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300470 catch (Exception er) {
471 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
472 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300473
azvyagintsevb4e0c442018-09-12 17:00:04 +0300474 if (legacyTestingMode.toBoolean()) {
475 common.infoMsg("Running legacy mode test for master hostname ${masterName}")
476 def nodes = sh(script: "find /srv/salt/reclass/nodes -name '*.yml' | grep -v 'cfg*.yml'", returnStdout: true)
477 for (minion in nodes.tokenize()) {
478 def basename = sh(script: "set +x;basename ${minion} .yml", returnStdout: true)
479 if (!basename.trim().contains(masterName)) {
480 testMinion(basename.trim())
481 }
482 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300483 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300484
azvyagintsevb4e0c442018-09-12 17:00:04 +0300485 try {
486 common.warningMsg("IgnoreMe:Force cleanup slave.Ignore docker-daemon errors")
487 timeout(time: 10, unit: 'SECONDS') {
488 sh(script: "set -x; docker kill ${dockerContainerName} || true", returnStdout: true)
489 }
490 timeout(time: 10, unit: 'SECONDS') {
491 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
492 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300493 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300494 catch (Exception er) {
495 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force!Message:\n" + er.toString())
azvyagintsev28fa9d92018-06-26 14:31:49 +0300496 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300497
azvyagintsevb4e0c442018-09-12 17:00:04 +0300498 if (TestMarkerResult) {
499 common.infoMsg("Test finished: SUCCESS")
500 } else {
501 common.warningMsg("Test finished: FAILURE")
502 }
503 return TestMarkerResult
azvyagintsev28fa9d92018-06-26 14:31:49 +0300504
chnydaf14ea2a2017-05-26 15:07:47 +0200505}
506
507/**
508 * Test salt-minion
509 *
azvyagintsev28fa9d92018-06-26 14:31:49 +0300510 * @param minion salt minion
chnydaf14ea2a2017-05-26 15:07:47 +0200511 */
512
azvyagintsev28fa9d92018-06-26 14:31:49 +0300513def testMinion(minionName) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300514 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 +0200515}
azvyagintsev2b279d82018-08-07 17:22:54 +0200516
azvyagintsev2b279d82018-08-07 17:22:54 +0200517/**
518 * Wrapper over setupAndTestNode, to test exactly one CC model.
azvyagintsevb4e0c442018-09-12 17:00:04 +0300519 Whole workspace and model - should be pre-rendered and passed via MODELS_TARGZ
520 Flow: grab all data, and pass to setupAndTestNode function
521 under-modell will be directly mirrored to `model/{cfg.testReclassEnv}/* /srv/salt/reclass/*`
azvyagintsev2b279d82018-08-07 17:22:54 +0200522 *
523 * @param cfg - dict with params:
azvyagintsevb4e0c442018-09-12 17:00:04 +0300524 MODELS_TARGZ http link to arch with (models|contexts|global_reclass)
525 modelFile
526 DockerCName directly passed to setupAndTestNode
527 EXTRA_FORMULAS directly passed to setupAndTestNode
528 DISTRIB_REVISION directly passed to setupAndTestNode
529 reclassVersion directly passed to setupAndTestNode
azvyagintsev2b279d82018-08-07 17:22:54 +0200530
azvyagintsevb4e0c442018-09-12 17:00:04 +0300531 Return: true\exception
azvyagintsev2b279d82018-08-07 17:22:54 +0200532 */
533
534def testCCModel(cfg) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300535 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300536 common.errorMsg('You are using deprecated function!Please migrate to "testNode".' +
537 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
538 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300539 sh(script: 'find . -mindepth 1 -delete || true', returnStatus: true)
540 sh(script: "wget --progress=dot:mega --auth-no-challenge -O models.tar.gz ${cfg.MODELS_TARGZ}")
541 // unpack data
542 sh(script: "tar -xzf models.tar.gz ")
543 common.infoMsg("Going to test exactly one context: ${cfg.modelFile}\n, with params: ${cfg}")
544 content = readFile(file: cfg.modelFile)
545 templateContext = readYaml text: content
546 clusterName = templateContext.default_context.cluster_name
547 clusterDomain = templateContext.default_context.cluster_domain
azvyagintsev2b279d82018-08-07 17:22:54 +0200548
azvyagintsevb4e0c442018-09-12 17:00:04 +0300549 def testResult = false
550 testResult = setupAndTestNode(
551 "cfg01.${clusterDomain}",
552 clusterName,
553 '',
554 cfg.testReclassEnv, // Sync into image exactly one env
555 'pkg',
556 cfg.DISTRIB_REVISION,
557 cfg.reclassVersion,
558 0,
559 false,
560 false,
561 '',
562 '',
563 cfg.DockerCName)
564 if (testResult) {
565 common.infoMsg("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: SUCCESS")
566 } else {
567 throw new RuntimeException("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: FAILURE")
568 }
569 return testResult
azvyagintsev2b279d82018-08-07 17:22:54 +0200570}