blob: 6e0655efeef118f4e77254a3c7ef4c9bca7d2768 [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 *
Vladislav Naumov11103862017-07-19 17:02:39 +030012 * @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 */
Jakub Josef996f4ef2017-10-24 13:20:43 +020017def 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
Mykyta Karpin1e4bfc92017-11-01 14:38:25 +020020 def virtualenv_cmd = "virtualenv ${path} --python ${python}"
Jakub Josef996f4ef2017-10-24 13:20:43 +020021 if (useSystemPackages){
22 virtualenv_cmd += " --system-site-packages"
23 }
Tomáš Kukrál69c25452017-07-27 14:59:40 +020024 if (clean) {
25 common.infoMsg("Cleaning venv directory " + path)
26 sh("rm -rf \"${path}\"")
27 }
28
29 common.infoMsg("[Python ${path}] Setup ${python} environment")
Sergey Kolekonovba203982016-12-21 18:32:17 +040030 sh(returnStdout: true, script: virtualenv_cmd)
Jakub Josef5f97d532017-11-29 18:51:41 +010031 if(!env.getEnvironment().containsKey("OFFLINE_DEPLOYMENT") || !env["OFFLINE_DEPLOYMENT"].toBoolean()){
32 try {
33 //TODO: remove wget after global env prop enforcments
Alexander Noskova5f11962017-12-05 11:25:16 +040034 runVirtualenvCommand(path, "wget -q -T 10 --spider http://google.com && pip install -U setuptools pip")
Jakub Josef5f97d532017-11-29 18:51:41 +010035 } catch(Exception e) {
36 common.warningMsg("Setuptools and pip cannot be updated, you might be offline")
37 }
Yuriy Taraday67352e92017-10-12 10:54:23 +000038 }
Vladislav Naumov11103862017-07-19 17:02:39 +030039 if (reqs_path==null) {
40 def args = ""
41 for (req in reqs) {
42 args = args + "${req}\n"
43 }
44 writeFile file: "${path}/requirements.txt", text: args
45 reqs_path = "${path}/requirements.txt"
Sergey Kolekonovba203982016-12-21 18:32:17 +040046 }
Vladislav Naumov11103862017-07-19 17:02:39 +030047 runVirtualenvCommand(path, "pip install -r ${reqs_path}")
Sergey Kolekonovba203982016-12-21 18:32:17 +040048}
49
50/**
51 * Run command in specific python virtualenv
52 *
53 * @param path Path to virtualenv
54 * @param cmd Command to be executed
55 */
56def runVirtualenvCommand(path, cmd) {
Tomáš Kukrál69c25452017-07-27 14:59:40 +020057 def common = new com.mirantis.mk.Common()
58
Jakub Josef5feeee42018-01-08 15:50:36 +010059 virtualenv_cmd = "set +x; . ${path}/bin/activate; ${cmd}"
Tomáš Kukrál69c25452017-07-27 14:59:40 +020060 common.infoMsg("[Python ${path}] Run command ${cmd}")
Sergey Kolekonovba203982016-12-21 18:32:17 +040061 output = sh(
62 returnStdout: true,
63 script: virtualenv_cmd
64 ).trim()
65 return output
66}
67
Ales Komarekd874d482016-12-26 10:33:29 +010068
69/**
70 * Install docutils in isolated environment
71 *
72 * @param path Path where virtualenv is created
73 */
74def setupDocutilsVirtualenv(path) {
75 requirements = [
76 'docutils',
77 ]
78 setupVirtualenv(path, 'python2', requirements)
79}
80
81
Sergey Kolekonovba203982016-12-21 18:32:17 +040082@NonCPS
83def loadJson(rawData) {
84 return new groovy.json.JsonSlurperClassic().parseText(rawData)
85}
86
87/**
88 * Parse content from markup-text tables to variables
89 *
90 * @param tableStr String representing the table
91 * @param mode Either list (1st row are keys) or item (key, value rows)
92 * @param format Format of the table
93 */
Ales Komarekd874d482016-12-26 10:33:29 +010094def parseTextTable(tableStr, type = 'item', format = 'rest', path = none) {
Ales Komarek0e558ee2016-12-23 13:02:55 +010095 parserFile = "${env.WORKSPACE}/textTableParser.py"
96 parserScript = """import json
97import argparse
98from docutils.parsers.rst import tableparser
99from docutils import statemachine
100
101def parse_item_table(raw_data):
102 i = 1
103 pretty_raw_data = []
104 for datum in raw_data:
105 if datum != "":
106 if datum[3] != ' ' and i > 4:
107 pretty_raw_data.append(raw_data[0])
108 if i == 3:
109 pretty_raw_data.append(datum.replace('-', '='))
110 else:
111 pretty_raw_data.append(datum)
112 i += 1
113 parser = tableparser.GridTableParser()
114 block = statemachine.StringList(pretty_raw_data)
115 docutils_data = parser.parse(block)
116 final_data = {}
117 for line in docutils_data[2]:
118 key = ' '.join(line[0][3]).strip()
119 value = ' '.join(line[1][3]).strip()
120 if key != "":
121 try:
122 value = json.loads(value)
123 except:
124 pass
125 final_data[key] = value
126 i+=1
127 return final_data
128
129def parse_list_table(raw_data):
130 i = 1
131 pretty_raw_data = []
132 for datum in raw_data:
133 if datum != "":
134 if datum[3] != ' ' and i > 4:
135 pretty_raw_data.append(raw_data[0])
136 if i == 3:
137 pretty_raw_data.append(datum.replace('-', '='))
138 else:
139 pretty_raw_data.append(datum)
140 i += 1
141 parser = tableparser.GridTableParser()
142 block = statemachine.StringList(pretty_raw_data)
143 docutils_data = parser.parse(block)
144 final_data = []
145 keys = []
146 for line in docutils_data[1]:
147 for item in line:
148 keys.append(' '.join(item[3]).strip())
149 for line in docutils_data[2]:
150 final_line = {}
151 key = ' '.join(line[0][3]).strip()
152 value = ' '.join(line[1][3]).strip()
153 if key != "":
154 try:
155 value = json.loads(value)
156 except:
157 pass
158 final_data[key] = value
159 i+=1
160 return final_data
161
162def parse_list_table(raw_data):
163 i = 1
164 pretty_raw_data = []
165 for datum in raw_data:
166 if datum != "":
167 if datum[3] != ' ' and i > 4:
168 pretty_raw_data.append(raw_data[0])
169 if i == 3:
170 pretty_raw_data.append(datum.replace('-', '='))
171 else:
172 pretty_raw_data.append(datum)
173 i += 1
174 parser = tableparser.GridTableParser()
175 block = statemachine.StringList(pretty_raw_data)
176 docutils_data = parser.parse(block)
177 final_data = []
178 keys = []
179 for line in docutils_data[1]:
180 for item in line:
181 keys.append(' '.join(item[3]).strip())
182 for line in docutils_data[2]:
183 final_line = {}
184 i = 0
185 for item in line:
186 value = ' '.join(item[3]).strip()
187 try:
188 value = json.loads(value)
189 except:
190 pass
191 final_line[keys[i]] = value
192 i += 1
193 final_data.append(final_line)
194 return final_data
195
196def read_table_file(file):
197 table_file = open(file, 'r')
Ales Komarekc000c152016-12-23 15:32:54 +0100198 raw_data = table_file.read().split('\\n')
Ales Komarek0e558ee2016-12-23 13:02:55 +0100199 table_file.close()
200 return raw_data
201
202parser = argparse.ArgumentParser()
203parser.add_argument('-f','--file', help='File with table data', required=True)
204parser.add_argument('-t','--type', help='Type of table (list/item)', required=True)
205args = vars(parser.parse_args())
206
207raw_data = read_table_file(args['file'])
208
209if args['type'] == 'list':
210 final_data = parse_list_table(raw_data)
211else:
212 final_data = parse_item_table(raw_data)
213
214print json.dumps(final_data)
215"""
216 writeFile file: parserFile, text: parserScript
Sergey Kolekonovba203982016-12-21 18:32:17 +0400217 tableFile = "${env.WORKSPACE}/prettytable.txt"
218 writeFile file: tableFile, text: tableStr
Ales Komarekd874d482016-12-26 10:33:29 +0100219
220 cmd = "python ${parserFile} --file '${tableFile}' --type ${type}"
221 if (path) {
Ales Komarekc6d28dd2016-12-28 12:59:38 +0100222 rawData = runVirtualenvCommand(path, cmd)
Ales Komarekd874d482016-12-26 10:33:29 +0100223 }
224 else {
225 rawData = sh (
226 script: cmd,
227 returnStdout: true
228 ).trim()
229 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400230 data = loadJson(rawData)
231 echo("[Parsed table] ${data}")
232 return data
233}
234
235/**
236 * Install cookiecutter in isolated environment
237 *
238 * @param path Path where virtualenv is created
239 */
240def setupCookiecutterVirtualenv(path) {
241 requirements = [
242 'cookiecutter',
Jakub Josef4df78272017-04-26 14:36:36 +0200243 'jinja2==2.8.1',
244 'PyYAML==3.12'
Sergey Kolekonovba203982016-12-21 18:32:17 +0400245 ]
246 setupVirtualenv(path, 'python2', requirements)
247}
248
249/**
250 * Generate the cookiecutter templates with given context
251 *
Jakub Josef4e10c372017-04-26 14:13:50 +0200252 * @param template template
253 * @param context template context
254 * @param path Path where virtualenv is created (optional)
255 * @param templatePath path to cookiecutter template repo (optional)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400256 */
Jakub Josef4e10c372017-04-26 14:13:50 +0200257def buildCookiecutterTemplate(template, context, outputDir = '.', path = null, templatePath = ".") {
Tomáš Kukráldad7b462017-03-27 13:53:05 +0200258 configFile = "default_config.yaml"
259 configString = "default_context:\n"
Tomáš Kukrál6de85042017-04-12 17:49:05 +0200260 writeFile file: configFile, text: context
Jakub Josef4e61cc02017-04-26 14:29:09 +0200261 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"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400262 output = sh (returnStdout: true, script: command)
263 echo("[Cookiecutter build] Output: ${output}")
264}
265
266/**
267 * Install jinja rendering in isolated environment
268 *
269 * @param path Path where virtualenv is created
270 */
271def setupJinjaVirtualenv(path) {
272 requirements = [
273 'jinja2-cli',
274 'pyyaml',
275 ]
276 setupVirtualenv(path, 'python2', requirements)
277}
278
279/**
280 * Generate the Jinja templates with given context
281 *
282 * @param path Path where virtualenv is created
283 */
284def jinjaBuildTemplate (template, context, path = none) {
285 contextFile = "jinja_context.yml"
286 contextString = ""
287 for (parameter in context) {
288 contextString = "${contextString}${parameter.key}: ${parameter.value}\n"
289 }
290 writeFile file: contextFile, text: contextString
291 cmd = "jinja2 ${template} ${contextFile} --format=yaml"
292 data = sh (returnStdout: true, script: cmd)
293 echo(data)
294 return data
295}
Oleg Grigorovbec45582017-09-12 20:29:24 +0300296
297/**
298 * Install salt-pepper in isolated environment
299 *
300 * @param path Path where virtualenv is created
chnydaa0dbb252017-10-05 10:46:09 +0200301 * @param url SALT_MASTER_URL
302 * @param credentialsId Credentials to salt api
Oleg Grigorovbec45582017-09-12 20:29:24 +0300303 */
Mykyta Karpin94916232017-11-15 10:20:59 +0200304def setupPepperVirtualenv(path, url, credentialsId, clean = false) {
chnydaa0dbb252017-10-05 10:46:09 +0200305 def common = new com.mirantis.mk.Common()
306
307 // virtualenv setup
Jakub Josef96cb63a2017-12-06 18:20:59 +0100308 requirements = ['salt-pepper==0.5.2']
Mykyta Karpin94916232017-11-15 10:20:59 +0200309 setupVirtualenv(path, 'python2', requirements, null, clean, true)
chnydabcfff182017-11-29 10:24:36 +0100310
chnydaa0dbb252017-10-05 10:46:09 +0200311 // pepperrc creation
312 rcFile = "${path}/pepperrc"
313 creds = common.getPasswordCredentials(credentialsId)
314 rc = """\
315[main]
316SALTAPI_EAUTH=pam
317SALTAPI_URL=${url}
318SALTAPI_USER=${creds.username}
319SALTAPI_PASS=${creds.password.toString()}
320"""
321 writeFile file: rcFile, text: rc
322 return rcFile
Jakub Josefd067f612017-09-26 13:42:56 +0200323}
Oleh Hryhorov44569fb2017-10-26 17:04:55 +0300324
325/**
326 * Install devops in isolated environment
327 *
328 * @param path Path where virtualenv is created
329 * @param clean Define to true is the venv have to cleaned up before install a new one
330 */
331def setupDevOpsVenv(venv, clean=false) {
332 requirements = ['git+https://github.com/openstack/fuel-devops.git']
333 setupVirtualenv(venv, 'python2', requirements, null, false, clean)
334}