blob: 8d9d19b39e3c1f59ac32f1d793f55698b600f3e6 [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
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000030 if (offlineDeployment) {
31 virtualenv_cmd += " --no-download"
Jakub Josef87a8a3c2018-01-26 12:11:11 +010032 }
Tomáš Kukrál69c25452017-07-27 14:59:40 +020033 common.infoMsg("[Python ${path}] Setup ${python} environment")
Sergey Kolekonovba203982016-12-21 18:32:17 +040034 sh(returnStdout: true, script: virtualenv_cmd)
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000035 if (!offlineDeployment) {
36 try {
37 runVirtualenvCommand(path, "pip install -U setuptools pip")
38 } catch (Exception e) {
39 common.warningMsg("Setuptools and pip cannot be updated, you might be offline but OFFLINE_DEPLOYMENT global property not initialized!")
40 }
Yuriy Taraday67352e92017-10-12 10:54:23 +000041 }
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000042 if (reqs_path == null) {
Vladislav Naumov11103862017-07-19 17:02:39 +030043 def args = ""
44 for (req in reqs) {
45 args = args + "${req}\n"
46 }
47 writeFile file: "${path}/requirements.txt", text: args
48 reqs_path = "${path}/requirements.txt"
Sergey Kolekonovba203982016-12-21 18:32:17 +040049 }
Jakub Josefa2491ad2018-01-15 16:26:27 +010050 runVirtualenvCommand(path, "pip install -r ${reqs_path}", true)
Sergey Kolekonovba203982016-12-21 18:32:17 +040051}
52
53/**
54 * Run command in specific python virtualenv
55 *
azvyagintsev386e94e2019-06-13 13:39:04 +030056 * @param path Path to virtualenv
57 * @param cmd Command to be executed
Jakub Josefe2f4ebb2018-01-15 16:11:51 +010058 * @param silent dont print any messages (optional, default false)
azvyagintsev386e94e2019-06-13 13:39:04 +030059 * @param flexAnswer return answer like a dict, with format ['status' : int, 'stderr' : str, 'stdout' : str ]
Sergey Kolekonovba203982016-12-21 18:32:17 +040060 */
azvyagintsev386e94e2019-06-13 13:39:04 +030061def runVirtualenvCommand(path, cmd, silent = false, flexAnswer = false) {
Tomáš Kukrál69c25452017-07-27 14:59:40 +020062 def common = new com.mirantis.mk.Common()
azvyagintsev386e94e2019-06-13 13:39:04 +030063 def res
64 def virtualenv_cmd = "set +x; . ${path}/bin/activate; ${cmd}"
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000065 if (!silent) {
Jakub Josefe2f4ebb2018-01-15 16:11:51 +010066 common.infoMsg("[Python ${path}] Run command ${cmd}")
67 }
azvyagintsev386e94e2019-06-13 13:39:04 +030068 if (flexAnswer) {
69 res = common.shCmdStatus(virtualenv_cmd)
70 } else {
71 res = sh(
72 returnStdout: true,
73 script: virtualenv_cmd
74 ).trim()
75 }
76 return res
Sergey Kolekonovba203982016-12-21 18:32:17 +040077}
78
Ales Komarekd874d482016-12-26 10:33:29 +010079/**
80 * Install docutils in isolated environment
81 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000082 * @param path Path where virtualenv is created
Ales Komarekd874d482016-12-26 10:33:29 +010083 */
84def setupDocutilsVirtualenv(path) {
85 requirements = [
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +000086 'docutils',
Ales Komarekd874d482016-12-26 10:33:29 +010087 ]
88 setupVirtualenv(path, 'python2', requirements)
89}
90
91
Sergey Kolekonovba203982016-12-21 18:32:17 +040092@NonCPS
93def loadJson(rawData) {
94 return new groovy.json.JsonSlurperClassic().parseText(rawData)
95}
96
97/**
98 * Parse content from markup-text tables to variables
99 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000100 * @param tableStr String representing the table
101 * @param mode Either list (1st row are keys) or item (key, value rows)
102 * @param format Format of the table
Sergey Kolekonovba203982016-12-21 18:32:17 +0400103 */
Ales Komarekd874d482016-12-26 10:33:29 +0100104def parseTextTable(tableStr, type = 'item', format = 'rest', path = none) {
Ales Komarek0e558ee2016-12-23 13:02:55 +0100105 parserFile = "${env.WORKSPACE}/textTableParser.py"
106 parserScript = """import json
107import argparse
108from docutils.parsers.rst import tableparser
109from docutils import statemachine
110
111def parse_item_table(raw_data):
112 i = 1
113 pretty_raw_data = []
114 for datum in raw_data:
115 if datum != "":
116 if datum[3] != ' ' and i > 4:
117 pretty_raw_data.append(raw_data[0])
118 if i == 3:
119 pretty_raw_data.append(datum.replace('-', '='))
120 else:
121 pretty_raw_data.append(datum)
122 i += 1
123 parser = tableparser.GridTableParser()
124 block = statemachine.StringList(pretty_raw_data)
125 docutils_data = parser.parse(block)
126 final_data = {}
127 for line in docutils_data[2]:
128 key = ' '.join(line[0][3]).strip()
129 value = ' '.join(line[1][3]).strip()
130 if key != "":
131 try:
132 value = json.loads(value)
133 except:
134 pass
135 final_data[key] = value
136 i+=1
137 return final_data
138
139def parse_list_table(raw_data):
140 i = 1
141 pretty_raw_data = []
142 for datum in raw_data:
143 if datum != "":
144 if datum[3] != ' ' and i > 4:
145 pretty_raw_data.append(raw_data[0])
146 if i == 3:
147 pretty_raw_data.append(datum.replace('-', '='))
148 else:
149 pretty_raw_data.append(datum)
150 i += 1
151 parser = tableparser.GridTableParser()
152 block = statemachine.StringList(pretty_raw_data)
153 docutils_data = parser.parse(block)
154 final_data = []
155 keys = []
156 for line in docutils_data[1]:
157 for item in line:
158 keys.append(' '.join(item[3]).strip())
159 for line in docutils_data[2]:
160 final_line = {}
161 key = ' '.join(line[0][3]).strip()
162 value = ' '.join(line[1][3]).strip()
163 if key != "":
164 try:
165 value = json.loads(value)
166 except:
167 pass
168 final_data[key] = value
169 i+=1
170 return final_data
171
172def parse_list_table(raw_data):
173 i = 1
174 pretty_raw_data = []
175 for datum in raw_data:
176 if datum != "":
177 if datum[3] != ' ' and i > 4:
178 pretty_raw_data.append(raw_data[0])
179 if i == 3:
180 pretty_raw_data.append(datum.replace('-', '='))
181 else:
182 pretty_raw_data.append(datum)
183 i += 1
184 parser = tableparser.GridTableParser()
185 block = statemachine.StringList(pretty_raw_data)
186 docutils_data = parser.parse(block)
187 final_data = []
188 keys = []
189 for line in docutils_data[1]:
190 for item in line:
191 keys.append(' '.join(item[3]).strip())
192 for line in docutils_data[2]:
193 final_line = {}
194 i = 0
195 for item in line:
196 value = ' '.join(item[3]).strip()
197 try:
198 value = json.loads(value)
199 except:
200 pass
201 final_line[keys[i]] = value
202 i += 1
203 final_data.append(final_line)
204 return final_data
205
206def read_table_file(file):
207 table_file = open(file, 'r')
Ales Komarekc000c152016-12-23 15:32:54 +0100208 raw_data = table_file.read().split('\\n')
Ales Komarek0e558ee2016-12-23 13:02:55 +0100209 table_file.close()
210 return raw_data
211
212parser = argparse.ArgumentParser()
213parser.add_argument('-f','--file', help='File with table data', required=True)
214parser.add_argument('-t','--type', help='Type of table (list/item)', required=True)
215args = vars(parser.parse_args())
216
217raw_data = read_table_file(args['file'])
218
219if args['type'] == 'list':
220 final_data = parse_list_table(raw_data)
221else:
222 final_data = parse_item_table(raw_data)
223
224print json.dumps(final_data)
225"""
226 writeFile file: parserFile, text: parserScript
Sergey Kolekonovba203982016-12-21 18:32:17 +0400227 tableFile = "${env.WORKSPACE}/prettytable.txt"
228 writeFile file: tableFile, text: tableStr
Ales Komarekd874d482016-12-26 10:33:29 +0100229
230 cmd = "python ${parserFile} --file '${tableFile}' --type ${type}"
231 if (path) {
Ales Komarekc6d28dd2016-12-28 12:59:38 +0100232 rawData = runVirtualenvCommand(path, cmd)
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000233 } else {
234 rawData = sh(
Ales Komarekd874d482016-12-26 10:33:29 +0100235 script: cmd,
236 returnStdout: true
237 ).trim()
238 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400239 data = loadJson(rawData)
240 echo("[Parsed table] ${data}")
241 return data
242}
243
244/**
245 * Install cookiecutter in isolated environment
246 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000247 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400248 */
249def setupCookiecutterVirtualenv(path) {
250 requirements = [
251 'cookiecutter',
Jakub Josef4df78272017-04-26 14:36:36 +0200252 'jinja2==2.8.1',
Dmitry Pyzhovb883a2d2018-12-14 16:42:52 +0300253 'PyYAML==3.12',
254 'python-gnupg==0.4.3'
Sergey Kolekonovba203982016-12-21 18:32:17 +0400255 ]
256 setupVirtualenv(path, 'python2', requirements)
257}
258
259/**
260 * Generate the cookiecutter templates with given context
261 *
Jakub Josef4e10c372017-04-26 14:13:50 +0200262 * @param template template
263 * @param context template context
264 * @param path Path where virtualenv is created (optional)
265 * @param templatePath path to cookiecutter template repo (optional)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400266 */
Jakub Josef4e10c372017-04-26 14:13:50 +0200267def buildCookiecutterTemplate(template, context, outputDir = '.', path = null, templatePath = ".") {
azvyagintsev7a123aa2019-01-09 21:38:56 +0200268 def common = new com.mirantis.mk.Common()
Tomáš Kukráldad7b462017-03-27 13:53:05 +0200269 configFile = "default_config.yaml"
Tomáš Kukrál6de85042017-04-12 17:49:05 +0200270 writeFile file: configFile, text: context
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000271 common.warningMsg('Old Cookiecutter env detected!')
272 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"
273 output = sh(returnStdout: true, script: command)
274 common.infoMsg('[Cookiecutter build] Result:' + output)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400275}
276
277/**
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400278 *
279 * @param context - context template
280 * @param contextName - context template name
281 * @param saltMasterName - hostname of Salt Master node
282 * @param virtualenv - pyvenv with CC and dep's
283 * @param templateEnvDir - root of CookieCutter
284 * @return
285 */
286def generateModel(context, contextName, saltMasterName, virtualenv, modelEnv, templateEnvDir, multiModels = true) {
Denis Egorenkofa2c6752018-10-18 15:51:45 +0400287 def common = new com.mirantis.mk.Common()
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400288 def generatedModel = multiModels ? "${modelEnv}/${contextName}" : modelEnv
289 def templateContext = readYaml text: context
290 def clusterDomain = templateContext.default_context.cluster_domain
291 def clusterName = templateContext.default_context.cluster_name
292 def outputDestination = "${generatedModel}/classes/cluster/${clusterName}"
293 def templateBaseDir = templateEnvDir
294 def templateDir = "${templateEnvDir}/dir"
295 def templateOutputDir = templateBaseDir
296 dir(templateEnvDir) {
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000297 if (fileExists(new File(templateEnvDir, 'tox.ini').toString())) {
Aleksey Zvyagintsev07b07ba2019-02-28 13:34:13 +0000298 def tempContextFile = new File(templateEnvDir, 'tempContext.yaml').toString()
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000299 writeFile file: tempContextFile, text: context
300 common.warningMsg('Generating models using context:\n')
301 print(context)
302 withEnv(["CONFIG_FILE=$tempContextFile",
Aleksey Zvyagintsev07b07ba2019-02-28 13:34:13 +0000303 "OUTPUT_DIR=${modelEnv}",
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000304 ]) {
305 print('[Cookiecutter build] Result:\n' +
306 sh(returnStdout: true, script: 'tox -ve generate_auto'))
Aleksey Zvyagintsev4c745e52019-02-21 10:30:02 +0000307 }
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000308 } else {
309 common.warningMsg("Old format: Generating model from context ${contextName}")
310 def productList = ["infra", "cicd", "kdt", "opencontrail", "kubernetes", "openstack", "oss", "stacklight", "ceph"]
311 for (product in productList) {
312 // get templateOutputDir and productDir
313 templateOutputDir = "${templateEnvDir}/output/${product}"
314 productDir = product
315 templateDir = "${templateEnvDir}/cluster_product/${productDir}"
316 // Bw for 2018.8.1 and older releases
317 if (product.startsWith("stacklight") && (!fileExists(templateDir))) {
318 common.warningMsg("Old release detected! productDir => 'stacklight2' ")
319 productDir = "stacklight2"
320 templateDir = "${templateEnvDir}/cluster_product/${productDir}"
321 }
322 // generate infra unless its explicitly disabled
323 if ((product == "infra" && templateContext.default_context.get("infra_enabled", "True").toBoolean())
324 || (templateContext.default_context.get(product + "_enabled", "False").toBoolean())) {
325
326 common.infoMsg("Generating product " + product + " from " + templateDir + " to " + templateOutputDir)
327
328 sh "rm -rf ${templateOutputDir} || true"
329 sh "mkdir -p ${templateOutputDir}"
330 sh "mkdir -p ${outputDestination}"
331
332 buildCookiecutterTemplate(templateDir, context, templateOutputDir, virtualenv, templateBaseDir)
333 sh "mv -v ${templateOutputDir}/${clusterName}/* ${outputDestination}"
334 } else {
335 common.warningMsg("Product " + product + " is disabled")
336 }
337 }
338
339 def localRepositories = templateContext.default_context.local_repositories
340 localRepositories = localRepositories ? localRepositories.toBoolean() : false
341 def offlineDeployment = templateContext.default_context.offline_deployment
342 offlineDeployment = offlineDeployment ? offlineDeployment.toBoolean() : false
343 if (localRepositories && !offlineDeployment) {
344 def mcpVersion = templateContext.default_context.mcp_version
345 def aptlyModelUrl = templateContext.default_context.local_model_url
346 def ssh = new com.mirantis.mk.Ssh()
347 dir(path: modelEnv) {
348 ssh.agentSh "git submodule add \"${aptlyModelUrl}\" \"classes/cluster/${clusterName}/cicd/aptly\""
349 if (!(mcpVersion in ["nightly", "testing", "stable"])) {
350 ssh.agentSh "cd \"classes/cluster/${clusterName}/cicd/aptly\";git fetch --tags;git checkout ${mcpVersion}"
351 }
352 }
353 }
354
355 def nodeFile = "${generatedModel}/nodes/${saltMasterName}.${clusterDomain}.yml"
356 def nodeString = """classes:
357- cluster.${clusterName}.infra.config
358parameters:
359 _param:
360 linux_system_codename: xenial
361 reclass_data_revision: master
362 linux:
363 system:
364 name: ${saltMasterName}
365 domain: ${clusterDomain}
366 """
367 sh "mkdir -p ${generatedModel}/nodes/"
368 writeFile(file: nodeFile, text: nodeString)
369 }
Denis Egorenko6c2e3ae2018-10-17 16:45:56 +0400370 }
371}
372
373/**
Sergey Kolekonovba203982016-12-21 18:32:17 +0400374 * Install jinja rendering in isolated environment
375 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000376 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400377 */
378def setupJinjaVirtualenv(path) {
379 requirements = [
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000380 'jinja2-cli',
381 'pyyaml',
Sergey Kolekonovba203982016-12-21 18:32:17 +0400382 ]
383 setupVirtualenv(path, 'python2', requirements)
384}
385
386/**
387 * Generate the Jinja templates with given context
388 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000389 * @param path Path where virtualenv is created
Sergey Kolekonovba203982016-12-21 18:32:17 +0400390 */
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000391def jinjaBuildTemplate(template, context, path = none) {
Sergey Kolekonovba203982016-12-21 18:32:17 +0400392 contextFile = "jinja_context.yml"
393 contextString = ""
394 for (parameter in context) {
395 contextString = "${contextString}${parameter.key}: ${parameter.value}\n"
396 }
397 writeFile file: contextFile, text: contextString
398 cmd = "jinja2 ${template} ${contextFile} --format=yaml"
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000399 data = sh(returnStdout: true, script: cmd)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400400 echo(data)
401 return data
402}
Oleg Grigorovbec45582017-09-12 20:29:24 +0300403
404/**
405 * Install salt-pepper in isolated environment
406 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000407 * @param path Path where virtualenv is created
408 * @param url SALT_MASTER_URL
409 * @param credentialsId Credentials to salt api
Oleg Grigorovbec45582017-09-12 20:29:24 +0300410 */
Jakub Josefc9b6d662018-02-21 16:21:03 +0100411def setupPepperVirtualenv(path, url, credentialsId) {
chnydaa0dbb252017-10-05 10:46:09 +0200412 def common = new com.mirantis.mk.Common()
413
414 // virtualenv setup
Mykyta Karpin81756c92018-03-02 13:03:26 +0200415 // pin pepper till https://mirantis.jira.com/browse/PROD-18188 is fixed
416 requirements = ['salt-pepper>=0.5.2,<0.5.4']
Jakub Josefc9b6d662018-02-21 16:21:03 +0100417 setupVirtualenv(path, 'python2', requirements, null, true, true)
chnydabcfff182017-11-29 10:24:36 +0100418
chnydaa0dbb252017-10-05 10:46:09 +0200419 // pepperrc creation
420 rcFile = "${path}/pepperrc"
421 creds = common.getPasswordCredentials(credentialsId)
422 rc = """\
423[main]
424SALTAPI_EAUTH=pam
425SALTAPI_URL=${url}
426SALTAPI_USER=${creds.username}
427SALTAPI_PASS=${creds.password.toString()}
428"""
429 writeFile file: rcFile, text: rc
430 return rcFile
Jakub Josefd067f612017-09-26 13:42:56 +0200431}
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300432
433/**
434 * Install devops in isolated environment
435 *
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000436 * @param path Path where virtualenv is created
437 * @param clean Define to true is the venv have to cleaned up before install a new one
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300438 */
Aleksey Zvyagintsevc4f66f62019-02-21 10:39:34 +0000439def setupDevOpsVenv(venv, clean = false) {
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300440 requirements = ['git+https://github.com/openstack/fuel-devops.git']
441 setupVirtualenv(venv, 'python2', requirements, null, false, clean)
442}