blob: 8c6384cee48124f2b3f9c382055a9f11178fb805 [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
2
Jakub Josefb77c0812017-03-27 14:11:01 +02003import java.util.stream.Collectors
Jakub Josef79ecec32017-02-17 14:36:28 +01004/**
5 * Salt functions
6 *
7*/
8
9/**
10 * Salt connection and context parameters
11 *
12 * @param url Salt API server URL
13 * @param credentialsID ID of credentials store entry
14 */
15def connection(url, credentialsId = "salt") {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010016 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +010017 params = [
18 "url": url,
19 "credentialsId": credentialsId,
20 "authToken": null,
21 "creds": common.getCredentials(credentialsId)
22 ]
23 params["authToken"] = saltLogin(params)
Jakub Josef79ecec32017-02-17 14:36:28 +010024 return params
25}
26
27/**
28 * Login to Salt API, return auth token
29 *
30 * @param master Salt connection object
31 */
32def saltLogin(master) {
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010033 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010034 data = [
35 'username': master.creds.username,
36 'password': master.creds.password.toString(),
37 'eauth': 'pam'
38 ]
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010039 authToken = http.restGet(master, '/login', data)['return'][0]['token']
Jakub Josef79ecec32017-02-17 14:36:28 +010040 return authToken
41}
42
43/**
chnydaa0dbb252017-10-05 10:46:09 +020044 * Run action using Salt API (using plain HTTP request from Jenkins master) or Pepper (from slave shell)
Jakub Josef79ecec32017-02-17 14:36:28 +010045 *
chnydaa0dbb252017-10-05 10:46:09 +020046 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) (determines if command will be sent with Pepper of Salt API )
Jakub Josef79ecec32017-02-17 14:36:28 +010047 * @param client Client type
48 * @param target Target specification, eg. for compound matches by Pillar
49 * data: ['expression': 'I@openssh:server', 'type': 'compound'])
50 * @param function Function to execute (eg. "state.sls")
Jakub Josef2f25cf22017-03-28 13:34:57 +020051 * @param batch Batch param to salt (integer or string with percents)
Martin Polreichf7976952019-03-04 10:06:11 +010052 * - null - automatic decision (based on number of worker threads env var or not use batch at all)
53 * - int - fixed size of batch
54 * - 'str%' - percantage of the requests in one batch
Jakub Josef79ecec32017-02-17 14:36:28 +010055 * @param args Additional arguments to function
56 * @param kwargs Additional key-value arguments to function
Jiri Broulik48544be2017-06-14 18:33:54 +020057 * @param timeout Additional argument salt api timeout
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +030058 * @param read_timeout http session read timeout
Jakub Josef79ecec32017-02-17 14:36:28 +010059 */
Jakub Josef79ecec32017-02-17 14:36:28 +010060
Martin Polreichf7976952019-03-04 10:06:11 +010061def runSaltCommand(saltId, client, target, function, batch = null, args = null, kwargs = null, timeout = -1, read_timeout = -1) {
Jakub Josef79ecec32017-02-17 14:36:28 +010062 data = [
63 'tgt': target.expression,
64 'fun': function,
65 'client': client,
66 'expr_form': target.type,
67 ]
Richard Felkld9476ac2018-07-12 19:01:33 +020068
Martin Polreichf7976952019-03-04 10:06:11 +010069 if (batch) {
Richard Felkld9476ac2018-07-12 19:01:33 +020070 batch = batch.toString()
Martin Polreichf7976952019-03-04 10:06:11 +010071 } else if (env.getEnvironment().containsKey('SALT_MASTER_OPT_WORKER_THREADS')) {
72 batch = env['SALT_MASTER_OPT_WORKER_THREADS'].toString()
73 }
74
75 if (batch instanceof String) {
76 if ((batch.isInteger() && batch.toInteger() > 0) || (batch.matches(/(\d){1,2}%/))){
Richard Felkld9476ac2018-07-12 19:01:33 +020077 data['client']= "local_batch"
78 data['batch'] = batch
79 }
Jakub Josef79ecec32017-02-17 14:36:28 +010080 }
81
82 if (args) {
83 data['arg'] = args
84 }
85
86 if (kwargs) {
87 data['kwarg'] = kwargs
88 }
89
Jiri Broulik48544be2017-06-14 18:33:54 +020090 if (timeout != -1) {
91 data['timeout'] = timeout
92 }
93
Martin Polreichf7976952019-03-04 10:06:11 +010094 def result = [:]
chnydaa0dbb252017-10-05 10:46:09 +020095 // Command will be sent using HttpRequest
96 if (saltId instanceof HashMap && saltId.containsKey("authToken") ) {
Jakub Josef79ecec32017-02-17 14:36:28 +010097
chnydaa0dbb252017-10-05 10:46:09 +020098 def headers = [
99 'X-Auth-Token': "${saltId.authToken}"
100 ]
101
102 def http = new com.mirantis.mk.Http()
Martin Polreichf7976952019-03-04 10:06:11 +0100103 result = http.sendHttpPostRequest("${saltId.url}/", data, headers, read_timeout)
chnydaa0dbb252017-10-05 10:46:09 +0200104 } else if (saltId instanceof HashMap) {
105 throw new Exception("Invalid saltId")
Martin Polreichf7976952019-03-04 10:06:11 +0100106 } else {
107 // Command will be sent using Pepper
108 result = runPepperCommand(data, saltId)
chnydaa0dbb252017-10-05 10:46:09 +0200109 }
110
Martin Polreichf7976952019-03-04 10:06:11 +0100111 // Convert returned Object to the same structure as from 'local' client to keep compatibility
112 if (data['client'].equals('local_batch')) {
113 def resultMap = ['return': [[:]]]
114 result['return'].each { it -> resultMap['return'][0] = it + resultMap['return'][0] }
115 return resultMap
116 } else {
117 return result
118 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100119}
120
Jakub Josef5ade54c2017-03-10 16:14:01 +0100121/**
chnydaa0dbb252017-10-05 10:46:09 +0200122 * Return pillar for given saltId and target
123 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100124 * @param target Get pillar target
125 * @param pillar pillar name (optional)
Martin Polreichf7976952019-03-04 10:06:11 +0100126 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100127 * @return output of salt command
128 */
Martin Polreichf7976952019-03-04 10:06:11 +0100129def getPillar(saltId, target, pillar = null, batch = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +0100130 if (pillar != null) {
Martin Polreichf7976952019-03-04 10:06:11 +0100131 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', batch, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +0100132 } else {
Martin Polreichf7976952019-03-04 10:06:11 +0100133 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.data', batch)
Ales Komareka3c7e502017-03-13 11:20:44 +0100134 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100135}
136
Jakub Josef5ade54c2017-03-10 16:14:01 +0100137/**
chnydaa0dbb252017-10-05 10:46:09 +0200138 * Return grain for given saltId and target
139 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100140 * @param target Get grain target
141 * @param grain grain name (optional)
Martin Polreichf7976952019-03-04 10:06:11 +0100142 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100143 * @return output of salt command
144 */
Martin Polreichf7976952019-03-04 10:06:11 +0100145def getGrain(saltId, target, grain = null, batch = null) {
Ales Komarekcec24d42017-03-08 10:25:45 +0100146 if(grain != null) {
Martin Polreichf7976952019-03-04 10:06:11 +0100147 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.item', batch, [grain])
Jakub Josef5ade54c2017-03-10 16:14:01 +0100148 } else {
Martin Polreichf7976952019-03-04 10:06:11 +0100149 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.items', batch)
Ales Komarekcec24d42017-03-08 10:25:45 +0100150 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100151}
152
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300153/**
154 * Return config items for given saltId and target
155 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
156 * @param target Get grain target
157 * @param config grain name (optional)
Martin Polreichf7976952019-03-04 10:06:11 +0100158 * @param batch Batch param to salt (integer or string with percents)
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300159 * @return output of salt command
160 */
Martin Polreichf7976952019-03-04 10:06:11 +0100161def getConfig(saltId, target, config, batch = null) {
162 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'config.get', batch, [config.replace('.', ':')], '--out=json')
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300163}
Jakub Josef432e9d92018-02-06 18:28:37 +0100164
Jakub Josef5ade54c2017-03-10 16:14:01 +0100165/**
chnydaa0dbb252017-10-05 10:46:09 +0200166 * Enforces state on given saltId and target
167 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100168 * @param target State enforcing target
169 * @param state Salt state
Jakub Josef432e9d92018-02-06 18:28:37 +0100170 * @param excludedStates states which will be excluded from main state (default empty string)
171 * @param output print output (optional, default true)
172 * @param failOnError throw exception on salt state result:false (optional, default true)
173 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
174 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
175 * @param read_timeout http session read timeout (optional, default -1 - disabled)
176 * @param retries Retry count for salt state. (optional, default -1 - no retries)
177 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
178 * @param saltArgs additional salt args eq. ["runas=aptly"]
179 * @return output of salt command
180 */
Martin Polreichc19e66b2018-10-22 12:22:03 +0200181def enforceStateWithExclude(Map params) {
182 //Set defaults
183 defaults = ["excludedStates": "", "output": true, "failOnError": true, "batch": null, "optional": false,
Martin Polreichf67b39a2019-02-08 10:06:34 +0100184 "read_timeout": -1, "retries": -1, "retries_wait": 5, "queue": true, "saltArgs": []]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200185 params = defaults + params
186 params.saltArgs << "exclude=${params.excludedStates}"
187 params.remove('excludedStates')
188 return enforceState(params)
189}
190
191
Martin Polreichf67b39a2019-02-08 10:06:34 +0100192def enforceStateWithExclude(saltId, target, state, excludedStates = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[], retries_wait=5) {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200193// Deprecated, convert state to use Map as input parameter
194 def common = new com.mirantis.mk.Common()
Martin Polreich49288692018-12-20 15:41:04 +0100195 common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter")
Martin Polreichc19e66b2018-10-22 12:22:03 +0200196 // Convert to Map
197 params = ['saltId': saltId, 'target': target, 'state': state, 'excludedStates': excludedStates, 'output': output,
198 'failOnError': failOnError, 'batch': batch, 'optional': optional, 'read_timeout': read_timeout,
Martin Polreichf67b39a2019-02-08 10:06:34 +0100199 'retries': retries, 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200200 // Call new method with Map as parameter
201 return enforceStateWithExclude(params)
Jakub Josef432e9d92018-02-06 18:28:37 +0100202}
203
Martin Polreich75e40642018-08-13 16:05:08 +0200204/**
205 * Allows to test the given target for reachability and if reachable enforces the state
206* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
207 * @param target State enforcing target
208 * @param state Salt state
209 * @param testTargetMatcher Salt compound matcher to be tested (default is empty string). If empty string, param `target` will be used for tests
210 * @param output print output (optional, default true)
211 * @param failOnError throw exception on salt state result:false (optional, default true)
212 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
213 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
214 * @param read_timeout http session read timeout (optional, default -1 - disabled)
215 * @param retries Retry count for salt state. (optional, default -1 - no retries)
216 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
217 * @param saltArgs additional salt args eq. ["runas=aptly"]
218 * @return output of salt command
219 */
Martin Polreichc19e66b2018-10-22 12:22:03 +0200220def enforceStateWithTest(Map params) {
Martin Polreich75e40642018-08-13 16:05:08 +0200221 def common = new com.mirantis.mk.Common()
Martin Polreichc19e66b2018-10-22 12:22:03 +0200222 //Set defaults
223 defaults = ["testTargetMatcher": "", "output": true, "failOnError": true, "batch": null, "optional": false,
Martin Polreichf67b39a2019-02-08 10:06:34 +0100224 "read_timeout": -1, "retries": -1, "retries_wait": 5, "queue": true, "saltArgs":[]]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200225 params = defaults + params
226 if (!params.testTargetMatcher) {
227 params.testTargetMatcher = params.target
Martin Polreich75e40642018-08-13 16:05:08 +0200228 }
Martin Polreichf7976952019-03-04 10:06:11 +0100229 if (testTarget(params.saltId, params.testTargetMatcher, params.batch)) {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200230 return enforceState(params)
Martin Polreich75e40642018-08-13 16:05:08 +0200231 } else {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200232 if (!params.optional) {
233 common.infoMsg("No Minions matched the target matcher: ${params.testTargetMatcher}, and 'optional' param was set to false. - This may signify missing pillar definition!!")
Martin Polreich92db3e12018-09-27 15:29:23 +0200234// throw new Exception("No Minions matched the target matcher: ${testTargetMatcher}.") TODO: Change the infoMsg to Error once the methods are changed to Use named params and optional param will be set globally
Martin Polreich75e40642018-08-13 16:05:08 +0200235 } else {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200236 common.infoMsg("No Minions matched the target matcher: ${params.testTargetMatcher}, but 'optional' param was set to true - Pipeline continues. ")
Martin Polreich75e40642018-08-13 16:05:08 +0200237 }
238 }
239}
240
Martin Polreichc19e66b2018-10-22 12:22:03 +0200241
Martin Polreichf67b39a2019-02-08 10:06:34 +0100242def enforceStateWithTest(saltId, target, state, testTargetMatcher = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[], retries_wait=5) {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200243// Deprecated, convert state to use Map as input parameter
244 def common = new com.mirantis.mk.Common()
Martin Polreich49288692018-12-20 15:41:04 +0100245 common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter")
Martin Polreichc19e66b2018-10-22 12:22:03 +0200246 // Convert to Map
247 params = ['saltId': saltId, 'target': target, 'state': state, 'testTargetMatcher': testTargetMatcher, 'output': output,
248 'failOnError': failOnError, 'batch': batch, 'optional': optional, 'read_timeout': read_timeout,
Martin Polreichf67b39a2019-02-08 10:06:34 +0100249 'retries': retries, 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200250 // Call new method with Map as parameter
251 return enforceStateWithTest(params)
252}
253
Jakub Josef432e9d92018-02-06 18:28:37 +0100254/* Enforces state on given saltId and target
255 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
256 * @param target State enforcing target
257 * @param state Salt state
Jakub Josef5ade54c2017-03-10 16:14:01 +0100258 * @param output print output (optional, default true)
259 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200260 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100261 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
Petr Michalecde0ff322017-10-04 09:32:14 +0200262 * @param read_timeout http session read timeout (optional, default -1 - disabled)
263 * @param retries Retry count for salt state. (optional, default -1 - no retries)
264 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
Jakub Josef432e9d92018-02-06 18:28:37 +0100265 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
Vasyl Saienko6a396212018-06-08 09:20:08 +0300266 * @param minionRestartWaitTimeout specifies timeout that we should wait after minion restart.
Jakub Josef5ade54c2017-03-10 16:14:01 +0100267 * @return output of salt command
268 */
Martin Polreichc19e66b2018-10-22 12:22:03 +0200269def enforceState(Map params) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100270 def common = new com.mirantis.mk.Common()
Martin Polreichc19e66b2018-10-22 12:22:03 +0200271 //Set defaults
Martin Polreichf67b39a2019-02-08 10:06:34 +0100272 defaults = ["output": true, "failOnError": true, "batch": null, "optional": false, "read_timeout": -1,
273 "retries": -1, "retries_wait": 5, "queue": true, "saltArgs": [], "minionRestartWaitTimeout": 10]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200274 params = defaults + params
Jakub Josef432e9d92018-02-06 18:28:37 +0100275 // add state to salt args
Martin Polreichc19e66b2018-10-22 12:22:03 +0200276 if (params.state instanceof String) {
277 params.saltArgs << params.state
Jakub Josef79ecec32017-02-17 14:36:28 +0100278 } else {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200279 params.saltArgs << params.state.join(',')
Jakub Josef79ecec32017-02-17 14:36:28 +0100280 }
281
Martin Polreichc19e66b2018-10-22 12:22:03 +0200282 common.infoMsg("Running state ${params.state} on ${params.target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300283 def out
Petr Michalecde0ff322017-10-04 09:32:14 +0200284 def kwargs = [:]
285
Martin Polreichc19e66b2018-10-22 12:22:03 +0200286 if (params.queue && params.batch == null) {
Petr Michalecde0ff322017-10-04 09:32:14 +0200287 kwargs["queue"] = true
288 }
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300289
Martin Polreichf7976952019-03-04 10:06:11 +0100290 if (params.optional == false || testTarget(params.saltId, params.target, params.batch)){
Martin Polreichc19e66b2018-10-22 12:22:03 +0200291 if (params.retries > 0){
Jakub Josef962ba912018-04-04 17:39:19 +0200292 def retriesCounter = 0
Martin Polreichc19e66b2018-10-22 12:22:03 +0200293 retry(params.retries){
Jakub Josef962ba912018-04-04 17:39:19 +0200294 retriesCounter++
Jakub Josef432e9d92018-02-06 18:28:37 +0100295 // we have to reverse order in saltArgs because salt state have to be first
Martin Polreichc19e66b2018-10-22 12:22:03 +0200296 out = runSaltCommand(params.saltId, 'local', ['expression': params.target, 'type': 'compound'], 'state.sls', params.batch, params.saltArgs.reverse(), kwargs, -1, params.read_timeout)
Jakub Josef432e9d92018-02-06 18:28:37 +0100297 // failOnError should be passed as true because we need to throw exception for retry block handler
Martin Polreichc19e66b2018-10-22 12:22:03 +0200298 checkResult(out, true, params.output, true, retriesCounter < params.retries) //disable ask on error for every interation except last one
Ivan Berezovskiy3e7656b2019-02-11 20:28:40 +0400299 sleep(params['retries_wait'])
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300300 }
Petr Michalecde0ff322017-10-04 09:32:14 +0200301 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100302 // we have to reverse order in saltArgs because salt state have to be first
Martin Polreichc19e66b2018-10-22 12:22:03 +0200303 out = runSaltCommand(params.saltId, 'local', ['expression': params.target, 'type': 'compound'], 'state.sls', params.batch, params.saltArgs.reverse(), kwargs, -1, params.read_timeout)
304 checkResult(out, params.failOnError, params.output)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300305 }
Martin Polreichc19e66b2018-10-22 12:22:03 +0200306 waitForMinion(out, params.minionRestartWaitTimeout)
Martin Polreich1c77afa2017-07-18 11:27:02 +0200307 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200308 } else {
309 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
310 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100311}
312
Martin Polreichf67b39a2019-02-08 10:06:34 +0100313def enforceState(saltId, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs = [], minionRestartWaitTimeout=10, retries_wait=5) {
Martin Polreichc19e66b2018-10-22 12:22:03 +0200314// Deprecated, convert state to use Map as input parameter
315 def common = new com.mirantis.mk.Common()
Martin Polreich49288692018-12-20 15:41:04 +0100316 common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter")
Martin Polreichc19e66b2018-10-22 12:22:03 +0200317 // Convert to Map
Martin Polreichf67b39a2019-02-08 10:06:34 +0100318 params = ['saltId': saltId, 'target': target, 'state': state, 'output': output, 'failOnError': failOnError,
319 'batch': batch, 'optional': optional, 'read_timeout': read_timeout, 'retries': retries,
320 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs, 'minionRestartWaitTimeout': minionRestartWaitTimeout]
Martin Polreichc19e66b2018-10-22 12:22:03 +0200321 // Call new method with Map as parameter
322 return enforceState(params)
323}
324
Jakub Josef5ade54c2017-03-10 16:14:01 +0100325/**
326 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200327 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100328 * @param target Get pillar target
329 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200330 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200331 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200332 * @param output do you want to print output
chnyda205a92b2018-01-11 17:07:32 +0100333 * @param saltArgs additional salt args eq. ["runas=aptly"]
Jakub Josef5ade54c2017-03-10 16:14:01 +0100334 * @return output of salt command
335 */
chnyda205a92b2018-01-11 17:07:32 +0100336def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100337 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200338 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100339 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200340 if (checkResponse) {
341 cmd = cmd + " && echo Salt command execution success"
342 }
chnyda205a92b2018-01-11 17:07:32 +0100343
Jakub Josef432e9d92018-02-06 18:28:37 +0100344 // add cmd name to salt args list
chnyda205a92b2018-01-11 17:07:32 +0100345 saltArgs << cmd
346
347 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse())
Jakub Josef053df392017-05-03 15:51:05 +0200348 if (checkResponse) {
349 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200350 if (out["return"]){
351 for(int i=0;i<out["return"].size();i++){
352 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200353 for(int j=0;j<node.size();j++){
354 def nodeKey = node.keySet()[j]
Martin Polreicha2effb82018-08-01 11:35:11 +0200355 if (node[nodeKey] instanceof String) {
356 if (!node[nodeKey].contains("Salt command execution success")) {
357 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
358 }
359 } else if (node[nodeKey] instanceof Boolean) {
360 if (!node[nodeKey]) {
361 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
362 }
363 } else {
364 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns unexpected data type: ${node[nodeKey]}")
Jakub Josef053df392017-05-03 15:51:05 +0200365 }
366 }
367 }
Martin Polreicha2effb82018-08-01 11:35:11 +0200368 } else {
Jakub Josef053df392017-05-03 15:51:05 +0200369 throw new Exception("Salt Api response doesn't have return param!")
370 }
371 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200372 if (output == true) {
373 printSaltCommandResult(out)
374 }
375 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100376}
377
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200378/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200379 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200380 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
381 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200382 * @param target Get pillar target
383 * @param minion_name unique identification of a minion in salt-key command output
384 * @param waitUntilPresent return after the minion becomes present (default true)
385 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
386 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200387 * @param maxRetries finite number of iterations to check status of a command (default 200)
388 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200389 * @return output of salt command
390 */
lmercl94189272018-06-01 11:03:46 +0200391def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200392 minion_name = minion_name.replace("*", "")
393 def common = new com.mirantis.mk.Common()
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200394 common.infoMsg("Looking for minion: " + minion_name)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200395 def cmd = 'salt-key | grep ' + minion_name
396 if (waitUntilPresent){
397 def count = 0
398 while(count < maxRetries) {
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200399 try {
400 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
401 if (output) {
402 printSaltCommandResult(out)
403 }
404 def valueMap = out["return"][0]
405 def result = valueMap.get(valueMap.keySet()[0])
406 def resultsArray = result.tokenize("\n")
407 def size = resultsArray.size()
408 if (size >= answers) {
409 return out
410 }
411 count++
412 sleep(time: 1000, unit: 'MILLISECONDS')
413 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
414 } catch (Exception er) {
415 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
416 }
417 }
418 } else {
419 try {
chnydaa0dbb252017-10-05 10:46:09 +0200420 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200421 if (output) {
422 printSaltCommandResult(out)
423 }
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200424 return out
425 } catch (Exception er) {
426 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
Jiri Broulik71512bc2017-08-04 10:00:18 +0200427 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200428 }
429 // otherwise throw exception
430 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
431 throw new Exception("${cmd} signals failure of status check!")
432}
433
434/**
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200435 * Checks if salt minions are in a list of salt master's accepted keys by matching compound
436 * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100437 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
438 * @param target Performs tests on this target node
439 * @param target_minions all targeted minions to test (for ex. I@salt:minion)
440 * @param waitUntilPresent return after the minion becomes present (default true)
441 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
442 * @param output print salt command (default true)
443 * @param maxRetries finite number of iterations to check status of a command (default 200)
444 * @param answers how many minions should return (optional, default 1)
445 * @return output of salt command
446 */
447def minionsPresent(saltId, target = 'I@salt:master', target_minions = '', waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
Martin Polreichf7976952019-03-04 10:06:11 +0100448 def target_hosts = getMinionsSorted(saltId, target_minions, batch)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100449 for (t in target_hosts) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200450 def tgt = stripDomainName(t)
451 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
452 }
453}
454
455/**
456 * Checks if salt minions are in a list of salt master's accepted keys by matching a list
457 * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3)
458 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
459 * @param target Performs tests on this target node
460 * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"])
461 * @param waitUntilPresent return after the minion becomes present (default true)
462 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
463 * @param output print salt command (default true)
464 * @param maxRetries finite number of iterations to check status of a command (default 200)
465 * @param answers how many minions should return (optional, default 1)
466 * @return output of salt command
467 */
468def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
469 def common = new com.mirantis.mk.Common()
470 for (tgt in target_minions) {
471 common.infoMsg("Checking if minion " + tgt + " is present")
472 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100473 }
474}
475
476/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200477 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200478 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200479 * @param target Should always be salt-master
Martin Polreich712d85c2019-07-01 17:21:12 +0200480 * @param targetNodes unique identification of a minion or group of salt minions
Jiri Broulik71512bc2017-08-04 10:00:18 +0200481 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Martin Polreich712d85c2019-07-01 17:21:12 +0200482 * @param cmdTimeout timeout for the salt command if minions do not return (default 10)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200483 * @param maxRetries finite number of iterations to check status of a command (default 200)
484 * @return output of salt command
485 */
Martin Polreich712d85c2019-07-01 17:21:12 +0200486
487def minionsReachable(saltId, target, targetNodes, batch=null, cmdTimeout = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200488 def common = new com.mirantis.mk.Common()
Martin Polreich712d85c2019-07-01 17:21:12 +0200489 def cmd = "salt -t${cmdTimeout} -C '${targetNodes}' test.ping"
490 common.infoMsg("Checking if all ${targetNodes} minions are reachable")
491 def retriesCount = 0
492 while(retriesCount < maxRetries) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200493 Calendar timeout = Calendar.getInstance();
Martin Polreich712d85c2019-07-01 17:21:12 +0200494 timeout.add(Calendar.SECOND, cmdTimeout);
495 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, cmdTimeout)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200496 Calendar current = Calendar.getInstance();
497 if (current.getTime().before(timeout.getTime())) {
Martin Polreich712d85c2019-07-01 17:21:12 +0200498 common.infoMsg("Successful response received from all targeted nodes.")
499 printSaltCommandResult(out)
500 return out
Jiri Broulik71512bc2017-08-04 10:00:18 +0200501 }
Martin Polreich712d85c2019-07-01 17:21:12 +0200502 def outYaml = readYaml text: getReturnValues(out)
503 def successfulNodes = []
504 def failedNodes = []
505 for (node in outYaml.keySet()) {
506 if (outYaml[node] == true || outYaml[node].toString().toLowerCase() == 'true') {
507 successfulNodes.add(node)
508 } else {
509 failedNodes.add(node)
510 }
511 }
512 common.infoMsg("Not all of the targeted minions returned yet. Successful response from ${successfulNodes}. Still waiting for ${failedNodes}.")
513 retriesCount++
Jiri Broulik71512bc2017-08-04 10:00:18 +0200514 sleep(time: 500, unit: 'MILLISECONDS')
515 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200516}
517
Martin Polreich712d85c2019-07-01 17:21:12 +0200518
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200519/**
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400520 * You can call this function when need to check that all minions are available, free and ready for command execution
521 * @param config LinkedHashMap config parameter, which contains next:
522 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
523 * @param target unique identification of a minion or group of salt minions
524 * @param target_reachable unique identification of a minion or group of salt minions to check availability
525 * @param wait timeout between retries to check target minions (default 5)
526 * @param retries finite number of iterations to check minions (default 10)
527 * @param timeout timeout for the salt command if minions do not return (default 5)
528 * @param availability check that minions also are available before checking readiness (default true)
529 */
530def checkTargetMinionsReady(LinkedHashMap config) {
531 def common = new com.mirantis.mk.Common()
532 def saltId = config.get('saltId')
533 def target = config.get('target')
534 def target_reachable = config.get('target_reachable', target)
535 def wait = config.get('wait', 30)
536 def retries = config.get('retries', 10)
537 def timeout = config.get('timeout', 5)
538 def checkAvailability = config.get('availability', true)
Martin Polreichf7976952019-03-04 10:06:11 +0100539 def batch = config.get('batch', null)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400540 common.retry(retries, wait) {
541 if (checkAvailability) {
Martin Polreichf7976952019-03-04 10:06:11 +0100542 minionsReachable(saltId, 'I@salt:master', target_reachable, batch)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400543 }
Martin Polreichf7976952019-03-04 10:06:11 +0100544 def running = runSaltProcessStep(saltId, target, 'saltutil.running', [], batch, true, timeout)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400545 for (value in running.get("return")[0].values()) {
546 if (value != []) {
547 throw new Exception("Not all salt-minions are ready for execution")
548 }
549 }
550 }
551}
552
553/**
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300554 * Restart and wait for salt-minions on target nodes.
555 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
556 * @param target unique identification of a minion or group of salt minions
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400557 * @param wait timeout for the salt command if minions do not return (default 10)
558 * @param maxRetries finite number of iterations to check status of a command (default 15)
559 * @param async Run salt minion restart and do not wait for response
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300560 * @return output of salt command
561 */
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400562def restartSaltMinion(saltId, target, wait = 10, maxRetries = 15, async = true) {
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300563 def common = new com.mirantis.mk.Common()
564 common.infoMsg("Restarting salt-minion on ${target} and waiting for they are reachable.")
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400565 runSaltProcessStep(saltId, target, 'cmd.shell', ['salt-call service.restart salt-minion'], null, true, 60, null, async)
566 checkTargetMinionsReady(['saltId': saltId, 'target': target, timeout: wait, retries: maxRetries])
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300567 common.infoMsg("All ${target} minions are alive...")
568}
569
570/**
571 * Upgrade package and restart salt minion.
572 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
573 * @param target unique identification of a minion or group of salt minions
574 * @param the name of pkg_name to upgrade
575 * @param wait timeout for the salt command if minions do not return (default 5)
576 * @param maxRetries finite number of iterations to check status of a command (default 10)
577 * @return output of salt command
578 */
579def upgradePackageAndRestartSaltMinion(saltId, target, pkg_name, wait = 5, maxRetries = 10) {
580 def common = new com.mirantis.mk.Common()
581 def latest_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.latest_version', [pkg_name, 'show_installed=True'])).split('\n')[0]
582 def current_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.version', [pkg_name])).split('\n')[0]
583 if (current_version && latest_version != current_version) {
584 common.infoMsg("Upgrading current ${pkg_name}: ${current_version} to ${latest_version}")
585 runSaltProcessStep(saltId, target, 'pkg.install', [pkg_name], 'only_upgrade=True')
586 restartSaltMinion(saltId, target, wait, maxRetries)
587 }
588}
589
590/**
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200591 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200592 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200593 * @param target Get pillar target
594 * @param cmd name of a service
595 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200596 * @param find bool value if it is suppose to find some string in the output or the cmd should return empty string (optional, default true)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200597 * @param waitUntilOk return after the minion becomes present (optional, default true)
598 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
599 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200600 * @param maxRetries finite number of iterations to check status of a command (default 200)
601 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200602 * @return output of salt command
603 */
chnydaa0dbb252017-10-05 10:46:09 +0200604def commandStatus(saltId, target, cmd, correct_state='running', find = true, waitUntilOk = true, batch=null, output = true, maxRetries = 200, answers = 0) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200605 def common = new com.mirantis.mk.Common()
606 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
607 if (waitUntilOk){
608 def count = 0
609 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200610 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200611 if (output) {
612 printSaltCommandResult(out)
613 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200614 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200615 def success = 0
616 if (answers == 0){
617 answers = resultMap.size()
618 }
619 for (int i=0;i<answers;i++) {
620 result = resultMap.get(resultMap.keySet()[i])
621 // if the goal is to find some string in output of the command
622 if (find) {
623 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
624 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
625 success++
626 if (success == answers) {
627 return out
628 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200629 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200630 // else the goal is to not find any string in output of the command
631 } else {
632 if(result instanceof String && result.isEmpty()) {
633 success++
634 if (success == answers) {
635 return out
chnydaa0dbb252017-10-05 10:46:09 +0200636 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200637 }
638 }
639 }
640 count++
641 sleep(time: 500, unit: 'MILLISECONDS')
642 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
643 }
644 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200645 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200646 def resultMap = out["return"][0]
647 if (output) {
648 printSaltCommandResult(out)
649 }
650 for (int i=0;i<resultMap.size();i++) {
651 result = resultMap.get(resultMap.keySet()[i])
652 // if the goal is to find some string in output of the command
653 if (find) {
654 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
655 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200656 return out
657 }
658
659 // else the goal is to not find any string in output of the command
660 } else {
661 if(result instanceof String && result.isEmpty()) {
662 return out
663 }
664 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200665 }
666 }
667 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200668 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200669 throw new Exception("${cmd} signals failure of status check!")
670}
671
Jakub Josef5ade54c2017-03-10 16:14:01 +0100672/**
673 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200674 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100675 * @param target Get pillar target
Martin Polreichf7976952019-03-04 10:06:11 +0100676 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100677 * @return output of salt command
678 */
Martin Polreichf7976952019-03-04 10:06:11 +0100679def syncAll(saltId, target, batch = null) {
680 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all', batch)
Jakub Josef79ecec32017-02-17 14:36:28 +0100681}
682
Jakub Josef5ade54c2017-03-10 16:14:01 +0100683/**
Jakub Josef432e9d92018-02-06 18:28:37 +0100684 * Perform complete salt refresh between master and target
685 * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all
686 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
687 * @param target Get pillar target
Martin Polreichf7976952019-03-04 10:06:11 +0100688 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef432e9d92018-02-06 18:28:37 +0100689 * @return output of salt command
690 */
Martin Polreichf7976952019-03-04 10:06:11 +0100691def fullRefresh(saltId, target, batch=20){
692 runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], batch, true)
693 runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], batch, true)
694 runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], batch, true)
Jakub Josef432e9d92018-02-06 18:28:37 +0100695}
696
697/**
698 * Enforce highstate on given targets
699 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
700 * @param target Highstate enforcing target
701 * @param excludedStates states which will be excluded from main state (default empty string)
702 * @param output print output (optional, default true)
703 * @param failOnError throw exception on salt state result:false (optional, default true)
704 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
705 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
706 * @return output of salt command
707 */
708def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) {
709 saltArgs << "exclude=${excludedStates}"
710 return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs)
711}
712/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100713 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200714 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100715 * @param target Highstate enforcing target
716 * @param output print output (optional, default true)
717 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200718 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100719 * @return output of salt command
720 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100721def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) {
Petr Jediný30be7032018-05-29 18:22:46 +0200722 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000723 def common = new com.mirantis.mk.Common()
724
Marek Celoud63366112017-07-25 17:27:24 +0200725 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000726
Jakub Josef374beb72017-04-27 15:45:09 +0200727 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100728 return out
729}
730
Jakub Josef5ade54c2017-03-10 16:14:01 +0100731/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100732 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200733 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100734 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100735 * @param batch Batch param to salt (integer or string with percents)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100736 * @return list of active minions fitin
737 */
Martin Polreichf7976952019-03-04 10:06:11 +0100738def getMinions(saltId, target, batch = null) {
739 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping', batch)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100740 return new ArrayList<String>(minionsRaw['return'][0].keySet())
741}
742
Jiri Broulikf8f96942018-02-15 10:03:42 +0100743/**
744 * Get sorted running minions IDs according to the target
745 * @param saltId Salt Connection object or pepperEnv
746 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100747 * @param batch Batch param to salt (integer or string with percents)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100748 * @return list of sorted active minions fitin
749 */
Martin Polreichf7976952019-03-04 10:06:11 +0100750def getMinionsSorted(saltId, target, batch = null) {
751 return getMinions(saltId, target, batch).sort()
Jiri Broulikf8f96942018-02-15 10:03:42 +0100752}
753
754/**
755 * Get first out of running minions IDs according to the target
756 * @param saltId Salt Connection object or pepperEnv
757 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100758 * @param batch Batch param to salt (integer or string with percents)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100759 * @return first of active minions fitin
760 */
Martin Polreichf7976952019-03-04 10:06:11 +0100761def getFirstMinion(saltId, target, batch = null) {
762 def minionsSorted = getMinionsSorted(saltId, target, batch)
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400763 return minionsSorted[0]
Jiri Broulikf8f96942018-02-15 10:03:42 +0100764}
765
766/**
767 * Get running salt minions IDs without it's domain name part and its numbering identifications
768 * @param saltId Salt Connection object or pepperEnv
769 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100770 * @param batch Batch param to salt (integer or string with percents)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100771 * @return list of active minions fitin without it's domain name part name numbering
772 */
Martin Polreichf7976952019-03-04 10:06:11 +0100773def getMinionsGeneralName(saltId, target, batch = null) {
774 def minionsSorted = getMinionsSorted(saltId, target, batch)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100775 return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "")
776}
777
778/**
779 * Get domain name of the env
780 * @param saltId Salt Connection object or pepperEnv
781 * @return domain name
782 */
783def getDomainName(saltId) {
784 return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain'))
785}
786
787/**
788 * Remove domain name from Salt minion ID
789 * @param name String of Salt minion ID
790 * @return Salt minion ID without its domain name
791 */
792def stripDomainName(name) {
793 return name.split("\\.")[0]
794}
795
796/**
797 * Gets return values of a salt command
798 * @param output String of Salt minion ID
799 * @return Return values of a salt command
800 */
801def getReturnValues(output) {
Martin Polreichf7976952019-03-04 10:06:11 +0100802 if(output && output.containsKey("return") && !output.get("return").isEmpty()) {
Jiri Broulikf8f96942018-02-15 10:03:42 +0100803 return output['return'][0].values()[0]
804 }
805 def common = new com.mirantis.mk.Common()
806 common.errorMsg('output does not contain return key')
807 return ''
808}
809
810/**
811 * Get minion ID of one of KVM nodes
812 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
813 * @return Salt minion ID of one of KVM nodes in env
814 */
815def getKvmMinionId(saltId) {
816 return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0]
817}
818
819/**
820 * Get Salt minion ID of KVM node hosting 'name' VM
821 * @param saltId Salt Connection object or pepperEnv
822 * @param name Name of the VM (for ex. ctl01)
823 * @return Salt minion ID of KVM node hosting 'name' VM
824 */
Jiri Broulikd2a50552018-04-25 17:17:59 +0200825def getNodeProvider(saltId, nodeName) {
826 def salt = new com.mirantis.mk.Salt()
827 def common = new com.mirantis.mk.Common()
828 def kvms = salt.getMinions(saltId, 'I@salt:control')
829 for (kvm in kvms) {
830 try {
831 vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true))
832 if (vms.toString().contains(nodeName)) {
833 return kvm
834 }
835 } catch (Exception er) {
836 common.infoMsg("${nodeName} not present on ${kvm}")
837 }
838 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100839}
840
Ales Komarek5276ebe2017-03-16 08:46:34 +0100841/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200842 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200843 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200844 * @param target Target to test
Martin Polreichf7976952019-03-04 10:06:11 +0100845 * @param batch Batch param to salt (integer or string with percents)
vrovachev1c4770b2017-07-05 13:25:21 +0400846 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200847 */
848
Martin Polreichf7976952019-03-04 10:06:11 +0100849def testTarget(saltId, target, batch = null) {
850 return getMinions(saltId, target, batch).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200851}
852
853/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100854 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200855 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100856 * @param target Key generating target
857 * @param host Key generating host
858 * @param keysize generated key size (optional, default 4096)
Martin Polreichf7976952019-03-04 10:06:11 +0100859 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100860 * @return output of salt command
861 */
Martin Polreichf7976952019-03-04 10:06:11 +0100862def generateNodeKey(saltId, target, host, keysize = 4096, batch = null) {
863 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', batch, [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100864}
865
Jakub Josef5ade54c2017-03-10 16:14:01 +0100866/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200867 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200868 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100869 * @param target Metadata generating target
870 * @param host Metadata generating host
871 * @param classes Reclass classes
872 * @param parameters Reclass parameters
Martin Polreichf7976952019-03-04 10:06:11 +0100873 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100874 * @return output of salt command
875 */
Martin Polreichf7976952019-03-04 10:06:11 +0100876def generateNodeMetadata(saltId, target, host, classes, parameters, batch = null) {
877 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', batch, [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100878}
879
Jakub Josef5ade54c2017-03-10 16:14:01 +0100880/**
881 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200882 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100883 * @param target Orchestration target
884 * @param orchestrate Salt orchestrate params
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200885 * @param kwargs Salt orchestrate params
Martin Polreichf7976952019-03-04 10:06:11 +0100886 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100887 * @return output of salt command
888 */
Martin Polreichf7976952019-03-04 10:06:11 +0100889def orchestrateSystem(saltId, target, orchestrate=[], kwargs = null, batch = null) {
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300890 //Since the runSaltCommand uses "arg" (singular) for "runner" client this won`t work correctly on old salt 2016
891 //cause this version of salt used "args" (plural) for "runner" client, see following link for reference:
892 //https://github.com/saltstack/salt/pull/32938
Oleksii Grudev0c098382018-08-08 16:16:38 +0300893 def common = new com.mirantis.mk.Common()
Martin Polreichf7976952019-03-04 10:06:11 +0100894 def result = runSaltCommand(saltId, 'runner', target, 'state.orchestrate', batch, orchestrate, kwargs, 7200, 7200)
Oleksii Grudev0c098382018-08-08 16:16:38 +0300895 if(result != null){
896 if(result['return']){
897 def retcode = result['return'][0].get('retcode')
898 if (retcode != 0) {
899 throw new Exception("Orchestration state failed while running: "+orchestrate)
900 }else{
901 common.infoMsg("Orchestrate state "+orchestrate+" succeeded")
902 }
903 }else{
904 common.errorMsg("Salt result has no return attribute! Result: ${result}")
905 }
906 }else{
907 common.errorMsg("Cannot check salt result, given result is null")
908 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100909}
910
Jakub Josef5ade54c2017-03-10 16:14:01 +0100911/**
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200912 * Run salt pre or post orchestrate tasks
913 *
914 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
915 * @param pillar_tree Reclass pillar that has orchestrate pillar for desired stage
916 * @param extra_tgt Extra targets for compound
Martin Polreichf7976952019-03-04 10:06:11 +0100917 * @param batch Batch param to salt (integer or string with percents)
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200918 * @return output of salt command
919 */
Martin Polreichf7976952019-03-04 10:06:11 +0100920def orchestratePrePost(saltId, pillar_tree, extra_tgt = '', batch = null) {
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200921
922 def common = new com.mirantis.mk.Common()
923 def salt = new com.mirantis.mk.Salt()
924 def compound = 'I@' + pillar_tree + " " + extra_tgt
925
926 common.infoMsg("Refreshing pillars")
Martin Polreichf7976952019-03-04 10:06:11 +0100927 runSaltProcessStep(saltId, '*', 'saltutil.refresh_pillar', [], batch, true)
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200928
929 common.infoMsg("Looking for orchestrate pillars")
Martin Polreichf7976952019-03-04 10:06:11 +0100930 if (salt.testTarget(saltId, compound, batch)) {
931 for ( node in salt.getMinionsSorted(saltId, compound, batch) ) {
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200932 def pillar = salt.getPillar(saltId, node, pillar_tree)
933 if ( !pillar['return'].isEmpty() ) {
934 for ( orch_id in pillar['return'][0].values() ) {
935 def orchestrator = orch_id.values()['orchestrator']
936 def orch_enabled = orch_id.values()['enabled']
937 if ( orch_enabled ) {
938 common.infoMsg("Orchestrating: ${orchestrator}")
Martin Polreichf7976952019-03-04 10:06:11 +0100939 salt.printSaltCommandResult(salt.orchestrateSystem(saltId, ['expression': node], [orchestrator], null, batch))
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200940 }
941 }
942 }
943 }
944 }
945}
946
947/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100948 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200949 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100950 * @param tgt Salt process step target
951 * @param fun Salt process step function
952 * @param arg process step arguments (optional, default [])
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400953 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch). Can't be used with async
Jakub Josef432e9d92018-02-06 18:28:37 +0100954 * @param output print output (optional, default true)
Jiri Broulik48544be2017-06-14 18:33:54 +0200955 * @param timeout Additional argument salt api timeout
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400956 * @param async Run the salt command but don't wait for a reply. Can't be used with batch
Jakub Josef5ade54c2017-03-10 16:14:01 +0100957 * @return output of salt command
958 */
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400959def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null, async = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100960 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200961 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100962 def out
963
Marek Celoud63366112017-07-25 17:27:24 +0200964 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Martin Polreichf7976952019-03-04 10:06:11 +0100965 if (async == true) {
966 out = runSaltCommand(saltId, 'local_async', ['expression': tgt, 'type': 'compound'], fun, null, arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100967 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200968 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100969 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100970
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100971 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200972 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100973 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200974 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100975}
976
977/**
978 * Check result for errors and throw exception if any found
979 *
980 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200981 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200982 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200983 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef432e9d92018-02-06 18:28:37 +0100984 * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false)
Jakub Josef79ecec32017-02-17 14:36:28 +0100985 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100986def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100987 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100988 if(result != null){
989 if(result['return']){
990 for (int i=0;i<result['return'].size();i++) {
991 def entry = result['return'][i]
992 if (!entry) {
993 if (failOnError) {
994 throw new Exception("Salt API returned empty response: ${result}")
995 } else {
996 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100997 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100998 }
999 for (int j=0;j<entry.size();j++) {
1000 def nodeKey = entry.keySet()[j]
1001 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +02001002 def outputResources = []
Jakub Josef47145942018-04-04 17:30:38 +02001003 def errorResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001004 common.infoMsg("Node ${nodeKey} changes:")
1005 if(node instanceof Map || node instanceof List){
1006 for (int k=0;k<node.size();k++) {
1007 def resource;
1008 def resKey;
1009 if(node instanceof Map){
1010 resKey = node.keySet()[k]
Victor Ryzhenkin49d67812019-01-09 15:28:21 +04001011 if (resKey == "retcode") {
Richard Felkld9476ac2018-07-12 19:01:33 +02001012 continue
Victor Ryzhenkin49d67812019-01-09 15:28:21 +04001013 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001014 }else if(node instanceof List){
1015 resKey = k
1016 }
1017 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +02001018 // print
Jakub Josefa87941c2017-04-20 17:14:58 +02001019 if(printResults){
1020 if(resource instanceof Map && resource.keySet().contains("result")){
1021 //clean unnesaccary fields
1022 if(resource.keySet().contains("__run_num__")){
1023 resource.remove("__run_num__")
1024 }
1025 if(resource.keySet().contains("__id__")){
1026 resource.remove("__id__")
1027 }
1028 if(resource.keySet().contains("pchanges")){
1029 resource.remove("pchanges")
1030 }
1031 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
1032 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +02001033 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001034 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +02001035 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001036 }
1037 }else{
Ivan Berezovskiy65fb6372019-08-09 19:49:55 +04001038 if(!printOnlyChanges || (resource.changes && resource.changes.size() > 0)) {
Jakub Josefbceaa322017-06-13 18:28:27 +02001039 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001040 }
1041 }
1042 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +02001043 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001044 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001045 }
Jakub Josefc4c40202017-04-28 12:04:24 +02001046 common.debugMsg("checkResult: checking resource: ${resource}")
1047 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josef47145942018-04-04 17:30:38 +02001048 errorResources.add(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +02001049 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001050 }
Jakub Josefa87941c2017-04-20 17:14:58 +02001051 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +02001052 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001053 }
1054 if(printResults && !outputResources.isEmpty()){
Jakub Josef47145942018-04-04 17:30:38 +02001055 println outputResources.stream().collect(Collectors.joining("\n"))
1056 }
1057 if(!errorResources.isEmpty()){
1058 for(resource in errorResources){
1059 def prettyResource = common.prettify(resource)
1060 if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") {
1061 timeout(time:1, unit:'HOURS') {
1062 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
1063 }
1064 } else {
1065 def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}"
1066 if (failOnError) {
1067 throw new Exception(errorMsg)
1068 } else {
1069 common.errorMsg(errorMsg)
1070 }
1071 }
1072 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001073 }
1074 }
Jakub Josef52f69f72017-03-14 15:18:08 +01001075 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001076 }else{
1077 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +01001078 }
Jakub Josef52f69f72017-03-14 15:18:08 +01001079 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +02001080 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +01001081 }
1082}
1083
1084/**
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001085* Parse salt API output to check minion restart and wait some time to be sure minion is up.
1086* See https://mirantis.jira.com/browse/PROD-16258 for more details
1087* TODO: change sleep to more tricky procedure.
1088*
1089* @param result Parsed response of Salt API
1090*/
Vasyl Saienko6a396212018-06-08 09:20:08 +03001091def waitForMinion(result, minionRestartWaitTimeout=10) {
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001092 def common = new com.mirantis.mk.Common()
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001093 //In order to prevent multiple sleeps use bool variable to catch restart for any minion.
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001094 def isMinionRestarted = false
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001095 if(result != null){
1096 if(result['return']){
1097 for (int i=0;i<result['return'].size();i++) {
1098 def entry = result['return'][i]
1099 // exit in case of empty response.
1100 if (!entry) {
1101 return
1102 }
1103 // Loop for nodes
1104 for (int j=0;j<entry.size();j++) {
1105 def nodeKey = entry.keySet()[j]
1106 def node=entry[nodeKey]
1107 if(node instanceof Map || node instanceof List){
1108 // Loop for node resources
1109 for (int k=0;k<node.size();k++) {
1110 def resource;
1111 def resKey;
1112 if(node instanceof Map){
1113 resKey = node.keySet()[k]
1114 }else if(node instanceof List){
1115 resKey = k
1116 }
1117 resource = node[resKey]
Jakub Joseffb9996d2018-04-10 14:05:31 +02001118 // try to find if salt_minion service was restarted
1119 if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001120 if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){
1121 if(resource.changes.size() > 0){
1122 isMinionRestarted=true
1123 }
1124 }
1125 }
1126 }
1127 }
1128 }
1129 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001130 }
1131 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001132 if (isMinionRestarted){
Vasyl Saienko6a396212018-06-08 09:20:08 +03001133 common.infoMsg("Salt minion service restart detected. Sleep ${minionRestartWaitTimeout} seconds to wait minion restart")
1134 sleep(minionRestartWaitTimeout)
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001135 }
1136}
1137
1138/**
Jakub Josef7852fe12017-03-15 16:02:41 +01001139 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +01001140 *
1141 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +01001142 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +01001143def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +01001144 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001145 if(result != null){
1146 if(result['return']){
1147 for (int i=0; i<result['return'].size(); i++) {
1148 def entry = result['return'][i]
1149 for (int j=0; j<entry.size(); j++) {
1150 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
1151 def nodeKey = entry.keySet()[j]
1152 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +02001153 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001154 }
Jakub Josef8a715bf2017-03-14 21:39:01 +01001155 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001156 }else{
1157 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +01001158 }
Jakub Josef8a715bf2017-03-14 21:39:01 +01001159 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001160 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +01001161 }
Jakub Josef79ecec32017-02-17 14:36:28 +01001162}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001163
1164
1165/**
1166 * Return content of file target
1167 *
chnydaa0dbb252017-10-05 10:46:09 +02001168 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001169 * @param target Compound target (should target only one host)
1170 * @param file File path to read (/etc/hosts for example)
1171 */
1172
Pavlo Shchelokovskyy97100072018-10-04 11:53:44 +03001173def getFileContent(saltId, target, file, checkResponse = true, batch=null, output = true, saltArgs = []) {
1174 result = cmdRun(saltId, target, "cat ${file}", checkResponse, batch, output, saltArgs)
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +02001175 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001176}
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001177
1178/**
1179 * Set override parameters in Salt cluster metadata
1180 *
chnydaa0dbb252017-10-05 10:46:09 +02001181 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001182 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +03001183 * @param reclass_dir Directory where Reclass git repo is located
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +02001184 * @param extra_tgt Extra targets for compound
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001185 */
1186
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001187def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass", extra_tgt = '') {
Tomáš Kukrálf178f052017-07-11 11:31:00 +02001188 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +03001189 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +02001190 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001191 def key = entry[0]
1192 def value = entry[1]
1193
1194 common.debugMsg("Set salt override ${key}=${value}")
Victor Ryzhenkin2f997302019-01-10 15:12:55 +04001195 runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'reclass.cluster_meta_set', ["name=${key}", "value=${value}"], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001196 }
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001197 runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'cmd.run', ["git -C ${reclass_dir} update-index --skip-worktree classes/cluster/overrides.yml"])
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001198}
Oleg Grigorovbec45582017-09-12 20:29:24 +03001199
1200/**
1201* Execute salt commands via salt-api with
1202* CLI client salt-pepper
1203*
1204* @param data Salt command map
1205* @param venv Path to virtualenv with
1206*/
1207
azvyagintsev386e94e2019-06-13 13:39:04 +03001208def runPepperCommand(data, venv) {
Jakub Josef03d4d5a2017-12-20 16:35:09 +01001209 def common = new com.mirantis.mk.Common()
Oleg Grigorovbec45582017-09-12 20:29:24 +03001210 def python = new com.mirantis.mk.Python()
1211 def dataStr = new groovy.json.JsonBuilder(data).toString()
azvyagintsev386e94e2019-06-13 13:39:04 +03001212 // TODO(alexz): parametrize?
1213 int retry = 10
chnyda4901a042017-11-16 12:14:56 +01001214
Jakub Josefa2491ad2018-01-15 16:26:27 +01001215 def pepperCmdFile = "${venv}/pepper-cmd.json"
1216 writeFile file: pepperCmdFile, text: dataStr
1217 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}"
Oleg Grigorovbec45582017-09-12 20:29:24 +03001218
azvyagintsev386e94e2019-06-13 13:39:04 +03001219 int tries = 0
1220 def FullOutput = ['status': 1]
Jakub Josef37cd4972018-02-01 16:25:25 +01001221 def outputObj
azvyagintsev386e94e2019-06-13 13:39:04 +03001222 while (tries++ < retry) {
1223 try {
1224 if (venv) {
1225 FullOutput = python.runVirtualenvCommand(venv, pepperCmd, true, true)
1226 } else {
1227 FullOutput = common.shCmdStatus(pepperCmd)
1228 }
1229 if (FullOutput['status'] != 0) {
1230 error()
1231 }
1232 break
1233 } catch (e) {
1234 // Check , if we get failed pepper HTTP call, and retry
1235 common.errorMsg("Command: ${pepperCmd} failed to execute with error:\n${FullOutput['stderr']}")
1236 if (FullOutput['stderr'].contains('Error with request: HTTP Error 50') || FullOutput['stderr'].contains('Pepper error: Server error')) {
1237 common.errorMsg("Pepper HTTP Error detected. Most probably, " +
1238 "master SaltReqTimeoutError in master zmq thread issue...lets retry ${tries}/${retry}")
1239 sleep(5)
1240 continue
1241 }
1242 }
1243 }
1244 // Try to parse json output. No sense to check exit code, since we always expect json answer only.
Jakub Josef37cd4972018-02-01 16:25:25 +01001245 try {
azvyagintsev386e94e2019-06-13 13:39:04 +03001246 outputObj = new groovy.json.JsonSlurperClassic().parseText(FullOutput['stdout'])
1247 } catch (Exception jsonE) {
1248 common.errorMsg('Parsing Salt API JSON response failed! Response: ' + FullOutput)
1249 throw jsonE
Jakub Josef37cd4972018-02-01 16:25:25 +01001250 }
1251 return outputObj
Oleg Grigorovbec45582017-09-12 20:29:24 +03001252}
Martin Polreich232ad902019-01-21 14:31:00 +01001253
azvyagintsev386e94e2019-06-13 13:39:04 +03001254
Martin Polreich232ad902019-01-21 14:31:00 +01001255/**
1256* Check time settings on defined nodes, compares them
1257* and evaluates the results
1258*
1259* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1260* @param target Targeted nodes to be checked
1261* @param diff Maximum time difference (in seconds) to be accepted during time sync check
Martin Polreichf7976952019-03-04 10:06:11 +01001262* @param batch Batch param to salt (integer or string with percents)
Martin Polreich232ad902019-01-21 14:31:00 +01001263* @return bool Return true if time difference is <= diff and returns false if time difference is > diff
1264*/
1265
Martin Polreichf7976952019-03-04 10:06:11 +01001266def checkClusterTimeSync(saltId, target, batch = null) {
Martin Polreich232ad902019-01-21 14:31:00 +01001267 def common = new com.mirantis.mk.Common()
1268 def salt = new com.mirantis.mk.Salt()
1269
1270 times = []
1271 try {
1272 diff = salt.getReturnValues(salt.getPillar(saltId, 'I@salt:master', 'linux:system:time_diff'))
1273 if (diff != null && diff != "" && diff.isInteger()) {
1274 diff = diff.toInteger()
1275 } else {
1276 diff = 5
1277 }
Martin Polreichf7976952019-03-04 10:06:11 +01001278 out = salt.runSaltProcessStep(saltId, target, 'status.time', '%s', batch)
Martin Polreich232ad902019-01-21 14:31:00 +01001279 outParsed = out['return'][0]
1280 def outKeySet = outParsed.keySet()
1281 for (key in outKeySet) {
1282 def time = outParsed[key].readLines().get(0)
1283 common.infoMsg(time)
1284 if (time.isInteger()) {
1285 times.add(time.toInteger())
1286 }
1287 }
1288 if ((times.max() - times.min()) <= diff) {
1289 return true
1290 } else {
1291 return false
1292 }
1293 } catch(Exception e) {
1294 common.errorMsg("Could not check cluster time sync.")
1295 return false
1296 }
1297}
Martin Polreichb577f2d2019-02-27 09:28:35 +01001298
1299/**
1300* Finds out IP address of the given node or a list of nodes
1301*
1302* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1303* @param nodes Targeted node hostnames to be checked (String or List of strings)
1304* @param useGrains If the, the value will be taken from grains. If false, it will be taken from 'hostname' command.
1305* @return Map Return result Map in format ['nodeName1': 'ipAdress1', 'nodeName2': 'ipAdress2', ...]
1306*/
1307
1308def getIPAddressesForNodenames(saltId, nodes = [], useGrains = true) {
1309 result = [:]
1310
1311 if (nodes instanceof String) {
1312 nodes = [nodes]
1313 }
1314
1315 if (useGrains) {
1316 for (String node in nodes) {
1317 ip = getReturnValues(getGrain(saltId, node, "fqdn_ip4"))["fqdn_ip4"][0]
1318 result[node] = ip
1319 }
1320 } else {
1321 for (String node in nodes) {
1322 ip = getReturnValues(cmdRun(saltId, node, "hostname -i")).readLines()[0]
1323 result[node] = ip
1324 }
1325 }
1326 return result
Martin Polreich4512e2e2019-03-29 12:10:00 +01001327}
1328
1329/**
1330* Checks if required package is installed and returns averaged IO stats for selected disks.
1331* Allows getting averaged values of specific parameter for all disks or a specified disk.
1332* Interval between checks and its number is parametrized and configurable.
1333*
1334* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1335* @param target Node to be targeted (Should only match 1 node)
1336* @param parameterName Name of parameter from 'iostat' output (default = '' -- returns all variables)
1337* @param interval Interval between checks (default = 1)
1338* @param count Number of checks (default = 5)
1339* @param disks Disks to be checked (default = '' -- returns all disks)
1340* @param output Print Salt command return (default = true)
1341* @return Map Map containing desired values in format ['disk':'value']
1342*/
1343
1344def getIostatValues(Map params) {
1345 def common = new com.mirantis.mk.Common()
1346 def ret = [:]
Martin Polreicha7744202019-04-04 16:58:28 +02001347 if (isPackageInstalled(['saltId': params.saltId, 'target': params.target, 'packageName': 'sysstat', 'output': false])) {
Martin Polreich4512e2e2019-03-29 12:10:00 +01001348 def arg = [params.get('interval', 1), params.get('count', 5), params.get('disks', '')]
1349 def res = getReturnValues(runSaltProcessStep(params.saltId, params.target, 'disk.iostat', arg, null, params.output))
1350 if (res instanceof Map) {
1351 for (int i = 0; i < res.size(); i++) {
1352 def key = res.keySet()[i]
1353 if (params.containsKey('parameterName')) {
1354 if (res[key].containsKey(params.parameterName)){
1355 ret[key] = res[key][params.parameterName]
1356 } else {
1357 common.errorMsg("Parameter '${params.parameterName}' not found for disk '${key}'. Valid parameter for this disk are: '${res[key].keySet()}'")
1358 }
1359 } else {
1360 return res // If no parameterName is defined, return all of them.
1361 }
1362 }
1363 }
1364 } else {
1365 common.errorMsg("Package 'sysstat' seems not to be installed on at least one of tageted nodes: ${params.target}. Please fix this to be able to check 'iostat' values. Find more in the docs TODO:<Add docs link>")
1366 }
1367 return ret
1368}
1369
1370/**
1371* Checks if defined package is installed on all nodes defined by target parameter.
1372*
1373* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1374* @param target Node or nodes to be targeted
1375* @param packageName Name of package to be checked
1376* @param output Print Salt command return (default = true)
1377* @return boolean True if package is installed on all defined nodes. False if not found on at least one of defined nodes.
1378*/
1379
1380def isPackageInstalled(Map params) {
1381 def output = params.get('output', true)
Ivan Berezovskiy61a493c2019-08-06 18:50:39 +04001382 def res = runSaltProcessStep(params.saltId, params.target, "pkg.list_pkgs", [], null, output)['return'][0]
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001383 if (res) {
1384 for (int i = 0; i < res.size(); i++) {
1385 def key = res.keySet()[i]
Denis Egorenkofcc4aef2019-10-30 14:07:12 +04001386 if (!(res[key] instanceof Map && res[key].get(params.packageName.toString(), false))) {
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001387 return false
1388 }
Martin Polreich4512e2e2019-03-29 12:10:00 +01001389 }
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001390 return true
1391 } else {
1392 return false
Martin Polreich4512e2e2019-03-29 12:10:00 +01001393 }
azvyagintsev386e94e2019-06-13 13:39:04 +03001394}
Denis Egorenko3621b962019-09-23 16:13:43 +04001395
1396/**
1397* Returns nubmer of worker_threads set for Salt Master
1398*
1399* @param saltId Salt Connection object or pepperEnv
1400*
1401*/
1402def getWorkerThreads(saltId) {
1403 if (env.getEnvironment().containsKey('SALT_MASTER_OPT_WORKER_THREADS')) {
1404 return env['SALT_MASTER_OPT_WORKER_THREADS'].toString()
1405 }
1406 def threads = cmdRun(saltId, "I@salt:master", "cat /etc/salt/master.d/master.conf | grep worker_threads | cut -f 2 -d ':'", true, null, true)
1407 return threads['return'][0].values()[0].replaceAll('Salt command execution success','').trim()
1408}
1409