blob: 601f3e0505e478f5ce7054e0afc8113cc92fd8a0 [file] [log] [blame]
Sergey Kolekonovba203982016-12-21 18:32:17 +04001package com.mirantis.mk
2
3/**
4 *
5 * Python functions
6 *
7 */
8
9/**
10 * Install python virtualenv
11 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000012 * @param path Path to virtualenv
13 * @param python Version of Python (python/python3)
14 * @param reqs Environment requirements in list format
15 * @param reqs_path Environment requirements path in str format
Sergey Kolekonovba203982016-12-21 18:32:17 +040016 */
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000017def setupVirtualenv(path, python = 'python2', reqs = [], reqs_path = null, clean = false, useSystemPackages = false) {
Tomáš Kukrál69c25452017-07-27 14:59:40 +020018 def common = new com.mirantis.mk.Common()
19
Jakub Josef87a8a3c2018-01-26 12:11:11 +010020 def offlineDeployment = env.getEnvironment().containsKey("OFFLINE_DEPLOYMENT") && env["OFFLINE_DEPLOYMENT"].toBoolean()
Mykyta Karpin1e4bfc92017-11-01 14:38:25 +020021 def virtualenv_cmd = "virtualenv ${path} --python ${python}"
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000022 if (useSystemPackages) {
Jakub Josef996f4ef2017-10-24 13:20:43 +020023 virtualenv_cmd += " --system-site-packages"
24 }
Tomáš Kukrál69c25452017-07-27 14:59:40 +020025 if (clean) {
26 common.infoMsg("Cleaning venv directory " + path)
27 sh("rm -rf \"${path}\"")
28 }
29
Vasyl Saienko1e2d09c2020-01-21 14:30:49 +020030 // NOTE(vsaienko): unless is fixed in upstream https://github.com/pypa/pip/issues/7620
31 //if (offlineDeployment) {
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000032 virtualenv_cmd += " --no-download"
Vasyl Saienko1e2d09c2020-01-21 14:30:49 +020033 //}
Tomáš Kukrál69c25452017-07-27 14:59:40 +020034 common.infoMsg("[Python ${path}] Setup ${python} environment")
Sergey Kolekonovba203982016-12-21 18:32:17 +040035 sh(returnStdout: true, script: virtualenv_cmd)
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000036 if (!offlineDeployment) {
37 try {
Denis Egorenko89171f92019-11-12 13:49:23 +040038 def pipPackage = 'pip'
39 if (python == 'python2') {
40 pipPackage = "\"pip<=19.3.1\""
41 common.infoMsg("Pinning pip package due to end of life of Python2 to ${pipPackage} version.")
42 }
Vasyl Saienko9a2bd372020-01-13 10:00:04 +020043 // NOTE(vsaienko): pin setuptools explicitly for latest version that works with python2
Vasyl Saienko1e2d09c2020-01-21 14:30:49 +020044 runVirtualenvCommand(path, "pip install -U \"setuptools<45.0.0\"")
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000045 } catch (Exception e) {
46 common.warningMsg("Setuptools and pip cannot be updated, you might be offline but OFFLINE_DEPLOYMENT global property not initialized!")
47 }
Yuriy Taraday67352e92017-10-12 10:54:23 +000048 }
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000049 if (reqs_path == null) {
Vladislav Naumov11103862017-07-19 17:02:39 +030050 def args = ""
51 for (req in reqs) {
52 args = args + "${req}\n"
53 }
54 writeFile file: "${path}/requirements.txt", text: args
55 reqs_path = "${path}/requirements.txt"
Sergey Kolekonovba203982016-12-21 18:32:17 +040056 }
Jakub Josefa2491ad2018-01-15 16:26:27 +010057 runVirtualenvCommand(path, "pip install -r ${reqs_path}", true)
Sergey Kolekonovba203982016-12-21 18:32:17 +040058}
59
60/**
61 * Run command in specific python virtualenv
62 *
azvyagintsev386e94e2019-06-13 13:39:04 +030063 * @param path Path to virtualenv
64 * @param cmd Command to be executed
Jakub Josefe2f4ebb2018-01-15 16:11:51 +010065 * @param silent dont print any messages (optional, default false)
azvyagintsev386e94e2019-06-13 13:39:04 +030066 * @param flexAnswer return answer like a dict, with format ['status' : int, 'stderr' : str, 'stdout' : str ]
Sergey Kolekonovba203982016-12-21 18:32:17 +040067 */
azvyagintsev386e94e2019-06-13 13:39:04 +030068def runVirtualenvCommand(path, cmd, silent = false, flexAnswer = false) {
Tomáš Kukrál69c25452017-07-27 14:59:40 +020069 def common = new com.mirantis.mk.Common()
azvyagintsev386e94e2019-06-13 13:39:04 +030070 def res
71 def virtualenv_cmd = "set +x; . ${path}/bin/activate; ${cmd}"
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000072 if (!silent) {
Jakub Josefe2f4ebb2018-01-15 16:11:51 +010073 common.infoMsg("[Python ${path}] Run command ${cmd}")
74 }
azvyagintsev386e94e2019-06-13 13:39:04 +030075 if (flexAnswer) {
76 res = common.shCmdStatus(virtualenv_cmd)
77 } else {
78 res = sh(
79 returnStdout: true,
80 script: virtualenv_cmd
81 ).trim()
82 }
83 return res
Sergey Kolekonovba203982016-12-21 18:32:17 +040084}
85
Ales Komarekd874d482016-12-26 10:33:29 +010086/**
Dennis Dmitriev8ac1fe72019-08-01 06:16:49 +030087 * Another command runner to control outputs and exit code
88 *
89 * - always print the executing command to control the pipeline execution
90 * - always allows to get the stdout/stderr/status in the result, even with enabled console enabled
91 * - throws an exception with stderr content, so it could be read from the job status and processed
92 *
93 * @param cmd String, command to be executed
94 * @param virtualenv String, path to Python virtualenv (optional, default: '')
95 * @param verbose Boolean, true: (default) mirror stdout to console and to the result['stdout'] at the same time,
96 * false: store stdout only to result['stdout']
97 * @param check_status Boolean, true: (default) throw an exception which contains result['stderr'] if exit code is not 0,
98 * false: only print stderr if not empty, and return the result
99 * @return Map, ['status' : int, 'stderr' : str, 'stdout' : str ]
100 */
101def runCmd(String cmd, String virtualenv='', Boolean verbose=true, Boolean check_status=true) {
102 def common = new com.mirantis.mk.Common()
103
104 def script
105 def redirect_output
106 def result = [:]
107 def stdout_path = sh(script: '#!/bin/bash +x\nmktemp', returnStdout: true).trim()
108 def stderr_path = sh(script: '#!/bin/bash +x\nmktemp', returnStdout: true).trim()
109
110 if (verbose) {
111 // show stdout to console and store to stdout_path
112 redirect_output = " 1> >(tee -a ${stdout_path}) 2>${stderr_path}"
113 } else {
114 // only store stdout to stdout_path
115 redirect_output = " 1>${stdout_path} 2>${stderr_path}"
116 }
117
118 if (virtualenv) {
119 common.infoMsg("Run shell command in Python virtualenv [${virtualenv}]:\n" + cmd)
120 script = """#!/bin/bash +x
121 . ${virtualenv}/bin/activate
122 ( ${cmd.stripIndent()} ) ${redirect_output}
123 """
124 } else {
125 common.infoMsg('Run shell command:\n' + cmd)
126 script = """#!/bin/bash +x
127 ( ${cmd.stripIndent()} ) ${redirect_output}
128 """
129 }
130
131 result['status'] = sh(script: script, returnStatus: true)
132 result['stdout'] = readFile(stdout_path)
133 result['stderr'] = readFile(stderr_path)
134 def cleanup_script = """#!/bin/bash +x
135 rm ${stdout_path} || true
136 rm ${stderr_path} || true
137 """
138 sh(script: cleanup_script)
139
140 if (result['status'] != 0 && check_status) {
141 def error_message = '\nScript returned exit code: ' + result['status'] + '\n<<<<<< STDERR: >>>>>>\n' + result['stderr']
142 common.errorMsg(error_message)
143 common.printMsg('', 'reset')
144 throw new Exception(error_message)
145 }
146
147 if (result['stderr'] && verbose) {
148 def warning_message = '\nScript returned exit code: ' + result['status'] + '\n<<<<<< STDERR: >>>>>>\n' + result['stderr']
149 common.warningMsg(warning_message)
150 common.printMsg('', 'reset')
151 }
152
153 return result
154}
155
156/**
Ales Komarekd874d482016-12-26 10:33:29 +0100157 * Install docutils in isolated environment
158 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000159 * @param path Path where virtualenv is created
Ales Komarekd874d482016-12-26 10:33:29 +0100160 */
Vasyl Saienko9a2bd372020-01-13 10:00:04 +0200161def setupDocutilsVirtualenv(path, python="python2") {
Ales Komarekd874d482016-12-26 10:33:29 +0100162 requirements = [
Denis Egorenko97ef0fb2020-01-13 14:22:49 +0400163 'docutils==0.16',
Ales Komarekd874d482016-12-26 10:33:29 +0100164 ]
Vasyl Saienko9a2bd372020-01-13 10:00:04 +0200165 setupVirtualenv(path, python, requirements)
Ales Komarekd874d482016-12-26 10:33:29 +0100166}
167
168
Sergey Kolekonovba203982016-12-21 18:32:17 +0400169@NonCPS
170def loadJson(rawData) {
171 return new groovy.json.JsonSlurperClassic().parseText(rawData)
172}
173
174/**
175 * Parse content from markup-text tables to variables
176 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000177 * @param tableStr String representing the table
178 * @param mode Either list (1st row are keys) or item (key, value rows)
179 * @param format Format of the table
Sergey Kolekonovba203982016-12-21 18:32:17 +0400180 */
Ales Komarekd874d482016-12-26 10:33:29 +0100181def parseTextTable(tableStr, type = 'item', format = 'rest', path = none) {
Ales Komarek0e558ee2016-12-23 13:02:55 +0100182 parserFile = "${env.WORKSPACE}/textTableParser.py"
183 parserScript = """import json
184import argparse
185from docutils.parsers.rst import tableparser
186from docutils import statemachine
187
188def parse_item_table(raw_data):
189 i = 1
190 pretty_raw_data = []
191 for datum in raw_data:
192 if datum != "":
193 if datum[3] != ' ' and i > 4:
194 pretty_raw_data.append(raw_data[0])
195 if i == 3:
196 pretty_raw_data.append(datum.replace('-', '='))
197 else:
198 pretty_raw_data.append(datum)
199 i += 1
200 parser = tableparser.GridTableParser()
201 block = statemachine.StringList(pretty_raw_data)
202 docutils_data = parser.parse(block)
203 final_data = {}
204 for line in docutils_data[2]:
205 key = ' '.join(line[0][3]).strip()
206 value = ' '.join(line[1][3]).strip()
207 if key != "":
208 try:
209 value = json.loads(value)
210 except:
211 pass
212 final_data[key] = value
213 i+=1
214 return final_data
215
216def parse_list_table(raw_data):
217 i = 1
218 pretty_raw_data = []
219 for datum in raw_data:
220 if datum != "":
221 if datum[3] != ' ' and i > 4:
222 pretty_raw_data.append(raw_data[0])
223 if i == 3:
224 pretty_raw_data.append(datum.replace('-', '='))
225 else:
226 pretty_raw_data.append(datum)
227 i += 1
228 parser = tableparser.GridTableParser()
229 block = statemachine.StringList(pretty_raw_data)
230 docutils_data = parser.parse(block)
231 final_data = []
232 keys = []
233 for line in docutils_data[1]:
234 for item in line:
235 keys.append(' '.join(item[3]).strip())
236 for line in docutils_data[2]:
237 final_line = {}
238 key = ' '.join(line[0][3]).strip()
239 value = ' '.join(line[1][3]).strip()
240 if key != "":
241 try:
242 value = json.loads(value)
243 except:
244 pass
245 final_data[key] = value
246 i+=1
247 return final_data
248
249def parse_list_table(raw_data):
250 i = 1
251 pretty_raw_data = []
252 for datum in raw_data:
253 if datum != "":
254 if datum[3] != ' ' and i > 4:
255 pretty_raw_data.append(raw_data[0])
256 if i == 3:
257 pretty_raw_data.append(datum.replace('-', '='))
258 else:
259 pretty_raw_data.append(datum)
260 i += 1
261 parser = tableparser.GridTableParser()
262 block = statemachine.StringList(pretty_raw_data)
263 docutils_data = parser.parse(block)
264 final_data = []
265 keys = []
266 for line in docutils_data[1]:
267 for item in line:
268 keys.append(' '.join(item[3]).strip())
269 for line in docutils_data[2]:
270 final_line = {}
271 i = 0
272 for item in line:
273 value = ' '.join(item[3]).strip()
274 try:
275 value = json.loads(value)
276 except:
277 pass
278 final_line[keys[i]] = value
279 i += 1
280 final_data.append(final_line)
281 return final_data
282
283def read_table_file(file):
284 table_file = open(file, 'r')
Ales Komarekc000c152016-12-23 15:32:54 +0100285 raw_data = table_file.read().split('\\n')
Ales Komarek0e558ee2016-12-23 13:02:55 +0100286 table_file.close()
287 return raw_data
288
289parser = argparse.ArgumentParser()
290parser.add_argument('-f','--file', help='File with table data', required=True)
291parser.add_argument('-t','--type', help='Type of table (list/item)', required=True)
292args = vars(parser.parse_args())
293
294raw_data = read_table_file(args['file'])
295
296if args['type'] == 'list':
297 final_data = parse_list_table(raw_data)
298else:
299 final_data = parse_item_table(raw_data)
300
301print json.dumps(final_data)
302"""
303 writeFile file: parserFile, text: parserScript
Sergey Kolekonovba203982016-12-21 18:32:17 +0400304 tableFile = "${env.WORKSPACE}/prettytable.txt"
305 writeFile file: tableFile, text: tableStr
Ales Komarekd874d482016-12-26 10:33:29 +0100306
307 cmd = "python ${parserFile} --file '${tableFile}' --type ${type}"
308 if (path) {
Ales Komarekc6d28dd2016-12-28 12:59:38 +0100309 rawData = runVirtualenvCommand(path, cmd)
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000310 } else {
311 rawData = sh(
Ales Komarekd874d482016-12-26 10:33:29 +0100312 script: cmd,
313 returnStdout: true
314 ).trim()
315 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400316 data = loadJson(rawData)
317 echo("[Parsed table] ${data}")
318 return data
319}
320
321/**
322 * Install cookiecutter in isolated environment
323 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000324 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400325 */
326def setupCookiecutterVirtualenv(path) {
327 requirements = [
328 'cookiecutter',
Jakub Josef4df78272017-04-26 14:36:36 +0200329 'jinja2==2.8.1',
Dmitry Pyzhovb883a2d2018-12-14 16:42:52 +0300330 'PyYAML==3.12',
331 'python-gnupg==0.4.3'
Sergey Kolekonovba203982016-12-21 18:32:17 +0400332 ]
333 setupVirtualenv(path, 'python2', requirements)
334}
335
336/**
337 * Generate the cookiecutter templates with given context
338 *
Jakub Josef4e10c372017-04-26 14:13:50 +0200339 * @param template template
340 * @param context template context
341 * @param path Path where virtualenv is created (optional)
342 * @param templatePath path to cookiecutter template repo (optional)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400343 */
Jakub Josef4e10c372017-04-26 14:13:50 +0200344def buildCookiecutterTemplate(template, context, outputDir = '.', path = null, templatePath = ".") {
azvyagintsev7a123aa2019-01-09 21:38:56 +0200345 def common = new com.mirantis.mk.Common()
Tomáš Kukráldad7b462017-03-27 13:53:05 +0200346 configFile = "default_config.yaml"
Tomáš Kukrál6de85042017-04-12 17:49:05 +0200347 writeFile file: configFile, text: context
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000348 common.warningMsg('Old Cookiecutter env detected!')
349 command = ". ${path}/bin/activate; if [ -f ${templatePath}/generate.py ]; then python ${templatePath}/generate.py --config-file ${configFile} --template ${template} --output-dir ${outputDir}; else cookiecutter --config-file ${configFile} --output-dir ${outputDir} --overwrite-if-exists --verbose --no-input ${template}; fi"
350 output = sh(returnStdout: true, script: command)
351 common.infoMsg('[Cookiecutter build] Result:' + output)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400352}
353
354/**
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400355 *
356 * @param context - context template
357 * @param contextName - context template name
358 * @param saltMasterName - hostname of Salt Master node
359 * @param virtualenv - pyvenv with CC and dep's
360 * @param templateEnvDir - root of CookieCutter
361 * @return
362 */
363def generateModel(context, contextName, saltMasterName, virtualenv, modelEnv, templateEnvDir, multiModels = true) {
Denis Egorenkofa2c6752018-10-18 15:51:45 +0400364 def common = new com.mirantis.mk.Common()
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400365 def generatedModel = multiModels ? "${modelEnv}/${contextName}" : modelEnv
366 def templateContext = readYaml text: context
367 def clusterDomain = templateContext.default_context.cluster_domain
368 def clusterName = templateContext.default_context.cluster_name
369 def outputDestination = "${generatedModel}/classes/cluster/${clusterName}"
370 def templateBaseDir = templateEnvDir
371 def templateDir = "${templateEnvDir}/dir"
372 def templateOutputDir = templateBaseDir
373 dir(templateEnvDir) {
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000374 if (fileExists(new File(templateEnvDir, 'tox.ini').toString())) {
Aleksey Zvyagintsev07b07ba2019-02-28 13:34:13 +0000375 def tempContextFile = new File(templateEnvDir, 'tempContext.yaml').toString()
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000376 writeFile file: tempContextFile, text: context
377 common.warningMsg('Generating models using context:\n')
378 print(context)
379 withEnv(["CONFIG_FILE=$tempContextFile",
Aleksey Zvyagintsev07b07ba2019-02-28 13:34:13 +0000380 "OUTPUT_DIR=${modelEnv}",
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000381 ]) {
382 print('[Cookiecutter build] Result:\n' +
383 sh(returnStdout: true, script: 'tox -ve generate_auto'))
Aleksey Zvyagintsev4c745e52019-02-21 10:30:02 +0000384 }
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000385 } else {
386 common.warningMsg("Old format: Generating model from context ${contextName}")
387 def productList = ["infra", "cicd", "kdt", "opencontrail", "kubernetes", "openstack", "oss", "stacklight", "ceph"]
388 for (product in productList) {
389 // get templateOutputDir and productDir
390 templateOutputDir = "${templateEnvDir}/output/${product}"
391 productDir = product
392 templateDir = "${templateEnvDir}/cluster_product/${productDir}"
393 // Bw for 2018.8.1 and older releases
394 if (product.startsWith("stacklight") && (!fileExists(templateDir))) {
395 common.warningMsg("Old release detected! productDir => 'stacklight2' ")
396 productDir = "stacklight2"
397 templateDir = "${templateEnvDir}/cluster_product/${productDir}"
398 }
399 // generate infra unless its explicitly disabled
400 if ((product == "infra" && templateContext.default_context.get("infra_enabled", "True").toBoolean())
401 || (templateContext.default_context.get(product + "_enabled", "False").toBoolean())) {
402
403 common.infoMsg("Generating product " + product + " from " + templateDir + " to " + templateOutputDir)
404
405 sh "rm -rf ${templateOutputDir} || true"
406 sh "mkdir -p ${templateOutputDir}"
407 sh "mkdir -p ${outputDestination}"
408
409 buildCookiecutterTemplate(templateDir, context, templateOutputDir, virtualenv, templateBaseDir)
410 sh "mv -v ${templateOutputDir}/${clusterName}/* ${outputDestination}"
411 } else {
412 common.warningMsg("Product " + product + " is disabled")
413 }
414 }
415
416 def localRepositories = templateContext.default_context.local_repositories
417 localRepositories = localRepositories ? localRepositories.toBoolean() : false
418 def offlineDeployment = templateContext.default_context.offline_deployment
419 offlineDeployment = offlineDeployment ? offlineDeployment.toBoolean() : false
420 if (localRepositories && !offlineDeployment) {
421 def mcpVersion = templateContext.default_context.mcp_version
422 def aptlyModelUrl = templateContext.default_context.local_model_url
423 def ssh = new com.mirantis.mk.Ssh()
424 dir(path: modelEnv) {
425 ssh.agentSh "git submodule add \"${aptlyModelUrl}\" \"classes/cluster/${clusterName}/cicd/aptly\""
426 if (!(mcpVersion in ["nightly", "testing", "stable"])) {
427 ssh.agentSh "cd \"classes/cluster/${clusterName}/cicd/aptly\";git fetch --tags;git checkout ${mcpVersion}"
428 }
429 }
430 }
431
432 def nodeFile = "${generatedModel}/nodes/${saltMasterName}.${clusterDomain}.yml"
433 def nodeString = """classes:
434- cluster.${clusterName}.infra.config
435parameters:
436 _param:
437 linux_system_codename: xenial
438 reclass_data_revision: master
439 linux:
440 system:
441 name: ${saltMasterName}
442 domain: ${clusterDomain}
443 """
444 sh "mkdir -p ${generatedModel}/nodes/"
445 writeFile(file: nodeFile, text: nodeString)
446 }
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400447 }
448}
449
450/**
Sergey Kolekonovba203982016-12-21 18:32:17 +0400451 * Install jinja rendering in isolated environment
452 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000453 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400454 */
455def setupJinjaVirtualenv(path) {
456 requirements = [
Denis Egorenko97ef0fb2020-01-13 14:22:49 +0400457 'jinja2-cli==0.7.0',
458 'pyyaml==5.3',
Sergey Kolekonovba203982016-12-21 18:32:17 +0400459 ]
460 setupVirtualenv(path, 'python2', requirements)
461}
462
463/**
464 * Generate the Jinja templates with given context
465 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000466 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400467 */
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000468def jinjaBuildTemplate(template, context, path = none) {
Sergey Kolekonovba203982016-12-21 18:32:17 +0400469 contextFile = "jinja_context.yml"
470 contextString = ""
471 for (parameter in context) {
472 contextString = "${contextString}${parameter.key}: ${parameter.value}\n"
473 }
474 writeFile file: contextFile, text: contextString
475 cmd = "jinja2 ${template} ${contextFile} --format=yaml"
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000476 data = sh(returnStdout: true, script: cmd)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400477 echo(data)
478 return data
479}
Oleg Grigorovbec45582017-09-12 20:29:24 +0300480
481/**
482 * Install salt-pepper in isolated environment
483 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000484 * @param path Path where virtualenv is created
485 * @param url SALT_MASTER_URL
486 * @param credentialsId Credentials to salt api
Oleg Grigorovbec45582017-09-12 20:29:24 +0300487 */
Jakub Josefc9b6d662018-02-21 16:21:03 +0100488def setupPepperVirtualenv(path, url, credentialsId) {
chnydaa0dbb252017-10-05 10:46:09 +0200489 def common = new com.mirantis.mk.Common()
490
491 // virtualenv setup
Mykyta Karpin81756c92018-03-02 13:03:26 +0200492 // pin pepper till https://mirantis.jira.com/browse/PROD-18188 is fixed
493 requirements = ['salt-pepper>=0.5.2,<0.5.4']
Jakub Josefc9b6d662018-02-21 16:21:03 +0100494 setupVirtualenv(path, 'python2', requirements, null, true, true)
chnydabcfff182017-11-29 10:24:36 +0100495
chnydaa0dbb252017-10-05 10:46:09 +0200496 // pepperrc creation
497 rcFile = "${path}/pepperrc"
498 creds = common.getPasswordCredentials(credentialsId)
499 rc = """\
500[main]
501SALTAPI_EAUTH=pam
502SALTAPI_URL=${url}
503SALTAPI_USER=${creds.username}
504SALTAPI_PASS=${creds.password.toString()}
505"""
506 writeFile file: rcFile, text: rc
507 return rcFile
Jakub Josefd067f612017-09-26 13:42:56 +0200508}
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300509
510/**
511 * Install devops in isolated environment
512 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000513 * @param path Path where virtualenv is created
514 * @param clean Define to true is the venv have to cleaned up before install a new one
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300515 */
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000516def setupDevOpsVenv(venv, clean = false) {
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300517 requirements = ['git+https://github.com/openstack/fuel-devops.git']
518 setupVirtualenv(venv, 'python2', requirements, null, false, clean)
519}