blob: c1f44702c70fe1e4736fb521185fe6060755d08d [file] [log] [blame]
Sergey Kolekonovba203982016-12-21 18:32:17 +04001package com.mirantis.mk
2
3/**
4 *
5 * Openstack functions
6 *
7 */
8
9/**
Tomáš Kukrálc3964e52017-02-22 14:07:37 +010010 * Convert maps
11 *
12 */
13
14@NonCPS def entries(m) {
15 return m.collect {k, v -> [k, v]}
16}
17
18/**
Sergey Kolekonovba203982016-12-21 18:32:17 +040019 * Install OpenStack service clients in isolated environment
20 *
21 * @param path Path where virtualenv is created
22 * @param version Version of the OpenStack clients
23 */
24
Tomáš Kukrálbee0b992017-08-10 16:50:40 +020025def setupOpenstackVirtualenv(path, version = 'latest') {
iberezovskiyd4240b52017-02-20 17:18:28 +040026 def python = new com.mirantis.mk.Python()
Vasyl Saienko030fc182017-07-12 14:54:42 +030027 python.setupDocutilsVirtualenv(path)
Sergey Kolekonovba203982016-12-21 18:32:17 +040028
29 def openstack_kilo_packages = [
Jakub Josef268bc842017-10-10 14:36:17 +020030 //XXX: hack to fix https://bugs.launchpad.net/ubuntu/+source/python-pip/+bug/1635463
31 'cliff==2.8',
Sergey Kolekonovba203982016-12-21 18:32:17 +040032 'python-cinderclient>=1.3.1,<1.4.0',
33 'python-glanceclient>=0.19.0,<0.20.0',
34 'python-heatclient>=0.6.0,<0.7.0',
35 'python-keystoneclient>=1.6.0,<1.7.0',
36 'python-neutronclient>=2.2.6,<2.3.0',
37 'python-novaclient>=2.19.0,<2.20.0',
38 'python-swiftclient>=2.5.0,<2.6.0',
Jakub Josefbd927322017-05-30 13:20:27 +000039 'python-openstackclient>=1.7.0,<1.8.0',
Sergey Kolekonovba203982016-12-21 18:32:17 +040040 'oslo.config>=2.2.0,<2.3.0',
41 'oslo.i18n>=2.3.0,<2.4.0',
42 'oslo.serialization>=1.8.0,<1.9.0',
43 'oslo.utils>=1.4.0,<1.5.0',
Jakub Josef60280212017-08-10 19:01:19 +020044 'docutils'
Sergey Kolekonovba203982016-12-21 18:32:17 +040045 ]
46
Tomáš Kukrál381a8c92017-06-21 09:01:52 +020047 def openstack_latest_packages = [
Jakub Josef268bc842017-10-10 14:36:17 +020048 //XXX: hack to fix https://bugs.launchpad.net/ubuntu/+source/python-pip/+bug/1635463
49 'cliff==2.8',
Vasyl Saienko36a019d2018-05-30 09:51:18 +030050 // NOTE(vsaienko): cmd2 is dependency for cliff, since we don't using upper-contstraints
51 // we have to pin cmd2 < 0.9.0 as later versions are not compatible with python2.
52 // TODO(vsaienko): use upper-constraints here, as in requirements we set only lowest library
53 // versions.
54 'cmd2<0.9.0;python_version=="2.7"',
55 'cmd2>=0.9.1;python_version=="3.4"',
56 'cmd2>=0.9.1;python_version=="3.5"',
Tomáš Kukrál381a8c92017-06-21 09:01:52 +020057 'python-openstackclient',
58 'python-heatclient',
Jakub Josef60280212017-08-10 19:01:19 +020059 'docutils'
Tomáš Kukrálc6a94c62017-06-19 14:44:24 +020060 ]
Sergey Kolekonovba203982016-12-21 18:32:17 +040061
Tomáš Kukrálc6a94c62017-06-19 14:44:24 +020062 if (version == 'kilo') {
Sergey Kolekonovba203982016-12-21 18:32:17 +040063 requirements = openstack_kilo_packages
Tomáš Kukrálc6a94c62017-06-19 14:44:24 +020064 } else if (version == 'liberty') {
Sergey Kolekonovba203982016-12-21 18:32:17 +040065 requirements = openstack_kilo_packages
Tomáš Kukrálc6a94c62017-06-19 14:44:24 +020066 } else if (version == 'mitaka') {
Sergey Kolekonovba203982016-12-21 18:32:17 +040067 requirements = openstack_kilo_packages
Tomáš Kukrál381a8c92017-06-21 09:01:52 +020068 } else {
Sergey Kolekonovba203982016-12-21 18:32:17 +040069 requirements = openstack_latest_packages
70 }
Tomáš Kukrálbee0b992017-08-10 16:50:40 +020071 python.setupVirtualenv(path, 'python2', requirements, null, true)
Sergey Kolekonovba203982016-12-21 18:32:17 +040072}
73
74/**
75 * create connection to OpenStack API endpoint
76 *
Jakub Josef6c963762018-01-18 16:02:22 +010077 * @param path Path to created venv
Sergey Kolekonovba203982016-12-21 18:32:17 +040078 * @param url OpenStack API endpoint address
79 * @param credentialsId Credentials to the OpenStack API
80 * @param project OpenStack project to connect to
81 */
Jakub Josef6c963762018-01-18 16:02:22 +010082def createOpenstackEnv(path, url, credentialsId, project, project_domain="default",
Tomáš Kukrál381a8c92017-06-21 09:01:52 +020083 project_id="", user_domain="default", api_ver="2", cacert="/etc/ssl/certs/ca-certificates.crt") {
iberezovskiyd4240b52017-02-20 17:18:28 +040084 def common = new com.mirantis.mk.Common()
Jakub Josef6c963762018-01-18 16:02:22 +010085 rcFile = "${path}/keystonerc"
Sergey Kolekonovba203982016-12-21 18:32:17 +040086 creds = common.getPasswordCredentials(credentialsId)
Alexander Tivelkovf89a1882017-01-11 13:29:35 +030087 rc = """set +x
88export OS_USERNAME=${creds.username}
Ales Komarek0e558ee2016-12-23 13:02:55 +010089export OS_PASSWORD=${creds.password.toString()}
90export OS_TENANT_NAME=${project}
91export OS_AUTH_URL=${url}
92export OS_AUTH_STRATEGY=keystone
kairat_kushaev0a26bf72017-05-18 13:20:09 +040093export OS_PROJECT_NAME=${project}
Jakub Josefbd927322017-05-30 13:20:27 +000094export OS_PROJECT_ID=${project_id}
kairat_kushaev0a26bf72017-05-18 13:20:09 +040095export OS_PROJECT_DOMAIN_ID=${project_domain}
Jakub Josefbd927322017-05-30 13:20:27 +000096export OS_USER_DOMAIN_NAME=${user_domain}
Kirill Mashchenko234708f2017-07-20 17:00:01 +030097export OS_IDENTITY_API_VERSION=${api_ver}
Tomáš Kukrál381a8c92017-06-21 09:01:52 +020098export OS_CACERT=${cacert}
Alexander Tivelkovf89a1882017-01-11 13:29:35 +030099set -x
Ales Komarek0e558ee2016-12-23 13:02:55 +0100100"""
101 writeFile file: rcFile, text: rc
102 return rcFile
Sergey Kolekonovba203982016-12-21 18:32:17 +0400103}
104
105/**
106 * Run command with OpenStack env params and optional python env
107 *
108 * @param cmd Command to be executed
109 * @param env Environmental parameters with endpoint credentials
110 * @param path Optional path to virtualenv with specific clients
111 */
112def runOpenstackCommand(cmd, venv, path = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400113 def python = new com.mirantis.mk.Python()
Sergey Kolekonovba203982016-12-21 18:32:17 +0400114 openstackCmd = ". ${venv}; ${cmd}"
115 if (path) {
116 output = python.runVirtualenvCommand(path, openstackCmd)
117 }
118 else {
119 echo("[Command]: ${openstackCmd}")
120 output = sh (
121 script: openstackCmd,
122 returnStdout: true
123 ).trim()
124 }
125 return output
126}
127
128/**
129 * Get OpenStack Keystone token for current credentials
130 *
131 * @param env Connection parameters for OpenStack API endpoint
132 * @param path Optional path to the custom virtualenv
133 */
134def getKeystoneToken(client, path = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400135 def python = new com.mirantis.mk.Python()
Jakub Josefbd927322017-05-30 13:20:27 +0000136 cmd = "openstack token issue"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400137 outputTable = runOpenstackCommand(cmd, client, path)
Ales Komareke11e8792016-12-28 09:42:25 +0100138 output = python.parseTextTable(outputTable, 'item', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400139 return output
140}
141
142/**
Ales Komarek51b7b152017-06-27 11:14:50 +0200143 * Create OpenStack environment file
Sergey Kolekonovba203982016-12-21 18:32:17 +0400144 *
145 * @param env Connection parameters for OpenStack API endpoint
146 * @param path Optional path to the custom virtualenv
147 */
148def createHeatEnv(file, environment = [], original_file = null) {
149 if (original_file) {
150 envString = readFile file: original_file
Tomáš Kukrál03029442017-02-21 17:14:29 +0100151 } else {
Sergey Kolekonovba203982016-12-21 18:32:17 +0400152 envString = "parameters:\n"
153 }
Tomáš Kukrál03029442017-02-21 17:14:29 +0100154
Tomáš Kukrálc3964e52017-02-22 14:07:37 +0100155 p = entries(environment)
Tomáš Kukrálb1fe9642017-02-22 11:21:17 +0100156 for (int i = 0; i < p.size(); i++) {
157 envString = "${envString} ${p.get(i)[0]}: ${p.get(i)[1]}\n"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400158 }
Tomáš Kukrál03029442017-02-21 17:14:29 +0100159
Tomáš Kukrále19ddea2017-02-21 11:09:40 +0100160 echo("writing to env file:\n${envString}")
Sergey Kolekonovba203982016-12-21 18:32:17 +0400161 writeFile file: file, text: envString
162}
163
164/**
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200165 * Create new OpenStack Heat stack. Will wait for action to be complited in
166 * specified amount of time (by default 120min)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400167 *
168 * @param env Connection parameters for OpenStack API endpoint
169 * @param template HOT template for the new Heat stack
170 * @param environment Environmentale parameters of the new Heat stack
171 * @param name Name of the new Heat stack
172 * @param path Optional path to the custom virtualenv
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200173 * @param timeout Optional number in minutes to wait for stack action is applied.
Sergey Kolekonovba203982016-12-21 18:32:17 +0400174 */
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200175def createHeatStack(client, name, template, params = [], environment = null, path = null, action="create", timeout=120) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400176 def python = new com.mirantis.mk.Python()
Jakub Josef0a898762017-08-11 16:27:44 +0200177 def templateFile = "${env.WORKSPACE}/template/template/${template}.hot"
178 def envFile
179 def envSource
Sergey Kolekonovba203982016-12-21 18:32:17 +0400180 if (environment) {
Tomáš Kukrála1152742017-08-22 16:21:50 +0200181 envFile = "${env.WORKSPACE}/template/env/${name}.env"
182 if (environment.contains("/")) {
183 //init() returns all elements but the last in a collection.
184 def envPath = environment.tokenize("/").init().join("/")
185 if (envPath) {
186 envFile = "${env.WORKSPACE}/template/env/${envPath}/${name}.env"
187 }
Ales Komarek51b7b152017-06-27 11:14:50 +0200188 }
Tomáš Kukrála1152742017-08-22 16:21:50 +0200189 envSource = "${env.WORKSPACE}/template/env/${environment}.env"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400190 createHeatEnv(envFile, params, envSource)
Jakub Josef9a59aeb2017-08-11 15:50:20 +0200191 } else {
Sergey Kolekonovba203982016-12-21 18:32:17 +0400192 envFile = "${env.WORKSPACE}/template/${name}.env"
193 createHeatEnv(envFile, params)
194 }
Tomáš Kukrála1152742017-08-22 16:21:50 +0200195
Mykyta Karpincf44f812017-08-28 14:45:21 +0300196 def cmd
Vasyl Saienkob91df802019-01-23 17:22:57 +0200197 def cmd_args = "-t ${templateFile} -e ${envFile} --timeout ${timeout} --wait ${name}"
Mykyta Karpincf44f812017-08-28 14:45:21 +0300198
Tomáš Kukrála1152742017-08-22 16:21:50 +0200199 if (action == "create") {
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200200 cmd = "openstack stack create ${cmd_args}"
Tomáš Kukrála1152742017-08-22 16:21:50 +0200201 } else {
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200202 cmd = "openstack stack update ${cmd_args}"
Tomáš Kukrála1152742017-08-22 16:21:50 +0200203 }
204
Sergey Kolekonovba203982016-12-21 18:32:17 +0400205 dir("${env.WORKSPACE}/template/template") {
206 outputTable = runOpenstackCommand(cmd, client, path)
207 }
Tomáš Kukrála1152742017-08-22 16:21:50 +0200208
Ales Komareke11e8792016-12-28 09:42:25 +0100209 output = python.parseTextTable(outputTable, 'item', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400210}
211
212/**
Jakub Josefdb4baf22017-05-10 15:16:09 +0200213 * Returns list of stacks for stack name filter
214 *
215 * @param client Connection parameters for OpenStack API endpoint
216 * @param filter Stack name filter
217 * @param path Optional path to the custom virtualenv
218 */
219def getStacksForNameContains(client, filter, path = null){
Jakub Josef6465fca2017-05-10 16:09:20 +0200220 cmd = 'heat stack-list | awk \'NR>3 {print $4}\' | sed \'$ d\' | grep ' + filter + '|| true'
Jakub Josefdb4baf22017-05-10 15:16:09 +0200221 return runOpenstackCommand(cmd, client, path).trim().tokenize("\n")
222}
223
224
225/**
Jakub Josef5e238a22017-04-19 16:35:15 +0200226 * Get list of stack names with given stack status
227 *
Jakub Josefdb4baf22017-05-10 15:16:09 +0200228 * @param client Connection parameters for OpenStack API endpoint
Jakub Josef5e238a22017-04-19 16:35:15 +0200229 * @param status Stack status
230 * @param path Optional path to the custom virtualenv
231 */
232 def getStacksWithStatus(client, status, path = null) {
233 cmd = 'heat stack-list -f stack_status='+status+' | awk \'NR>3 {print $4}\' | sed \'$ d\''
234 return runOpenstackCommand(cmd, client, path).trim().tokenize("\n")
235 }
236
237/**
Sergey Kolekonovba203982016-12-21 18:32:17 +0400238 * Get life cycle status for existing OpenStack Heat stack
239 *
240 * @param env Connection parameters for OpenStack API endpoint
241 * @param name Name of the managed Heat stack instance
242 * @param path Optional path to the custom virtualenv
243 */
244def getHeatStackStatus(client, name, path = null) {
245 cmd = 'heat stack-list | awk -v stack='+name+' \'{if ($4==stack) print $6}\''
246 return runOpenstackCommand(cmd, client, path)
247}
248
249/**
250 * Get info about existing OpenStack Heat stack
251 *
252 * @param env Connection parameters for OpenStack API endpoint
253 * @param name Name of the managed Heat stack instance
254 * @param path Optional path to the custom virtualenv
255 */
256def getHeatStackInfo(env, name, path = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400257 def python = new com.mirantis.mk.Python()
Sergey Kolekonovba203982016-12-21 18:32:17 +0400258 cmd = "heat stack-show ${name}"
259 outputTable = runOpenstackCommand(cmd, env, path)
Ales Komareke11e8792016-12-28 09:42:25 +0100260 output = python.parseTextTable(outputTable, 'item', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400261 return output
262}
263
264/**
265 * Get existing OpenStack Heat stack output parameter
266 *
267 * @param env Connection parameters for OpenStack API endpoint
268 * @param name Name of the managed Heat stack
269 * @param parameter Name of the output parameter
270 * @param path Optional path to the custom virtualenv
271 */
272def getHeatStackOutputParam(env, name, outputParam, path = null) {
Vasyl Saienkoea4b2812017-07-10 10:36:03 +0000273 cmd = "heat output-show ${name} ${outputParam}"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400274 output = runOpenstackCommand(cmd, env, path)
Ales Komarekeedc2222017-01-03 10:10:03 +0100275 echo("${cmd}: ${output}")
Vasyl Saienko2a1c2de2017-07-11 11:41:53 +0300276 // NOTE(vsaienko) heatclient 1.5.1 returns output in "", while later
277 // versions returns string without "".
278 // TODO Use openstack 'stack output show' when all jobs using at least Mitaka heatclient
279 return "${output}".replaceAll('"', '')
Sergey Kolekonovba203982016-12-21 18:32:17 +0400280}
281
282/**
283 * List all resources from existing OpenStack Heat stack
284 *
285 * @param env Connection parameters for OpenStack API endpoint
286 * @param name Name of the managed Heat stack instance
287 * @param path Optional path to the custom virtualenv
Mykyta Karpin72306362018-02-08 16:40:43 +0200288 * @param depth Optional depth of stack for listing resources,
289 * 0 - do not list nested resources
Sergey Kolekonovba203982016-12-21 18:32:17 +0400290 */
Mykyta Karpin72306362018-02-08 16:40:43 +0200291def getHeatStackResources(env, name, path = null, depth = 0) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400292 def python = new com.mirantis.mk.Python()
Mykyta Karpin72306362018-02-08 16:40:43 +0200293 cmd = "heat resource-list --nested-depth ${depth} ${name}"
Sergey Kolekonovba203982016-12-21 18:32:17 +0400294 outputTable = runOpenstackCommand(cmd, env, path)
Ales Komareke11e8792016-12-28 09:42:25 +0100295 output = python.parseTextTable(outputTable, 'list', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400296 return output
297}
298
299/**
300 * Get info about resource from existing OpenStack Heat stack
301 *
302 * @param env Connection parameters for OpenStack API endpoint
303 * @param name Name of the managed Heat stack instance
304 * @param path Optional path to the custom virtualenv
305 */
306def getHeatStackResourceInfo(env, name, resource, path = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400307 def python = new com.mirantis.mk.Python()
Sergey Kolekonovba203982016-12-21 18:32:17 +0400308 cmd = "heat resource-show ${name} ${resource}"
309 outputTable = runOpenstackCommand(cmd, env, path)
Ales Komareke11e8792016-12-28 09:42:25 +0100310 output = python.parseTextTable(outputTable, 'item', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400311 return output
312}
313
314/**
315 * Update existing OpenStack Heat stack
316 *
317 * @param env Connection parameters for OpenStack API endpoint
318 * @param name Name of the managed Heat stack instance
319 * @param path Optional path to the custom virtualenv
320 */
321def updateHeatStack(env, name, path = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +0400322 def python = new com.mirantis.mk.Python()
Sergey Kolekonovba203982016-12-21 18:32:17 +0400323 cmd = "heat stack-update ${name}"
324 outputTable = runOpenstackCommand(cmd, env, path)
Ales Komareke11e8792016-12-28 09:42:25 +0100325 output = python.parseTextTable(outputTable, 'item', 'prettytable', path)
Sergey Kolekonovba203982016-12-21 18:32:17 +0400326 return output
327}
328
329/**
330 * Delete existing OpenStack Heat stack
331 *
332 * @param env Connection parameters for OpenStack API endpoint
333 * @param name Name of the managed Heat stack instance
334 * @param path Optional path to the custom virtualenv
335 */
336def deleteHeatStack(env, name, path = null) {
337 cmd = "heat stack-delete ${name}"
338 outputTable = runOpenstackCommand(cmd, env, path)
339}
340
341/**
Mykyta Karpin72306362018-02-08 16:40:43 +0200342 * Return hashmap of hashes server_id:server_name of servers from OpenStack Heat stack
Sergey Kolekonovba203982016-12-21 18:32:17 +0400343 *
344 * @param env Connection parameters for OpenStack API endpoint
345 * @param name Name of the managed Heat stack instance
346 * @param path Optional path to the custom virtualenv
347 */
348def getHeatStackServers(env, name, path = null) {
Mykyta Karpin72306362018-02-08 16:40:43 +0200349 // set depth to 1000 to ensure all nested resources are shown
350 resources = getHeatStackResources(env, name, path, 1000)
351 servers = [:]
Sergey Kolekonovba203982016-12-21 18:32:17 +0400352 for (resource in resources) {
353 if (resource.resource_type == 'OS::Nova::Server') {
Mykyta Karpin67978112018-02-22 11:16:45 +0200354 server = getHeatStackResourceInfo(env, resource.stack_name, resource.resource_name, path)
Mykyta Karpin72306362018-02-08 16:40:43 +0200355 servers[server.attributes.id] = server.attributes.name
Sergey Kolekonovba203982016-12-21 18:32:17 +0400356 }
357 }
358 echo("[Stack ${name}] Servers: ${servers}")
359 return servers
360}
Jiri Broulikf8f96942018-02-15 10:03:42 +0100361
362/**
Mykyta Karpin8306a9d2018-07-27 11:34:10 +0300363 * Delete nova key pair
364 *
365 * @param env Connection parameters for OpenStack API endpoint
366 * @param name Name of the key pair to delete
367 * @param path Optional path to the custom virtualenv
368 */
369def deleteKeyPair(env, name, path = null) {
370 def common = new com.mirantis.mk.Common()
371 common.infoMsg("Removing key pair ${name}")
372 def cmd = "openstack keypair delete ${name}"
373 runOpenstackCommand(cmd, env, path)
374}
375
376/**
377 * Get nova key pair
378 *
379 * @param env Connection parameters for OpenStack API endpoint
380 * @param name Name of the key pair to show
381 * @param path Optional path to the custom virtualenv
382 */
383
384def getKeyPair(env, name, path = null) {
385 def common = new com.mirantis.mk.Common()
386 def cmd = "openstack keypair show ${name}"
387 def outputTable
388 try {
389 outputTable = runOpenstackCommand(cmd, env, path)
390 } catch (Exception e) {
391 common.infoMsg("Key pair ${name} not found")
392 }
393 return outputTable
394}
395
396/**
Jiri Broulikf8f96942018-02-15 10:03:42 +0100397 * Stops all services that contain specific string (for example nova,heat, etc.)
398 * @param env Salt Connection object or pepperEnv
399 * @param probe single node on which to list service names
400 * @param target all targeted nodes
401 * @param services lists of type of services to be stopped
Jiri Broulikf6daac62018-03-08 13:17:53 +0100402 * @param confirm enable/disable manual service stop confirmation
Jiri Broulikf8f96942018-02-15 10:03:42 +0100403 * @return output of salt commands
404 */
Jiri Broulik27e83052018-03-06 11:37:29 +0100405def stopServices(env, probe, target, services=[], confirm=false) {
Jiri Broulikf8f96942018-02-15 10:03:42 +0100406 def salt = new com.mirantis.mk.Salt()
Jiri Broulikf6daac62018-03-08 13:17:53 +0100407 def common = new com.mirantis.mk.Common()
Jiri Broulikf8f96942018-02-15 10:03:42 +0100408 for (s in services) {
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400409 def outputServicesStr = salt.getReturnValues(salt.cmdRun(env, probe, "service --status-all | grep ${s} | awk \'{print \$4}\'"))
Jiri Broulikf6daac62018-03-08 13:17:53 +0100410 def servicesList = outputServicesStr.tokenize("\n").init()
Jiri Broulik27e83052018-03-06 11:37:29 +0100411 if (confirm) {
Jiri Broulikf6daac62018-03-08 13:17:53 +0100412 if (servicesList) {
413 try {
414 input message: "Click PROCEED to stop ${servicesList}. Otherwise click ABORT to skip stopping them."
415 for (name in servicesList) {
416 if (!name.contains('Salt command')) {
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400417 salt.runSaltProcessStep(env, target, 'service.stop', ["${name}"])
Jiri Broulikf6daac62018-03-08 13:17:53 +0100418 }
419 }
420 } catch (Exception er) {
421 common.infoMsg("skipping stopping ${servicesList} services")
422 }
423 }
424 } else {
425 if (servicesList) {
Jiri Broulik27e83052018-03-06 11:37:29 +0100426 for (name in servicesList) {
427 if (!name.contains('Salt command')) {
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400428 salt.runSaltProcessStep(env, target, 'service.stop', ["${name}"])
Jiri Broulik27e83052018-03-06 11:37:29 +0100429 }
430 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100431 }
432 }
433 }
434}
435
436/**
Vasyl Saienko4129e102018-09-03 10:15:52 +0300437 * Return intersection of globally installed services and those are
438 * defined on specific target according to theirs priorities.
439 *
440 * @param env Salt Connection object or env
441 * @param target The target node to get list of apps for.
442**/
443def getOpenStackUpgradeServices(env, target){
444 def salt = new com.mirantis.mk.Salt()
445 def common = new com.mirantis.mk.Common()
446
447 def global_apps = salt.getConfig(env, 'I@salt:master:enabled:true', 'orchestration.upgrade.applications')
448 def node_apps = salt.getPillar(env, target, '__reclass__:applications')['return'][0].values()[0]
449 def node_sorted_apps = []
450 if ( !global_apps['return'][0].values()[0].isEmpty() ) {
451 Map<String,Integer> _sorted_apps = [:]
452 for (k in global_apps['return'][0].values()[0].keySet()) {
453 if (k in node_apps) {
454 _sorted_apps[k] = global_apps['return'][0].values()[0][k].values()[0].toInteger()
455 }
456 }
457 node_sorted_apps = common.SortMapByValueAsc(_sorted_apps).keySet()
458 common.infoMsg("Applications are placed in following order:"+node_sorted_apps)
459 } else {
460 common.errorMsg("No applications found.")
461 }
462
463 return node_sorted_apps
464}
465
466
467/**
468 * Run specified upgrade phase for all services on given node.
469 *
470 * @param env Salt Connection object or env
471 * @param target The target node to run states on.
472 * @param phase The phase name to run.
473**/
474def runOpenStackUpgradePhase(env, target, phase){
475 def salt = new com.mirantis.mk.Salt()
476 def common = new com.mirantis.mk.Common()
477
478 services = getOpenStackUpgradeServices(env, target)
479 def st
480
481 for (service in services){
482 st = "${service}.upgrade.${phase}".trim()
483 common.infoMsg("Running ${phase} for service ${st} on ${target}")
484 salt.enforceState(env, target, st)
485 }
486}
487
488
489/**
490 * Run OpenStack states on specified node.
491 *
492 * @param env Salt Connection object or env
493 * @param target The target node to run states on.
494**/
495def applyOpenstackAppsStates(env, target){
496 def salt = new com.mirantis.mk.Salt()
497 def common = new com.mirantis.mk.Common()
498
499 services = getOpenStackUpgradeServices(env, target)
500 def st
501
502 for (service in services){
503 st = "${service}".trim()
504 common.infoMsg("Running ${st} on ${target}")
505 salt.enforceState(env, target, st)
506 }
507}
508
509/**
Martin Polreich65864b02018-12-05 10:42:50 +0100510 * Verifies Galera database
511 *
512 * This function checks for Galera master, tests connection and if reachable, it obtains the result
513 * of Salt mysql.status function. The result is then parsed, validated and outputed to the user.
514 *
515 * @param env Salt Connection object or pepperEnv
516 * @return resultCode int values used to determine exit status in the calling function
517 */
Martin Polreich9a5d6682018-12-21 16:42:06 +0100518def verifyGaleraStatus(env, slave=false) {
Martin Polreich65864b02018-12-05 10:42:50 +0100519 def salt = new com.mirantis.mk.Salt()
520 def common = new com.mirantis.mk.Common()
521 def out = ""
522 def status = "unknown"
Martin Polreich9a5d6682018-12-21 16:42:06 +0100523 def testNode = ""
524 if (!slave) {
525 try {
526 galeraMaster = salt.getMinions(env, "I@galera:master")
527 common.infoMsg("Current Galera master is: ${galeraMaster}")
528 salt.minionsReachable(env, "I@salt:master", "I@galera:master")
529 testNode = "I@galera:master"
530 } catch (Exception e) {
531 common.errorMsg('Galera master is not reachable.')
532 return 128
533 }
534 } else {
535 try {
536 galeraMinions = salt.getMinions(env, "I@galera:slave")
537 common.infoMsg("Testing Galera slave minions: ${galeraMinions}")
538 } catch (Exception e) {
539 common.errorMsg("Cannot obtain Galera slave minions list.")
540 return 129
541 }
542 for (minion in galeraMinions) {
543 try {
544 salt.minionsReachable(env, "I@salt:master", minion)
545 testNode = minion
546 break
547 } catch (Exception e) {
548 common.warningMsg("Slave '${minion}' is not reachable.")
549 }
550 }
551 }
552 if (!testNode) {
553 common.errorMsg("No Galera slave was reachable.")
554 return 130
Martin Polreich65864b02018-12-05 10:42:50 +0100555 }
556 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100557 out = salt.cmdRun(env, "I@salt:master", "salt -C '${testNode}' mysql.status")
Martin Polreich65864b02018-12-05 10:42:50 +0100558 } catch (Exception e) {
559 common.errorMsg('Could not determine mysql status.')
560 return 256
561 }
562 if (out) {
563 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100564 status = validateAndPrintGaleraStatusReport(env, out, testNode)
Martin Polreich65864b02018-12-05 10:42:50 +0100565 } catch (Exception e) {
566 common.errorMsg('Could not parse the mysql status output. Check it manually.')
567 return 1
568 }
569 } else {
570 common.errorMsg("Mysql status response unrecognized or is empty. Response: ${out}")
571 return 1024
572 }
573 if (status == "OK") {
574 common.infoMsg("No errors found - MySQL status is ${status}.")
575 return 0
576 } else if (status == "unknown") {
577 common.warningMsg('MySQL status cannot be detemined')
578 return 1
579 } else {
580 common.errorMsg("Errors found.")
581 return 2
582 }
583}
584
585/** Validates and prints result of verifyGaleraStatus function
586@param env Salt Connection object or pepperEnv
587@param out Output of the mysql.status Salt function
588@return status "OK", "ERROR" or "uknown" depending on result of validation
589*/
590
Martin Polreich9a5d6682018-12-21 16:42:06 +0100591def validateAndPrintGaleraStatusReport(env, out, minion) {
Martin Polreich65864b02018-12-05 10:42:50 +0100592 def salt = new com.mirantis.mk.Salt()
593 def common = new com.mirantis.mk.Common()
Martin Polreich9a5d6682018-12-21 16:42:06 +0100594 if (minion == "I@galera:master") {
595 role = "master"
596 } else {
597 role = "slave"
598 }
Martin Polreich94321422019-01-17 16:20:24 +0100599 sizeOut = salt.getReturnValues(salt.getPillar(env, minion, "galera:${role}:members"))
Martin Polreich65864b02018-12-05 10:42:50 +0100600 expected_cluster_size = sizeOut.size()
601 outlist = out['return'][0]
602 resultString = outlist.get(outlist.keySet()[0]).replace("\n ", " ").replace(" ", "").replace("Salt command execution success", "").replace("----------", "").replace(": \n", ": no value\n")
603 resultYaml = readYaml text: resultString
604 parameters = [
605 wsrep_cluster_status: [title: 'Cluster status', expectedValues: ['Primary'], description: ''],
606 wsrep_cluster_size: [title: 'Current cluster size', expectedValues: [expected_cluster_size], description: ''],
Martin Polreich9a5d6682018-12-21 16:42:06 +0100607 wsrep_ready: [title: 'Node status', expectedValues: ['ON', true], description: ''],
608 wsrep_local_state_comment: [title: 'Node status comment', expectedValues: ['Joining', 'Waiting on SST', 'Joined', 'Synced', 'Donor'], description: ''],
609 wsrep_connected: [title: 'Node connectivity', expectedValues: ['ON', true], description: ''],
Martin Polreich65864b02018-12-05 10:42:50 +0100610 wsrep_local_recv_queue_avg: [title: 'Average size of local reveived queue', expectedThreshold: [warn: 0.5, error: 1.0], description: '(Value above 0 means that the node cannot apply write-sets as fast as it receives them, which can lead to replication throttling)'],
611 wsrep_local_send_queue_avg: [title: 'Average size of local send queue', expectedThreshold: [warn: 0.5, error: 1.0], description: '(Value above 0 indicate replication throttling or network throughput issues, such as a bottleneck on the network link.)']
612 ]
Martin Polreich65864b02018-12-05 10:42:50 +0100613 for (key in parameters.keySet()) {
614 value = resultYaml[key]
615 parameters.get(key) << [actualValue: value]
616 }
617 for (key in parameters.keySet()) {
618 param = parameters.get(key)
619 if (key == 'wsrep_local_recv_queue_avg' || key == 'wsrep_local_send_queue_avg') {
620 if (param.get('actualValue') > param.get('expectedThreshold').get('error')) {
621 param << [match: 'error']
622 } else if (param.get('actualValue') > param.get('expectedThreshold').get('warn')) {
623 param << [match: 'warn']
624 } else {
625 param << [match: 'ok']
626 }
627 } else {
628 for (expValue in param.get('expectedValues')) {
629 if (expValue == param.get('actualValue')) {
630 param << [match: 'ok']
631 break
632 } else {
633 param << [match: 'error']
634 }
635 }
636 }
637 }
638 cluster_info_report = []
639 cluster_warning_report = []
640 cluster_error_report = []
641 for (key in parameters.keySet()) {
642 param = parameters.get(key)
643 if (param.containsKey('expectedThreshold')) {
644 expValues = "below ${param.get('expectedThreshold').get('warn')}"
645 } else {
646 if (param.get('expectedValues').size() > 1) {
647 expValues = param.get('expectedValues').join(' or ')
648 } else {
649 expValues = param.get('expectedValues')[0]
650 }
651 }
652 reportString = "${param.title}: ${param.actualValue} (Expected: ${expValues}) ${param.description}"
653 if (param.get('match').equals('ok')) {
654 cluster_info_report.add("[OK ] ${reportString}")
655 } else if (param.get('match').equals('warn')) {
656 cluster_warning_report.add("[WARNING] ${reportString}")
657 } else {
658 cluster_error_report.add("[ ERROR] ${reportString})")
659 }
660 }
661 common.infoMsg("CLUSTER STATUS REPORT: ${cluster_info_report.size()} expected values, ${cluster_warning_report.size()} warnings and ${cluster_error_report.size()} error found:")
662 if (cluster_info_report.size() > 0) {
663 common.infoMsg(cluster_info_report.join('\n'))
664 }
665 if (cluster_warning_report.size() > 0) {
666 common.warningMsg(cluster_warning_report.join('\n'))
667 }
668 if (cluster_error_report.size() > 0) {
669 common.errorMsg(cluster_error_report.join('\n'))
670 return "ERROR"
671 } else {
672 return "OK"
673 }
674}
675
Martin Polreich9a5d6682018-12-21 16:42:06 +0100676def getGaleraLastShutdownNode(env) {
677 def salt = new com.mirantis.mk.Salt()
678 def common = new com.mirantis.mk.Common()
679 members = ''
680 lastNode = [ip: '', seqno: -2]
681 try {
682 members = salt.getReturnValues(salt.getPillar(env, "I@galera:master", "galera:master:members"))
683 } catch (Exception er) {
684 common.errorMsg('Could not retrieve members list')
685 return 'I@galera:master'
686 }
687 if (members) {
688 for (member in members) {
689 try {
690 salt.minionsReachable(env, 'I@salt:master', "S@${member.host}")
691 out = salt.getReturnValues(salt.cmdRun(env, "S@${member.host}", 'cat /var/lib/mysql/grastate.dat | grep "seqno" | cut -d ":" -f2', true, null, false))
692 seqno = out.tokenize('\n')[0].trim()
693 if (seqno.isNumber()) {
694 seqno = seqno.toInteger()
695 } else {
696 seqno = -2
697 }
698 highestSeqno = lastNode.get('seqno')
699 if (seqno > highestSeqno) {
700 lastNode << [ip: "${member.host}", seqno: seqno]
701 }
702 } catch (Exception er) {
703 common.warningMsg("Could not determine 'seqno' value for node ${member.host} ")
704 }
705 }
706 }
707 if (lastNode.get('ip') != '') {
708 return "S@${lastNode.ip}"
709 } else {
710 return "I@galera:master"
711 }
712}
713
Martin Polreich65864b02018-12-05 10:42:50 +0100714/**
Jiri Broulikf8f96942018-02-15 10:03:42 +0100715 * Restores Galera database
716 * @param env Salt Connection object or pepperEnv
717 * @return output of salt commands
718 */
719def restoreGaleraDb(env) {
720 def salt = new com.mirantis.mk.Salt()
721 def common = new com.mirantis.mk.Common()
722 try {
723 salt.runSaltProcessStep(env, 'I@galera:slave', 'service.stop', ['mysql'])
724 } catch (Exception er) {
725 common.warningMsg('Mysql service already stopped')
726 }
727 try {
728 salt.runSaltProcessStep(env, 'I@galera:master', 'service.stop', ['mysql'])
729 } catch (Exception er) {
730 common.warningMsg('Mysql service already stopped')
731 }
Martin Polreich9a5d6682018-12-21 16:42:06 +0100732 lastNodeTarget = getGaleraLastShutdownNode(env)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100733 try {
734 salt.cmdRun(env, 'I@galera:slave', "rm /var/lib/mysql/ib_logfile*")
735 } catch (Exception er) {
736 common.warningMsg('Files are not present')
737 }
738 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100739 salt.cmdRun(env, 'I@galera:slave', "rm /var/lib/mysql/grastate.dat")
740 } catch (Exception er) {
741 common.warningMsg('Files are not present')
742 }
743 try {
744 salt.cmdRun(env, lastNodeTarget, "mkdir /root/mysql/mysql.bak")
Jiri Broulikf8f96942018-02-15 10:03:42 +0100745 } catch (Exception er) {
746 common.warningMsg('Directory already exists')
747 }
748 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100749 salt.cmdRun(env, lastNodeTarget, "rm -rf /root/mysql/mysql.bak/*")
Jiri Broulikf8f96942018-02-15 10:03:42 +0100750 } catch (Exception er) {
751 common.warningMsg('Directory already empty')
752 }
753 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100754 salt.cmdRun(env, lastNodeTarget, "mv /var/lib/mysql/* /root/mysql/mysql.bak")
Jiri Broulikf8f96942018-02-15 10:03:42 +0100755 } catch (Exception er) {
756 common.warningMsg('Files were already moved')
757 }
758 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100759 salt.runSaltProcessStep(env, lastNodeTarget, 'file.remove', ["/var/lib/mysql/.galera_bootstrap"])
Jiri Broulikf8f96942018-02-15 10:03:42 +0100760 } catch (Exception er) {
761 common.warningMsg('File is not present')
762 }
Martin Polreich9a5d6682018-12-21 16:42:06 +0100763 salt.cmdRun(env, lastNodeTarget, "sed -i '/gcomm/c\\wsrep_cluster_address=\"gcomm://\"' /etc/mysql/my.cnf")
764 def backup_dir = salt.getReturnValues(salt.getPillar(env, lastNodeTarget, 'xtrabackup:client:backup_dir'))
Jiri Broulikf8f96942018-02-15 10:03:42 +0100765 if(backup_dir == null || backup_dir.isEmpty()) { backup_dir='/var/backups/mysql/xtrabackup' }
Martin Polreich9a5d6682018-12-21 16:42:06 +0100766 salt.runSaltProcessStep(env, lastNodeTarget, 'file.remove', ["${backup_dir}/dbrestored"])
Jiri Broulikf8f96942018-02-15 10:03:42 +0100767 salt.cmdRun(env, 'I@xtrabackup:client', "su root -c 'salt-call state.sls xtrabackup'")
Martin Polreich9a5d6682018-12-21 16:42:06 +0100768 salt.runSaltProcessStep(env, lastNodeTarget, 'service.start', ['mysql'])
Jiri Broulikf8f96942018-02-15 10:03:42 +0100769
770 // wait until mysql service on galera master is up
Jiri Broulik22b04572018-02-16 12:02:41 +0100771 try {
Martin Polreich9a5d6682018-12-21 16:42:06 +0100772 salt.commandStatus(env, lastNodeTarget, 'service mysql status', 'running')
Jiri Broulik22b04572018-02-16 12:02:41 +0100773 } catch (Exception er) {
774 input message: "Database is not running please fix it first and only then click on PROCEED."
775 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100776
Martin Polreich9a5d6682018-12-21 16:42:06 +0100777 salt.runSaltProcessStep(env, "I@galera:master and not ${lastNodeTarget}", 'service.start', ['mysql'])
778 salt.runSaltProcessStep(env, "I@galera:slave and not ${lastNodeTarget}", 'service.start', ['mysql'])
Vasyl Saienko0adc34b2019-01-23 15:52:37 +0200779}