blob: 0e49a42701a3eecc5359f23499dda814683149ae [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"
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', [:])
102 def defaultRepos = readYaml text: defaultExtraReposYaml
Denis Egorenko7269cf32019-03-27 19:12:06 +0400103 if (! oldRelease && distribRevision != releaseVersionQ4) {
104 defaultRepos['repo']['mcp_saltformulas_update'] = [
105 'source': "deb [arch=amd64] http://mirror.mirantis.com/update/${distribRevision}/salt-formulas/xenial xenial main",
106 'repo_key': "http://mirror.mirantis.com/update/${distribRevision}/salt-formulas/xenial/archive-salt-formulas.key"
107 ]
108 }
Denis Egorenko5cea1412018-10-18 16:40:11 +0400109 if (extraRepoMergeStrategy == 'merge') {
110 extraReposConfig = common.mergeMaps(defaultRepos, extraRepos)
111 } else {
112 extraReposConfig = extraRepos ? extraRepos : defaultRepos
113 }
114 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400115 def img = docker.image(dockerImageName)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000116
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400117 img.pull()
118
119 try {
120 img.inside(dockerOptsFinal) {
121 withEnv(envOpts) {
122 try {
123 // Currently, we don't have any other point to install
124 // runtime dependencies for tests.
125 if (baseRepoPreConfig) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000126 // Warning! POssible point of 'allow-downgrades' issue
127 // Probably, need to add such flag into apt.prefs
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400128 sh("""#!/bin/bash -xe
129 echo "Installing extra-deb dependencies inside docker:"
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000130 echo > /etc/apt/sources.list
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400131 rm -vf /etc/apt/sources.list.d/* || true
Denis Egorenkoe02a1b22018-10-19 17:47:53 +0400132 rm -vf /etc/apt/preferences.d/* || true
Aleksey Zvyagintsevc5453342018-10-05 15:03:59 +0000133 """)
Denis Egorenko5cea1412018-10-18 16:40:11 +0400134 common.debianExtraRepos(extraReposConfig)
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000135 sh('''#!/bin/bash -xe
136 apt-get update
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400137 apt-get install -y python-netaddr
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000138 ''')
139
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400140 }
141 runCommands.sort().each { command, body ->
142 common.warningMsg("Running command: ${command}")
143 // doCall is the closure implementation in groovy, allow to pass arguments to closure
144 body.call()
145 }
146 // If we didn't dropped for now - test has been passed.
147 TestMarkerResult = true
148 }
149 finally {
150 runFinally.sort().each { command, body ->
151 common.warningMsg("Running ${command} command.")
152 // doCall is the closure implementation in groovy, allow to pass arguments to closure
153 body.call()
154 }
155 }
156 }
157 }
158 }
159 catch (Exception er) {
160 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
161 }
162
163 try {
164 common.warningMsg("IgnoreMe:Force cleanup slave.Ignore docker-daemon errors")
165 timeout(time: 10, unit: 'SECONDS') {
166 sh(script: "set -x; docker kill ${dockerContainerName} || true", returnStdout: true)
167 }
168 timeout(time: 10, unit: 'SECONDS') {
169 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
170 }
171 }
172 catch (Exception er) {
173 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force!Message:\n" + er.toString())
174 }
175
176 if (TestMarkerResult) {
177 common.infoMsg("Test finished: SUCCESS")
178 } else {
179 common.warningMsg("Test finished: FAILURE")
180 }
181 return TestMarkerResult
182}
183
184/**
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000185 * Wrapper around setupDockerAndTest, to run checks against new Reclass version
186 * that current model is compatible with new Reclass.
187 *
188 * @param config - LinkedHashMap with configuration params:
189 * dockerHostname - (required) Hostname to use for Docker container.
190 * distribRevision - (optional) Revision of packages to use (default proposed).
191 * extraRepo - (optional) Extra repo to use to install new Reclass version. Has
192 * high priority on distribRevision
193 * targetNodes - (required) List nodes to check pillar data.
Denis Egorenkob090a762018-09-12 19:25:41 +0400194 */
195def compareReclassVersions(config) {
196 def common = new com.mirantis.mk.Common()
197 def salt = new com.mirantis.mk.Salt()
198 common.infoMsg("Going to test new reclass for CFG node")
199 def distribRevision = config.get('distribRevision', 'proposed')
200 def venv = config.get('venv')
201 def extraRepo = config.get('extraRepo', '')
202 def extraRepoKey = config.get('extraRepoKey', '')
203 def targetNodes = config.get('targetNodes')
204 sh "rm -rf ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
205 sh "mkdir -p ${env.WORKSPACE}/old ${env.WORKSPACE}/new"
206 def configRun = [
azvyagintsevabcf42e2018-10-05 20:40:27 +0300207 'distribRevision': distribRevision,
azvyagintsevb9afd232019-02-11 14:22:31 +0200208 'dockerExtraOpts': [
Denis Egorenkob090a762018-09-12 19:25:41 +0400209 "-v /srv/salt/reclass:/srv/salt/reclass:ro",
210 "-v /etc/salt:/etc/salt:ro",
211 "-v /usr/share/salt-formulas/:/usr/share/salt-formulas/:ro"
212 ],
azvyagintsevb9afd232019-02-11 14:22:31 +0200213 'envOpts' : [
Denis Egorenkob090a762018-09-12 19:25:41 +0400214 "WORKSPACE=${env.WORKSPACE}",
215 "NODES_LIST=${targetNodes.join(' ')}"
216 ],
azvyagintsevb9afd232019-02-11 14:22:31 +0200217 'runCommands' : [
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000218 '001_Update_Reclass_package' : {
219 sh('apt-get update && apt-get install -y reclass')
Denis Egorenkob090a762018-09-12 19:25:41 +0400220 },
221 '002_Test_Reclass_Compatibility': {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000222 sh('''
Denis Egorenkob090a762018-09-12 19:25:41 +0400223 reclass-salt -b /srv/salt/reclass -t > ${WORKSPACE}/new/inventory || exit 1
224 for node in $NODES_LIST; do
225 reclass-salt -b /srv/salt/reclass -p $node > ${WORKSPACE}/new/$node || exit 1
226 done
227 ''')
228 }
229 ]
230 ]
231 if (extraRepo) {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000232 // FIXME
Denis Egorenkob090a762018-09-12 19:25:41 +0400233 configRun['runCommands']['0001_Additional_Extra_Repo_Passed'] = {
234 sh("""
235 echo "${extraRepo}" > /etc/apt/sources.list.d/mcp_extra.list
236 [ "${extraRepoKey}" ] && wget -O - ${extraRepoKey} | apt-key add -
237 """)
238 }
Denis Egorenkob090a762018-09-12 19:25:41 +0400239 }
240 if (setupDockerAndTest(configRun)) {
241 common.infoMsg("New reclass version is compatible with current model: SUCCESS")
242 def inventoryOld = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -t", true, null, true).get("return")[0].values()[0]
243 // [0..-31] to exclude 'echo Salt command execution success' from output
244 writeFile(file: "${env.WORKSPACE}/old/inventory", text: inventoryOld[0..-31])
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000245 for (String node in targetNodes) {
Denis Egorenkob090a762018-09-12 19:25:41 +0400246 def nodeOut = salt.cmdRun(venv, "I@salt:master", "reclass-salt -b /srv/salt/reclass -p ${node}", true, null, true).get("return")[0].values()[0]
247 writeFile(file: "${env.WORKSPACE}/old/${node}", text: nodeOut[0..-31])
248 }
249 def reclassDiff = common.comparePillars(env.WORKSPACE, env.BUILD_URL, '')
250 currentBuild.description = reclassDiff
251 if (reclassDiff != '<b>No job changes</b>') {
252 throw new RuntimeException("Pillars with new reclass version has been changed: FAILED")
253 } else {
254 common.infoMsg("Pillars not changed with new reclass version: SUCCESS")
255 }
256 } else {
257 throw new RuntimeException("New reclass version is not compatible with current model: FAILED")
258 }
259}
260
261/**
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400262 * Wrapper over setupDockerAndTest, to test CC model.
263 *
264 * @param config - dict with params:
265 * dockerHostname - (required) salt master's name
266 * clusterName - (optional) model cluster name
267 * extraFormulas - (optional) extraFormulas to install. DEPRECATED
268 * formulasSource - (optional) formulas source (git or pkg, default pkg)
269 * reclassVersion - (optional) Version of used reclass (branch, tag, ...) (optional, default master)
270 * reclassEnv - (require) directory of model
271 * ignoreClassNotfound - (optional) Ignore missing classes for reclass model (default false)
272 * aptRepoUrl - (optional) package repository with salt formulas
273 * aptRepoGPG - (optional) GPG key for apt repository with formulas
274 * testContext - (optional) Description of test
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000275 Return: true\exception
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400276 */
277
278def testNode(LinkedHashMap config) {
279 def common = new com.mirantis.mk.Common()
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400280 def dockerHostname = config.get('dockerHostname')
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400281 def domain = config.get('domain')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400282 def reclassEnv = config.get('reclassEnv')
283 def clusterName = config.get('clusterName', "")
284 def formulasSource = config.get('formulasSource', 'pkg')
285 def extraFormulas = config.get('extraFormulas', 'linux')
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400286 def ignoreClassNotfound = config.get('ignoreClassNotfound', false)
287 def aptRepoUrl = config.get('aptRepoUrl', "")
288 def aptRepoGPG = config.get('aptRepoGPG', "")
289 def testContext = config.get('testContext', 'test')
Denis Egorenko66876fc2019-03-07 15:57:56 +0400290 def nodegenerator = config.get('nodegenerator', false)
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400291 config['envOpts'] = [
292 "RECLASS_ENV=${reclassEnv}", "SALT_STOPSTART_WAIT=5",
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400293 "HOSTNAME=${dockerHostname}", "CLUSTER_NAME=${clusterName}",
294 "DOMAIN=${domain}", "FORMULAS_SOURCE=${formulasSource}",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400295 "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400296 "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}", "DEBUG=1",
Denis Egorenkod54f60f2018-10-10 19:38:03 +0400297 "APT_REPOSITORY=${aptRepoUrl}", "APT_REPOSITORY_GPG=${aptRepoGPG}"
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400298 ]
299
300 config['runCommands'] = [
301 '001_Clone_salt_formulas_scripts': {
azvyagintsev62c97742019-01-02 17:53:54 +0200302 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 +0400303 },
304
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000305 '002_Prepare_something' : {
azvyagintsevb9afd232019-02-11 14:22:31 +0200306 sh('''#!/bin/bash -x
307 rsync -ah ${RECLASS_ENV}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Denis Egorenkoe3509c12019-02-19 14:06:26 +0400308 echo "127.0.0.1 ${HOSTNAME}.${DOMAIN}" >> /etc/hosts
azvyagintsevb9afd232019-02-11 14:22:31 +0200309 if [ -f '/srv/salt/reclass/salt_master_pillar.asc' ] ; then
310 mkdir -p /etc/salt/gpgkeys
311 chmod 700 /etc/salt/gpgkeys
312 GNUPGHOME=/etc/salt/gpgkeys gpg --import /srv/salt/reclass/salt_master_pillar.asc
313 fi
Alexander Evseev4983dec2018-10-25 15:49:39 +0200314 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
315 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 +0400316 ''')
317 },
318
Denis Egorenkoc6b24be2018-10-10 17:36:04 +0400319 '003_Install_Reclass_package' : {
320 sh('apt-get install -y reclass')
321 },
322
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000323 '004_Run_tests' : {
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400324 def testTimeout = 40 * 60
325 timeout(time: testTimeout, unit: 'SECONDS') {
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000326 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400327 source /srv/salt/scripts/bootstrap.sh
328 cd /srv/salt/scripts
329 source_local_envs
330 configure_salt_master
331 configure_salt_minion
332 install_salt_formula_pkg
333 source /srv/salt/scripts/bootstrap.sh
334 cd /srv/salt/scripts
335 saltservice_restart''')
336
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000337 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400338 source /srv/salt/scripts/bootstrap.sh
339 cd /srv/salt/scripts
340 source_local_envs
341 saltmaster_init''')
342
Aleksey Zvyagintsevb20bd262018-10-05 15:09:06 +0000343 sh('''#!/bin/bash
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400344 source /srv/salt/scripts/bootstrap.sh
345 cd /srv/salt/scripts
346 verify_salt_minions''')
347 }
348 }
349 ]
350 config['runFinally'] = [
351 '001_Archive_artefacts': {
352 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
353 archiveArtifacts artifacts: "nodesinfo.tar.gz"
354 }
355 ]
Denis Egorenko66876fc2019-03-07 15:57:56 +0400356 // this tool should be tested in master branch only
357 // and not for all jobs, as pilot will be used cc-reclass-chunk
358 if (nodegenerator) {
359 config['runCommands']['005_Test_new_nodegenerator'] = {
360 try {
361 sh('''#!/bin/bash
362 new_generated_dir=/srv/salt/_new_generated
363 mkdir -p ${new_generated_dir}
364 nodegenerator -b /srv/salt/reclass/classes/ -o ${new_generated_dir} ${CLUSTER_NAME}
365 diff -r /srv/salt/reclass/nodes/_generated ${new_generated_dir} > /tmp/nodegenerator.diff
366 tar -czf /tmp/_generated.tar.gz /srv/salt/reclass/nodes/_generated/
367 tar -czf /tmp/_new_generated.tar.gz ${new_generated_dir}/
368 tar -czf /tmp/_model.tar.gz /srv/salt/reclass/classes/cluster/*
369 ''')
370 } catch (Exception e) {
371 print "Test new nodegenerator tool is failed: ${e}"
372 }
373 }
374 config['runFinally']['002_Archive_nodegenerator_artefact'] = {
375 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)
376 if (fileExists('nodegenerator.tar.gz')) {
377 archiveArtifacts artifacts: "nodegenerator.tar.gz"
378 }
379 }
380 }
Denis Egorenko6fd79ac2018-09-12 13:28:21 +0400381 testResult = setupDockerAndTest(config)
382 if (testResult) {
383 common.infoMsg("Node test for context: ${testContext} model: ${reclassEnv} finished: SUCCESS")
384 } else {
385 throw new RuntimeException("Node test for context: ${testContext} model: ${reclassEnv} finished: FAILURE")
386 }
387 return testResult
388}
389
390/**
chnydaf14ea2a2017-05-26 15:07:47 +0200391 * setup and test salt-master
392 *
azvyagintsevb4e0c442018-09-12 17:00:04 +0300393 * @param masterName salt master's name
394 * @param clusterName model cluster name
395 * @param extraFormulas extraFormulas to install. DEPRECATED
396 * @param formulasSource formulas source (git or pkg)
397 * @param reclassVersion Version of used reclass (branch, tag, ...) (optional, default master)
398 * @param testDir directory of model
399 * @param formulasSource Salt formulas source type (optional, default pkg)
400 * @param formulasRevision APT revision for formulas (optional default stable)
Petr Michalec6414aa52017-08-17 14:32:52 +0200401 * @param ignoreClassNotfound Ignore missing classes for reclass model
azvyagintsevb4e0c442018-09-12 17:00:04 +0300402 * @param dockerMaxCpus max cpus passed to docker (default 0, disabled)
403 * @param legacyTestingMode do you want to enable legacy testing mode (iterating through the nodes directory definitions instead of reading cluster models)
404 * @param aptRepoUrl package repository with salt formulas
405 * @param aptRepoGPG GPG key for apt repository with formulas
azvyagintsev28fa9d92018-06-26 14:31:49 +0300406 * Return true | false
chnydaf14ea2a2017-05-26 15:07:47 +0200407 */
408
azvyagintsevb4e0c442018-09-12 17:00:04 +0300409def setupAndTestNode(masterName, clusterName, extraFormulas = '*', testDir, formulasSource = 'pkg',
Vasyl Saienko369ed902018-07-23 11:49:32 +0000410 formulasRevision = 'stable', reclassVersion = "master", dockerMaxCpus = 0,
azvyagintsev28fa9d92018-06-26 14:31:49 +0300411 ignoreClassNotfound = false, legacyTestingMode = false, aptRepoUrl = '', aptRepoGPG = '', dockerContainerName = false) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300412 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300413 // TODO
414 common.errorMsg('You are using deprecated function!Please migrate to "setupDockerAndTest".' +
415 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
416 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300417 // timeout for test execution (40min)
418 def testTimeout = 40 * 60
419 def TestMarkerResult = false
420 def saltOpts = "--retcode-passthrough --force-color"
421 def workspace = common.getWorkspace()
422 def img = docker.image("mirantis/salt:saltstack-ubuntu-xenial-salt-2017.7")
423 img.pull()
chnydaf14ea2a2017-05-26 15:07:47 +0200424
azvyagintsev635affb2018-09-13 13:02:54 +0300425 if (formulasSource == 'pkg') {
426 if (extraFormulas) {
427 common.warningMsg("You have passed deprecated variable:extraFormulas=${extraFormulas}. " +
428 "\n It would be ignored, and all formulas would be installed anyway")
429 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300430 }
431 if (!dockerContainerName) {
432 dockerContainerName = 'setupAndTestNode' + UUID.randomUUID().toString()
433 }
434 def dockerMaxCpusOpt = "--cpus=4"
435 if (dockerMaxCpus > 0) {
436 dockerMaxCpusOpt = "--cpus=${dockerMaxCpus}"
437 }
438 try {
439 img.inside("-u root:root --hostname=${masterName} --ulimit nofile=4096:8192 ${dockerMaxCpusOpt} --name=${dockerContainerName}") {
azvyagintsev635affb2018-09-13 13:02:54 +0300440 withEnv(["FORMULAS_SOURCE=${formulasSource}", "EXTRA_FORMULAS=${extraFormulas}", "EXTRA_FORMULAS_PKG_ALL=true",
azvyagintsevb4e0c442018-09-12 17:00:04 +0300441 "DISTRIB_REVISION=${formulasRevision}",
442 "DEBUG=1", "MASTER_HOSTNAME=${masterName}",
443 "CLUSTER_NAME=${clusterName}", "MINION_ID=${masterName}",
444 "RECLASS_VERSION=${reclassVersion}", "RECLASS_IGNORE_CLASS_NOTFOUND=${ignoreClassNotfound}",
445 "APT_REPOSITORY=${aptRepoUrl}", "SALT_STOPSTART_WAIT=5",
446 "APT_REPOSITORY_GPG=${aptRepoGPG}"]) {
447 try {
448 // Currently, we don't have any other point to install
449 // runtime dependencies for tests.
450 sh("""#!/bin/bash -xe
azvyagintsev1bfe6842018-08-09 18:40:17 +0200451 echo "Installing extra-deb dependencies inside docker:"
452 echo "APT::Get::AllowUnauthenticated 'true';" > /etc/apt/apt.conf.d/99setupAndTestNode
453 echo "APT::Get::Install-Suggests 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
454 echo "APT::Get::Install-Recommends 'false';" >> /etc/apt/apt.conf.d/99setupAndTestNode
455 rm -vf /etc/apt/sources.list.d/* || true
456 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial main restricted universe' > /etc/apt/sources.list
457 echo 'deb [arch=amd64] http://mirror.mirantis.com/$DISTRIB_REVISION/ubuntu xenial-updates main restricted universe' >> /etc/apt/sources.list
458 apt-get update
459 apt-get install -y python-netaddr
460 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300461 sh(script: "git clone https://github.com/salt-formulas/salt-formulas-scripts /srv/salt/scripts", returnStdout: true)
462 sh("""rsync -ah ${testDir}/* /srv/salt/reclass && echo '127.0.1.2 salt' >> /etc/hosts
Alexander Evseev4983dec2018-10-25 15:49:39 +0200463 cd /srv/salt && find . -type f \\( -name '*.yml' -or -name '*.sh' \\) -exec sed -i 's/apt-mk.mirantis.com/apt.mcp.mirantis.net/g' {} \\;
464 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 +0200465 """)
azvyagintsevb4e0c442018-09-12 17:00:04 +0300466 // FIXME: should be changed to use reclass from mcp_extra_nigtly?
467 sh("""for s in \$(python -c \"import site; print(' '.join(site.getsitepackages()))\"); do
azvyagintsev1bfe6842018-08-09 18:40:17 +0200468 sudo -H pip install --install-option=\"--prefix=\" --upgrade --force-reinstall -I \
469 -t \"\$s\" git+https://github.com/salt-formulas/reclass.git@${reclassVersion};
470 done""")
azvyagintsevb4e0c442018-09-12 17:00:04 +0300471 timeout(time: testTimeout, unit: 'SECONDS') {
472 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200473 source /srv/salt/scripts/bootstrap.sh
474 cd /srv/salt/scripts
475 source_local_envs
476 configure_salt_master
477 configure_salt_minion
478 install_salt_formula_pkg
479 source /srv/salt/scripts/bootstrap.sh
480 cd /srv/salt/scripts
481 saltservice_restart''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300482 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 saltmaster_init''')
487
azvyagintsevb4e0c442018-09-12 17:00:04 +0300488 if (!legacyTestingMode.toBoolean()) {
489 sh('''#!/bin/bash
azvyagintsev1bfe6842018-08-09 18:40:17 +0200490 source /srv/salt/scripts/bootstrap.sh
491 cd /srv/salt/scripts
492 verify_salt_minions
493 ''')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300494 }
495 }
496 // If we didn't dropped for now - test has been passed.
497 TestMarkerResult = true
498 }
499
500 finally {
501 // Collect rendered per-node data.Those info could be simply used
502 // for diff processing. Data was generated via reclass.cli --nodeinfo,
503 /// during verify_salt_minions.
504 sh(script: "cd /tmp; tar -czf ${env.WORKSPACE}/nodesinfo.tar.gz *reclass*", returnStatus: true)
505 archiveArtifacts artifacts: "nodesinfo.tar.gz"
506 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200507 }
azvyagintsev1bfe6842018-08-09 18:40:17 +0200508 }
chnydaf14ea2a2017-05-26 15:07:47 +0200509 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300510 catch (Exception er) {
511 common.warningMsg("IgnoreMe:Something wrong with img.Message:\n" + er.toString())
512 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300513
azvyagintsevb4e0c442018-09-12 17:00:04 +0300514 if (legacyTestingMode.toBoolean()) {
515 common.infoMsg("Running legacy mode test for master hostname ${masterName}")
516 def nodes = sh(script: "find /srv/salt/reclass/nodes -name '*.yml' | grep -v 'cfg*.yml'", returnStdout: true)
517 for (minion in nodes.tokenize()) {
518 def basename = sh(script: "set +x;basename ${minion} .yml", returnStdout: true)
519 if (!basename.trim().contains(masterName)) {
520 testMinion(basename.trim())
521 }
522 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300523 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300524
azvyagintsevb4e0c442018-09-12 17:00:04 +0300525 try {
526 common.warningMsg("IgnoreMe:Force cleanup slave.Ignore docker-daemon errors")
527 timeout(time: 10, unit: 'SECONDS') {
528 sh(script: "set -x; docker kill ${dockerContainerName} || true", returnStdout: true)
529 }
530 timeout(time: 10, unit: 'SECONDS') {
531 sh(script: "set -x; docker rm --force ${dockerContainerName} || true", returnStdout: true)
532 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300533 }
azvyagintsevb4e0c442018-09-12 17:00:04 +0300534 catch (Exception er) {
535 common.warningMsg("IgnoreMe:Timeout to delete test docker container with force!Message:\n" + er.toString())
azvyagintsev28fa9d92018-06-26 14:31:49 +0300536 }
azvyagintsev28fa9d92018-06-26 14:31:49 +0300537
azvyagintsevb4e0c442018-09-12 17:00:04 +0300538 if (TestMarkerResult) {
539 common.infoMsg("Test finished: SUCCESS")
540 } else {
541 common.warningMsg("Test finished: FAILURE")
542 }
543 return TestMarkerResult
azvyagintsev28fa9d92018-06-26 14:31:49 +0300544
chnydaf14ea2a2017-05-26 15:07:47 +0200545}
546
547/**
548 * Test salt-minion
549 *
azvyagintsev28fa9d92018-06-26 14:31:49 +0300550 * @param minion salt minion
chnydaf14ea2a2017-05-26 15:07:47 +0200551 */
552
azvyagintsev28fa9d92018-06-26 14:31:49 +0300553def testMinion(minionName) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300554 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 +0200555}
azvyagintsev2b279d82018-08-07 17:22:54 +0200556
azvyagintsev2b279d82018-08-07 17:22:54 +0200557/**
558 * Wrapper over setupAndTestNode, to test exactly one CC model.
azvyagintsevb4e0c442018-09-12 17:00:04 +0300559 Whole workspace and model - should be pre-rendered and passed via MODELS_TARGZ
560 Flow: grab all data, and pass to setupAndTestNode function
561 under-modell will be directly mirrored to `model/{cfg.testReclassEnv}/* /srv/salt/reclass/*`
azvyagintsev2b279d82018-08-07 17:22:54 +0200562 *
563 * @param cfg - dict with params:
azvyagintsevb4e0c442018-09-12 17:00:04 +0300564 MODELS_TARGZ http link to arch with (models|contexts|global_reclass)
565 modelFile
566 DockerCName directly passed to setupAndTestNode
567 EXTRA_FORMULAS directly passed to setupAndTestNode
568 DISTRIB_REVISION directly passed to setupAndTestNode
569 reclassVersion directly passed to setupAndTestNode
azvyagintsev2b279d82018-08-07 17:22:54 +0200570
azvyagintsevb4e0c442018-09-12 17:00:04 +0300571 Return: true\exception
azvyagintsev2b279d82018-08-07 17:22:54 +0200572 */
573
574def testCCModel(cfg) {
azvyagintsevb4e0c442018-09-12 17:00:04 +0300575 def common = new com.mirantis.mk.Common()
azvyagintsev1cecc092018-09-14 13:19:16 +0300576 common.errorMsg('You are using deprecated function!Please migrate to "testNode".' +
577 'It would be removed after 2018.q4 release!Pushing forced 60s sleep..')
578 sh('sleep 60')
azvyagintsevb4e0c442018-09-12 17:00:04 +0300579 sh(script: 'find . -mindepth 1 -delete || true', returnStatus: true)
580 sh(script: "wget --progress=dot:mega --auth-no-challenge -O models.tar.gz ${cfg.MODELS_TARGZ}")
581 // unpack data
582 sh(script: "tar -xzf models.tar.gz ")
583 common.infoMsg("Going to test exactly one context: ${cfg.modelFile}\n, with params: ${cfg}")
584 content = readFile(file: cfg.modelFile)
585 templateContext = readYaml text: content
586 clusterName = templateContext.default_context.cluster_name
587 clusterDomain = templateContext.default_context.cluster_domain
azvyagintsev2b279d82018-08-07 17:22:54 +0200588
azvyagintsevb4e0c442018-09-12 17:00:04 +0300589 def testResult = false
590 testResult = setupAndTestNode(
591 "cfg01.${clusterDomain}",
592 clusterName,
593 '',
594 cfg.testReclassEnv, // Sync into image exactly one env
595 'pkg',
596 cfg.DISTRIB_REVISION,
597 cfg.reclassVersion,
598 0,
599 false,
600 false,
601 '',
602 '',
603 cfg.DockerCName)
604 if (testResult) {
605 common.infoMsg("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: SUCCESS")
606 } else {
607 throw new RuntimeException("testCCModel for context: ${cfg.modelFile} model: ${cfg.testReclassEnv} finished: FAILURE")
608 }
609 return testResult
azvyagintsev2b279d82018-08-07 17:22:54 +0200610}