blob: 30957e58fb526d35086338a6b4fab65faf59ffa5 [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"]
Sergey Galkin7137ad02019-11-07 14:52:13 +0400334 * @param replacing list with maps for deletion in info message (passwords, logins, etc)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100335 * @return output of salt command
336 */
Sergey Galkin7137ad02019-11-07 14:52:13 +0400337def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = [], replacing = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100338 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200339 def originalCmd = cmd
Sergey Galkin7137ad02019-11-07 14:52:13 +0400340 common.infoSensitivityMsg("Running command ${cmd} on ${target}", true, replacing)
Jakub Josef053df392017-05-03 15:51:05 +0200341 if (checkResponse) {
342 cmd = cmd + " && echo Salt command execution success"
343 }
chnyda205a92b2018-01-11 17:07:32 +0100344
Jakub Josef432e9d92018-02-06 18:28:37 +0100345 // add cmd name to salt args list
chnyda205a92b2018-01-11 17:07:32 +0100346 saltArgs << cmd
347
348 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse())
Jakub Josef053df392017-05-03 15:51:05 +0200349 if (checkResponse) {
350 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200351 if (out["return"]){
352 for(int i=0;i<out["return"].size();i++){
353 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200354 for(int j=0;j<node.size();j++){
355 def nodeKey = node.keySet()[j]
Martin Polreicha2effb82018-08-01 11:35:11 +0200356 if (node[nodeKey] instanceof String) {
357 if (!node[nodeKey].contains("Salt command execution success")) {
358 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
359 }
360 } else if (node[nodeKey] instanceof Boolean) {
361 if (!node[nodeKey]) {
362 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
363 }
364 } else {
365 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns unexpected data type: ${node[nodeKey]}")
Jakub Josef053df392017-05-03 15:51:05 +0200366 }
367 }
368 }
Martin Polreicha2effb82018-08-01 11:35:11 +0200369 } else {
Jakub Josef053df392017-05-03 15:51:05 +0200370 throw new Exception("Salt Api response doesn't have return param!")
371 }
372 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200373 if (output == true) {
374 printSaltCommandResult(out)
375 }
376 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100377}
378
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200379/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200380 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200381 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
382 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200383 * @param target Get pillar target
384 * @param minion_name unique identification of a minion in salt-key command output
385 * @param waitUntilPresent return after the minion becomes present (default true)
386 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
387 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200388 * @param maxRetries finite number of iterations to check status of a command (default 200)
389 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200390 * @return output of salt command
391 */
lmercl94189272018-06-01 11:03:46 +0200392def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200393 minion_name = minion_name.replace("*", "")
394 def common = new com.mirantis.mk.Common()
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200395 common.infoMsg("Looking for minion: " + minion_name)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200396 def cmd = 'salt-key | grep ' + minion_name
397 if (waitUntilPresent){
398 def count = 0
399 while(count < maxRetries) {
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200400 try {
401 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
402 if (output) {
403 printSaltCommandResult(out)
404 }
405 def valueMap = out["return"][0]
406 def result = valueMap.get(valueMap.keySet()[0])
407 def resultsArray = result.tokenize("\n")
408 def size = resultsArray.size()
409 if (size >= answers) {
410 return out
411 }
412 count++
413 sleep(time: 1000, unit: 'MILLISECONDS')
414 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
415 } catch (Exception er) {
416 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
417 }
418 }
419 } else {
420 try {
chnydaa0dbb252017-10-05 10:46:09 +0200421 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200422 if (output) {
423 printSaltCommandResult(out)
424 }
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200425 return out
426 } catch (Exception er) {
427 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
Jiri Broulik71512bc2017-08-04 10:00:18 +0200428 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200429 }
430 // otherwise throw exception
431 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
432 throw new Exception("${cmd} signals failure of status check!")
433}
434
435/**
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200436 * Checks if salt minions are in a list of salt master's accepted keys by matching compound
437 * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100438 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
439 * @param target Performs tests on this target node
440 * @param target_minions all targeted minions to test (for ex. I@salt:minion)
441 * @param waitUntilPresent return after the minion becomes present (default true)
442 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
443 * @param output print salt command (default true)
444 * @param maxRetries finite number of iterations to check status of a command (default 200)
445 * @param answers how many minions should return (optional, default 1)
446 * @return output of salt command
447 */
448def 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 +0100449 def target_hosts = getMinionsSorted(saltId, target_minions, batch)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100450 for (t in target_hosts) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200451 def tgt = stripDomainName(t)
452 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
453 }
454}
455
456/**
457 * Checks if salt minions are in a list of salt master's accepted keys by matching a list
458 * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3)
459 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
460 * @param target Performs tests on this target node
461 * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"])
462 * @param waitUntilPresent return after the minion becomes present (default true)
463 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
464 * @param output print salt command (default true)
465 * @param maxRetries finite number of iterations to check status of a command (default 200)
466 * @param answers how many minions should return (optional, default 1)
467 * @return output of salt command
468 */
469def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
470 def common = new com.mirantis.mk.Common()
471 for (tgt in target_minions) {
472 common.infoMsg("Checking if minion " + tgt + " is present")
473 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100474 }
475}
476
477/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200478 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200479 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200480 * @param target Should always be salt-master
Martin Polreich712d85c2019-07-01 17:21:12 +0200481 * @param targetNodes unique identification of a minion or group of salt minions
Jiri Broulik71512bc2017-08-04 10:00:18 +0200482 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Martin Polreich712d85c2019-07-01 17:21:12 +0200483 * @param cmdTimeout timeout for the salt command if minions do not return (default 10)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200484 * @param maxRetries finite number of iterations to check status of a command (default 200)
485 * @return output of salt command
486 */
Martin Polreich712d85c2019-07-01 17:21:12 +0200487
488def minionsReachable(saltId, target, targetNodes, batch=null, cmdTimeout = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200489 def common = new com.mirantis.mk.Common()
Martin Polreich712d85c2019-07-01 17:21:12 +0200490 def cmd = "salt -t${cmdTimeout} -C '${targetNodes}' test.ping"
491 common.infoMsg("Checking if all ${targetNodes} minions are reachable")
492 def retriesCount = 0
493 while(retriesCount < maxRetries) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200494 Calendar timeout = Calendar.getInstance();
Martin Polreich712d85c2019-07-01 17:21:12 +0200495 timeout.add(Calendar.SECOND, cmdTimeout);
496 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, cmdTimeout)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200497 Calendar current = Calendar.getInstance();
498 if (current.getTime().before(timeout.getTime())) {
Martin Polreich712d85c2019-07-01 17:21:12 +0200499 common.infoMsg("Successful response received from all targeted nodes.")
500 printSaltCommandResult(out)
501 return out
Jiri Broulik71512bc2017-08-04 10:00:18 +0200502 }
Martin Polreich712d85c2019-07-01 17:21:12 +0200503 def outYaml = readYaml text: getReturnValues(out)
504 def successfulNodes = []
505 def failedNodes = []
506 for (node in outYaml.keySet()) {
507 if (outYaml[node] == true || outYaml[node].toString().toLowerCase() == 'true') {
508 successfulNodes.add(node)
509 } else {
510 failedNodes.add(node)
511 }
512 }
513 common.infoMsg("Not all of the targeted minions returned yet. Successful response from ${successfulNodes}. Still waiting for ${failedNodes}.")
514 retriesCount++
Jiri Broulik71512bc2017-08-04 10:00:18 +0200515 sleep(time: 500, unit: 'MILLISECONDS')
516 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200517}
518
Martin Polreich712d85c2019-07-01 17:21:12 +0200519
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200520/**
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400521 * You can call this function when need to check that all minions are available, free and ready for command execution
522 * @param config LinkedHashMap config parameter, which contains next:
523 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
524 * @param target unique identification of a minion or group of salt minions
525 * @param target_reachable unique identification of a minion or group of salt minions to check availability
526 * @param wait timeout between retries to check target minions (default 5)
527 * @param retries finite number of iterations to check minions (default 10)
528 * @param timeout timeout for the salt command if minions do not return (default 5)
529 * @param availability check that minions also are available before checking readiness (default true)
530 */
531def checkTargetMinionsReady(LinkedHashMap config) {
532 def common = new com.mirantis.mk.Common()
533 def saltId = config.get('saltId')
534 def target = config.get('target')
535 def target_reachable = config.get('target_reachable', target)
536 def wait = config.get('wait', 30)
537 def retries = config.get('retries', 10)
538 def timeout = config.get('timeout', 5)
539 def checkAvailability = config.get('availability', true)
Martin Polreichf7976952019-03-04 10:06:11 +0100540 def batch = config.get('batch', null)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400541 common.retry(retries, wait) {
542 if (checkAvailability) {
Martin Polreichf7976952019-03-04 10:06:11 +0100543 minionsReachable(saltId, 'I@salt:master', target_reachable, batch)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400544 }
Martin Polreichf7976952019-03-04 10:06:11 +0100545 def running = runSaltProcessStep(saltId, target, 'saltutil.running', [], batch, true, timeout)
Denis Egorenkoa1edaba2019-02-27 19:19:12 +0400546 for (value in running.get("return")[0].values()) {
547 if (value != []) {
548 throw new Exception("Not all salt-minions are ready for execution")
549 }
550 }
551 }
552}
553
554/**
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300555 * Restart and wait for salt-minions on target nodes.
556 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
557 * @param target unique identification of a minion or group of salt minions
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400558 * @param wait timeout for the salt command if minions do not return (default 10)
559 * @param maxRetries finite number of iterations to check status of a command (default 15)
560 * @param async Run salt minion restart and do not wait for response
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300561 * @return output of salt command
562 */
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400563def restartSaltMinion(saltId, target, wait = 10, maxRetries = 15, async = true) {
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300564 def common = new com.mirantis.mk.Common()
565 common.infoMsg("Restarting salt-minion on ${target} and waiting for they are reachable.")
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400566 runSaltProcessStep(saltId, target, 'cmd.shell', ['salt-call service.restart salt-minion'], null, true, 60, null, async)
567 checkTargetMinionsReady(['saltId': saltId, 'target': target, timeout: wait, retries: maxRetries])
Vasyl Saienko121f34c2019-06-24 23:39:32 +0300568 common.infoMsg("All ${target} minions are alive...")
569}
570
571/**
572 * Upgrade package and restart salt minion.
573 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
574 * @param target unique identification of a minion or group of salt minions
575 * @param the name of pkg_name to upgrade
576 * @param wait timeout for the salt command if minions do not return (default 5)
577 * @param maxRetries finite number of iterations to check status of a command (default 10)
578 * @return output of salt command
579 */
580def upgradePackageAndRestartSaltMinion(saltId, target, pkg_name, wait = 5, maxRetries = 10) {
581 def common = new com.mirantis.mk.Common()
582 def latest_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.latest_version', [pkg_name, 'show_installed=True'])).split('\n')[0]
583 def current_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.version', [pkg_name])).split('\n')[0]
584 if (current_version && latest_version != current_version) {
585 common.infoMsg("Upgrading current ${pkg_name}: ${current_version} to ${latest_version}")
586 runSaltProcessStep(saltId, target, 'pkg.install', [pkg_name], 'only_upgrade=True')
587 restartSaltMinion(saltId, target, wait, maxRetries)
588 }
589}
590
591/**
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200592 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200593 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200594 * @param target Get pillar target
595 * @param cmd name of a service
596 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200597 * @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 +0200598 * @param waitUntilOk return after the minion becomes present (optional, default true)
599 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
600 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200601 * @param maxRetries finite number of iterations to check status of a command (default 200)
602 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200603 * @return output of salt command
604 */
chnydaa0dbb252017-10-05 10:46:09 +0200605def 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 +0200606 def common = new com.mirantis.mk.Common()
607 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
608 if (waitUntilOk){
609 def count = 0
610 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200611 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200612 if (output) {
613 printSaltCommandResult(out)
614 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200615 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200616 def success = 0
617 if (answers == 0){
618 answers = resultMap.size()
619 }
620 for (int i=0;i<answers;i++) {
621 result = resultMap.get(resultMap.keySet()[i])
622 // if the goal is to find some string in output of the command
623 if (find) {
624 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
625 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
626 success++
627 if (success == answers) {
628 return out
629 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200630 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200631 // else the goal is to not find any string in output of the command
632 } else {
633 if(result instanceof String && result.isEmpty()) {
634 success++
635 if (success == answers) {
636 return out
chnydaa0dbb252017-10-05 10:46:09 +0200637 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200638 }
639 }
640 }
641 count++
642 sleep(time: 500, unit: 'MILLISECONDS')
643 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
644 }
645 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200646 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200647 def resultMap = out["return"][0]
648 if (output) {
649 printSaltCommandResult(out)
650 }
651 for (int i=0;i<resultMap.size();i++) {
652 result = resultMap.get(resultMap.keySet()[i])
653 // if the goal is to find some string in output of the command
654 if (find) {
655 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
656 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200657 return out
658 }
659
660 // else the goal is to not find any string in output of the command
661 } else {
662 if(result instanceof String && result.isEmpty()) {
663 return out
664 }
665 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200666 }
667 }
668 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200669 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200670 throw new Exception("${cmd} signals failure of status check!")
671}
672
Jakub Josef5ade54c2017-03-10 16:14:01 +0100673/**
674 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200675 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100676 * @param target Get pillar target
Martin Polreichf7976952019-03-04 10:06:11 +0100677 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100678 * @return output of salt command
679 */
Martin Polreichf7976952019-03-04 10:06:11 +0100680def syncAll(saltId, target, batch = null) {
681 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all', batch)
Jakub Josef79ecec32017-02-17 14:36:28 +0100682}
683
Jakub Josef5ade54c2017-03-10 16:14:01 +0100684/**
Jakub Josef432e9d92018-02-06 18:28:37 +0100685 * Perform complete salt refresh between master and target
686 * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all
687 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
688 * @param target Get pillar target
Martin Polreichf7976952019-03-04 10:06:11 +0100689 * @param batch Batch param to salt (integer or string with percents)
Ivan Berezovskiy19063902020-03-19 13:25:30 +0400690 * @param oneByOne Refresh each node separately
Jakub Josef432e9d92018-02-06 18:28:37 +0100691 * @return output of salt command
692 */
Ivan Berezovskiy19063902020-03-19 13:25:30 +0400693def fullRefresh(saltId, target, batch=20, oneByOne=false) {
694 if (oneByOne) {
695 def minions = getMinions(saltId, target)
696 for (minion in minions) {
697 runSaltProcessStep(saltId, minion, 'saltutil.refresh_pillar', [], null, true, 60)
698 runSaltProcessStep(saltId, minion, 'saltutil.refresh_grains', [], null, true, 60)
699 runSaltProcessStep(saltId, minion, 'saltutil.sync_all', [], null, true, 180)
700 }
701 } else {
702 runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], batch, true)
703 runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], batch, true)
704 runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], batch, true)
705 }
Jakub Josef432e9d92018-02-06 18:28:37 +0100706}
707
708/**
709 * Enforce highstate on given targets
710 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
711 * @param target Highstate enforcing target
712 * @param excludedStates states which will be excluded from main state (default empty string)
713 * @param output print output (optional, default true)
714 * @param failOnError throw exception on salt state result:false (optional, default true)
715 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
716 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
717 * @return output of salt command
718 */
719def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) {
720 saltArgs << "exclude=${excludedStates}"
721 return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs)
722}
723/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100724 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200725 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100726 * @param target Highstate enforcing target
727 * @param output print output (optional, default true)
728 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200729 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100730 * @return output of salt command
731 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100732def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) {
Petr Jediný30be7032018-05-29 18:22:46 +0200733 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000734 def common = new com.mirantis.mk.Common()
735
Marek Celoud63366112017-07-25 17:27:24 +0200736 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000737
Jakub Josef374beb72017-04-27 15:45:09 +0200738 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100739 return out
740}
741
Jakub Josef5ade54c2017-03-10 16:14:01 +0100742/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100743 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200744 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100745 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100746 * @param batch Batch param to salt (integer or string with percents)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100747 * @return list of active minions fitin
748 */
Martin Polreichf7976952019-03-04 10:06:11 +0100749def getMinions(saltId, target, batch = null) {
750 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping', batch)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100751 return new ArrayList<String>(minionsRaw['return'][0].keySet())
752}
753
Jiri Broulikf8f96942018-02-15 10:03:42 +0100754/**
755 * Get sorted 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 list of sorted active minions fitin
760 */
Martin Polreichf7976952019-03-04 10:06:11 +0100761def getMinionsSorted(saltId, target, batch = null) {
762 return getMinions(saltId, target, batch).sort()
Jiri Broulikf8f96942018-02-15 10:03:42 +0100763}
764
765/**
766 * Get first out of running minions IDs according to the target
767 * @param saltId Salt Connection object or pepperEnv
768 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100769 * @param batch Batch param to salt (integer or string with percents)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100770 * @return first of active minions fitin
771 */
Martin Polreichf7976952019-03-04 10:06:11 +0100772def getFirstMinion(saltId, target, batch = null) {
773 def minionsSorted = getMinionsSorted(saltId, target, batch)
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400774 return minionsSorted[0]
Jiri Broulikf8f96942018-02-15 10:03:42 +0100775}
776
777/**
778 * Get running salt minions IDs without it's domain name part and its numbering identifications
779 * @param saltId Salt Connection object or pepperEnv
780 * @param target Get minions target
Martin Polreichf7976952019-03-04 10:06:11 +0100781 * @param batch Batch param to salt (integer or string with percents)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100782 * @return list of active minions fitin without it's domain name part name numbering
783 */
Martin Polreichf7976952019-03-04 10:06:11 +0100784def getMinionsGeneralName(saltId, target, batch = null) {
785 def minionsSorted = getMinionsSorted(saltId, target, batch)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100786 return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "")
787}
788
789/**
790 * Get domain name of the env
791 * @param saltId Salt Connection object or pepperEnv
792 * @return domain name
793 */
794def getDomainName(saltId) {
795 return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain'))
796}
797
798/**
799 * Remove domain name from Salt minion ID
800 * @param name String of Salt minion ID
801 * @return Salt minion ID without its domain name
802 */
803def stripDomainName(name) {
804 return name.split("\\.")[0]
805}
806
807/**
808 * Gets return values of a salt command
809 * @param output String of Salt minion ID
810 * @return Return values of a salt command
811 */
812def getReturnValues(output) {
Martin Polreichf7976952019-03-04 10:06:11 +0100813 if(output && output.containsKey("return") && !output.get("return").isEmpty()) {
Jiri Broulikf8f96942018-02-15 10:03:42 +0100814 return output['return'][0].values()[0]
815 }
816 def common = new com.mirantis.mk.Common()
817 common.errorMsg('output does not contain return key')
818 return ''
819}
820
821/**
822 * Get minion ID of one of KVM nodes
823 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
824 * @return Salt minion ID of one of KVM nodes in env
825 */
826def getKvmMinionId(saltId) {
827 return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0]
828}
829
830/**
831 * Get Salt minion ID of KVM node hosting 'name' VM
832 * @param saltId Salt Connection object or pepperEnv
833 * @param name Name of the VM (for ex. ctl01)
834 * @return Salt minion ID of KVM node hosting 'name' VM
835 */
Jiri Broulikd2a50552018-04-25 17:17:59 +0200836def getNodeProvider(saltId, nodeName) {
837 def salt = new com.mirantis.mk.Salt()
838 def common = new com.mirantis.mk.Common()
839 def kvms = salt.getMinions(saltId, 'I@salt:control')
840 for (kvm in kvms) {
841 try {
842 vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true))
843 if (vms.toString().contains(nodeName)) {
844 return kvm
845 }
846 } catch (Exception er) {
847 common.infoMsg("${nodeName} not present on ${kvm}")
848 }
849 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100850}
851
Ales Komarek5276ebe2017-03-16 08:46:34 +0100852/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200853 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200854 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200855 * @param target Target to test
Martin Polreichf7976952019-03-04 10:06:11 +0100856 * @param batch Batch param to salt (integer or string with percents)
vrovachev1c4770b2017-07-05 13:25:21 +0400857 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200858 */
859
Martin Polreichf7976952019-03-04 10:06:11 +0100860def testTarget(saltId, target, batch = null) {
861 return getMinions(saltId, target, batch).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200862}
863
864/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100865 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200866 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100867 * @param target Key generating target
868 * @param host Key generating host
869 * @param keysize generated key size (optional, default 4096)
Martin Polreichf7976952019-03-04 10:06:11 +0100870 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100871 * @return output of salt command
872 */
Martin Polreichf7976952019-03-04 10:06:11 +0100873def generateNodeKey(saltId, target, host, keysize = 4096, batch = null) {
874 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', batch, [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100875}
876
Jakub Josef5ade54c2017-03-10 16:14:01 +0100877/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200878 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200879 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100880 * @param target Metadata generating target
881 * @param host Metadata generating host
882 * @param classes Reclass classes
883 * @param parameters Reclass parameters
Martin Polreichf7976952019-03-04 10:06:11 +0100884 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100885 * @return output of salt command
886 */
Martin Polreichf7976952019-03-04 10:06:11 +0100887def generateNodeMetadata(saltId, target, host, classes, parameters, batch = null) {
888 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', batch, [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100889}
890
Jakub Josef5ade54c2017-03-10 16:14:01 +0100891/**
892 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200893 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100894 * @param target Orchestration target
895 * @param orchestrate Salt orchestrate params
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200896 * @param kwargs Salt orchestrate params
Martin Polreichf7976952019-03-04 10:06:11 +0100897 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100898 * @return output of salt command
899 */
Martin Polreichf7976952019-03-04 10:06:11 +0100900def orchestrateSystem(saltId, target, orchestrate=[], kwargs = null, batch = null) {
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300901 //Since the runSaltCommand uses "arg" (singular) for "runner" client this won`t work correctly on old salt 2016
902 //cause this version of salt used "args" (plural) for "runner" client, see following link for reference:
903 //https://github.com/saltstack/salt/pull/32938
Oleksii Grudev0c098382018-08-08 16:16:38 +0300904 def common = new com.mirantis.mk.Common()
Martin Polreichf7976952019-03-04 10:06:11 +0100905 def result = runSaltCommand(saltId, 'runner', target, 'state.orchestrate', batch, orchestrate, kwargs, 7200, 7200)
Oleksii Grudev0c098382018-08-08 16:16:38 +0300906 if(result != null){
907 if(result['return']){
908 def retcode = result['return'][0].get('retcode')
909 if (retcode != 0) {
910 throw new Exception("Orchestration state failed while running: "+orchestrate)
911 }else{
912 common.infoMsg("Orchestrate state "+orchestrate+" succeeded")
913 }
914 }else{
915 common.errorMsg("Salt result has no return attribute! Result: ${result}")
916 }
917 }else{
918 common.errorMsg("Cannot check salt result, given result is null")
919 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100920}
921
Jakub Josef5ade54c2017-03-10 16:14:01 +0100922/**
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200923 * Run salt pre or post orchestrate tasks
924 *
925 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
926 * @param pillar_tree Reclass pillar that has orchestrate pillar for desired stage
927 * @param extra_tgt Extra targets for compound
Martin Polreichf7976952019-03-04 10:06:11 +0100928 * @param batch Batch param to salt (integer or string with percents)
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200929 * @return output of salt command
930 */
Martin Polreichf7976952019-03-04 10:06:11 +0100931def orchestratePrePost(saltId, pillar_tree, extra_tgt = '', batch = null) {
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200932
933 def common = new com.mirantis.mk.Common()
934 def salt = new com.mirantis.mk.Salt()
935 def compound = 'I@' + pillar_tree + " " + extra_tgt
936
937 common.infoMsg("Refreshing pillars")
Martin Polreichf7976952019-03-04 10:06:11 +0100938 runSaltProcessStep(saltId, '*', 'saltutil.refresh_pillar', [], batch, true)
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200939
940 common.infoMsg("Looking for orchestrate pillars")
Martin Polreichf7976952019-03-04 10:06:11 +0100941 if (salt.testTarget(saltId, compound, batch)) {
942 for ( node in salt.getMinionsSorted(saltId, compound, batch) ) {
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200943 def pillar = salt.getPillar(saltId, node, pillar_tree)
944 if ( !pillar['return'].isEmpty() ) {
945 for ( orch_id in pillar['return'][0].values() ) {
946 def orchestrator = orch_id.values()['orchestrator']
947 def orch_enabled = orch_id.values()['enabled']
948 if ( orch_enabled ) {
949 common.infoMsg("Orchestrating: ${orchestrator}")
Martin Polreichf7976952019-03-04 10:06:11 +0100950 salt.printSaltCommandResult(salt.orchestrateSystem(saltId, ['expression': node], [orchestrator], null, batch))
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200951 }
952 }
953 }
954 }
955 }
956}
957
958/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100959 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200960 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100961 * @param tgt Salt process step target
962 * @param fun Salt process step function
963 * @param arg process step arguments (optional, default [])
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400964 * @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 +0100965 * @param output print output (optional, default true)
Jiri Broulik48544be2017-06-14 18:33:54 +0200966 * @param timeout Additional argument salt api timeout
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400967 * @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 +0100968 * @return output of salt command
969 */
Ivan Berezovskiy768dabd2019-08-01 15:52:44 +0400970def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null, async = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100971 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200972 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100973 def out
974
Marek Celoud63366112017-07-25 17:27:24 +0200975 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Martin Polreichf7976952019-03-04 10:06:11 +0100976 if (async == true) {
977 out = runSaltCommand(saltId, 'local_async', ['expression': tgt, 'type': 'compound'], fun, null, arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100978 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200979 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100980 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100981
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100982 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200983 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100984 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200985 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100986}
987
988/**
989 * Check result for errors and throw exception if any found
990 *
991 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200992 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200993 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200994 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef432e9d92018-02-06 18:28:37 +0100995 * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false)
Jakub Josef79ecec32017-02-17 14:36:28 +0100996 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100997def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100998 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100999 if(result != null){
1000 if(result['return']){
1001 for (int i=0;i<result['return'].size();i++) {
1002 def entry = result['return'][i]
1003 if (!entry) {
1004 if (failOnError) {
1005 throw new Exception("Salt API returned empty response: ${result}")
1006 } else {
1007 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +01001008 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001009 }
1010 for (int j=0;j<entry.size();j++) {
1011 def nodeKey = entry.keySet()[j]
1012 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +02001013 def outputResources = []
Jakub Josef47145942018-04-04 17:30:38 +02001014 def errorResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001015 common.infoMsg("Node ${nodeKey} changes:")
1016 if(node instanceof Map || node instanceof List){
1017 for (int k=0;k<node.size();k++) {
1018 def resource;
1019 def resKey;
1020 if(node instanceof Map){
1021 resKey = node.keySet()[k]
Victor Ryzhenkin49d67812019-01-09 15:28:21 +04001022 if (resKey == "retcode") {
Richard Felkld9476ac2018-07-12 19:01:33 +02001023 continue
Victor Ryzhenkin49d67812019-01-09 15:28:21 +04001024 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001025 }else if(node instanceof List){
1026 resKey = k
1027 }
1028 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +02001029 // print
Jakub Josefa87941c2017-04-20 17:14:58 +02001030 if(printResults){
1031 if(resource instanceof Map && resource.keySet().contains("result")){
1032 //clean unnesaccary fields
1033 if(resource.keySet().contains("__run_num__")){
1034 resource.remove("__run_num__")
1035 }
1036 if(resource.keySet().contains("__id__")){
1037 resource.remove("__id__")
1038 }
1039 if(resource.keySet().contains("pchanges")){
1040 resource.remove("pchanges")
1041 }
1042 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
1043 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +02001044 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001045 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +02001046 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001047 }
1048 }else{
Ivan Berezovskiy65fb6372019-08-09 19:49:55 +04001049 if(!printOnlyChanges || (resource.changes && resource.changes.size() > 0)) {
Jakub Josefbceaa322017-06-13 18:28:27 +02001050 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001051 }
1052 }
1053 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +02001054 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001055 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001056 }
Jakub Josefc4c40202017-04-28 12:04:24 +02001057 common.debugMsg("checkResult: checking resource: ${resource}")
1058 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josef47145942018-04-04 17:30:38 +02001059 errorResources.add(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +02001060 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001061 }
Jakub Josefa87941c2017-04-20 17:14:58 +02001062 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +02001063 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +02001064 }
1065 if(printResults && !outputResources.isEmpty()){
Jakub Josef47145942018-04-04 17:30:38 +02001066 println outputResources.stream().collect(Collectors.joining("\n"))
1067 }
1068 if(!errorResources.isEmpty()){
1069 for(resource in errorResources){
1070 def prettyResource = common.prettify(resource)
1071 if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") {
1072 timeout(time:1, unit:'HOURS') {
1073 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
1074 }
1075 } else {
1076 def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}"
1077 if (failOnError) {
1078 throw new Exception(errorMsg)
1079 } else {
1080 common.errorMsg(errorMsg)
1081 }
1082 }
1083 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001084 }
1085 }
Jakub Josef52f69f72017-03-14 15:18:08 +01001086 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001087 }else{
1088 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +01001089 }
Jakub Josef52f69f72017-03-14 15:18:08 +01001090 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +02001091 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +01001092 }
1093}
1094
1095/**
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001096* Parse salt API output to check minion restart and wait some time to be sure minion is up.
1097* See https://mirantis.jira.com/browse/PROD-16258 for more details
1098* TODO: change sleep to more tricky procedure.
1099*
1100* @param result Parsed response of Salt API
1101*/
Vasyl Saienko6a396212018-06-08 09:20:08 +03001102def waitForMinion(result, minionRestartWaitTimeout=10) {
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001103 def common = new com.mirantis.mk.Common()
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001104 //In order to prevent multiple sleeps use bool variable to catch restart for any minion.
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001105 def isMinionRestarted = false
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001106 if(result != null){
1107 if(result['return']){
1108 for (int i=0;i<result['return'].size();i++) {
1109 def entry = result['return'][i]
1110 // exit in case of empty response.
1111 if (!entry) {
1112 return
1113 }
1114 // Loop for nodes
1115 for (int j=0;j<entry.size();j++) {
1116 def nodeKey = entry.keySet()[j]
1117 def node=entry[nodeKey]
1118 if(node instanceof Map || node instanceof List){
1119 // Loop for node resources
1120 for (int k=0;k<node.size();k++) {
1121 def resource;
1122 def resKey;
1123 if(node instanceof Map){
1124 resKey = node.keySet()[k]
1125 }else if(node instanceof List){
1126 resKey = k
1127 }
1128 resource = node[resKey]
Jakub Joseffb9996d2018-04-10 14:05:31 +02001129 // try to find if salt_minion service was restarted
1130 if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){
Oleg Iurchenko3eedc782017-12-12 11:49:29 +02001131 if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){
1132 if(resource.changes.size() > 0){
1133 isMinionRestarted=true
1134 }
1135 }
1136 }
1137 }
1138 }
1139 }
1140 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001141 }
1142 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001143 if (isMinionRestarted){
Vasyl Saienko6a396212018-06-08 09:20:08 +03001144 common.infoMsg("Salt minion service restart detected. Sleep ${minionRestartWaitTimeout} seconds to wait minion restart")
1145 sleep(minionRestartWaitTimeout)
Oleg Iurchenko7eb21502017-11-28 18:53:43 +02001146 }
1147}
1148
1149/**
Jakub Josef7852fe12017-03-15 16:02:41 +01001150 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +01001151 *
1152 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +01001153 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +01001154def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +01001155 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001156 if(result != null){
1157 if(result['return']){
1158 for (int i=0; i<result['return'].size(); i++) {
1159 def entry = result['return'][i]
1160 for (int j=0; j<entry.size(); j++) {
1161 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
1162 def nodeKey = entry.keySet()[j]
1163 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +02001164 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001165 }
Jakub Josef8a715bf2017-03-14 21:39:01 +01001166 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001167 }else{
1168 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +01001169 }
Jakub Josef8a715bf2017-03-14 21:39:01 +01001170 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +01001171 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +01001172 }
Jakub Josef79ecec32017-02-17 14:36:28 +01001173}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001174
1175
1176/**
1177 * Return content of file target
1178 *
chnydaa0dbb252017-10-05 10:46:09 +02001179 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001180 * @param target Compound target (should target only one host)
1181 * @param file File path to read (/etc/hosts for example)
1182 */
1183
Pavlo Shchelokovskyy97100072018-10-04 11:53:44 +03001184def getFileContent(saltId, target, file, checkResponse = true, batch=null, output = true, saltArgs = []) {
1185 result = cmdRun(saltId, target, "cat ${file}", checkResponse, batch, output, saltArgs)
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +02001186 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001187}
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001188
1189/**
1190 * Set override parameters in Salt cluster metadata
1191 *
chnydaa0dbb252017-10-05 10:46:09 +02001192 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001193 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +03001194 * @param reclass_dir Directory where Reclass git repo is located
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +02001195 * @param extra_tgt Extra targets for compound
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001196 */
1197
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001198def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass", extra_tgt = '') {
Tomáš Kukrálf178f052017-07-11 11:31:00 +02001199 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +03001200 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +02001201 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001202 def key = entry[0]
1203 def value = entry[1]
1204
1205 common.debugMsg("Set salt override ${key}=${value}")
Victor Ryzhenkin2f997302019-01-10 15:12:55 +04001206 runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'reclass.cluster_meta_set', ["name=${key}", "value=${value}"], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001207 }
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001208 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 +03001209}
Oleg Grigorovbec45582017-09-12 20:29:24 +03001210
1211/**
1212* Execute salt commands via salt-api with
1213* CLI client salt-pepper
1214*
1215* @param data Salt command map
1216* @param venv Path to virtualenv with
1217*/
1218
azvyagintsev386e94e2019-06-13 13:39:04 +03001219def runPepperCommand(data, venv) {
Jakub Josef03d4d5a2017-12-20 16:35:09 +01001220 def common = new com.mirantis.mk.Common()
Oleg Grigorovbec45582017-09-12 20:29:24 +03001221 def python = new com.mirantis.mk.Python()
1222 def dataStr = new groovy.json.JsonBuilder(data).toString()
azvyagintsev386e94e2019-06-13 13:39:04 +03001223 // TODO(alexz): parametrize?
1224 int retry = 10
chnyda4901a042017-11-16 12:14:56 +01001225
Jakub Josefa2491ad2018-01-15 16:26:27 +01001226 def pepperCmdFile = "${venv}/pepper-cmd.json"
1227 writeFile file: pepperCmdFile, text: dataStr
1228 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}"
Oleg Grigorovbec45582017-09-12 20:29:24 +03001229
azvyagintsev386e94e2019-06-13 13:39:04 +03001230 int tries = 0
1231 def FullOutput = ['status': 1]
Jakub Josef37cd4972018-02-01 16:25:25 +01001232 def outputObj
azvyagintsev386e94e2019-06-13 13:39:04 +03001233 while (tries++ < retry) {
1234 try {
1235 if (venv) {
1236 FullOutput = python.runVirtualenvCommand(venv, pepperCmd, true, true)
1237 } else {
1238 FullOutput = common.shCmdStatus(pepperCmd)
1239 }
1240 if (FullOutput['status'] != 0) {
1241 error()
1242 }
1243 break
1244 } catch (e) {
1245 // Check , if we get failed pepper HTTP call, and retry
1246 common.errorMsg("Command: ${pepperCmd} failed to execute with error:\n${FullOutput['stderr']}")
1247 if (FullOutput['stderr'].contains('Error with request: HTTP Error 50') || FullOutput['stderr'].contains('Pepper error: Server error')) {
1248 common.errorMsg("Pepper HTTP Error detected. Most probably, " +
1249 "master SaltReqTimeoutError in master zmq thread issue...lets retry ${tries}/${retry}")
1250 sleep(5)
1251 continue
1252 }
1253 }
1254 }
1255 // 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 +01001256 try {
azvyagintsev386e94e2019-06-13 13:39:04 +03001257 outputObj = new groovy.json.JsonSlurperClassic().parseText(FullOutput['stdout'])
1258 } catch (Exception jsonE) {
1259 common.errorMsg('Parsing Salt API JSON response failed! Response: ' + FullOutput)
1260 throw jsonE
Jakub Josef37cd4972018-02-01 16:25:25 +01001261 }
1262 return outputObj
Oleg Grigorovbec45582017-09-12 20:29:24 +03001263}
Martin Polreich232ad902019-01-21 14:31:00 +01001264
azvyagintsev386e94e2019-06-13 13:39:04 +03001265
Martin Polreich232ad902019-01-21 14:31:00 +01001266/**
1267* Check time settings on defined nodes, compares them
1268* and evaluates the results
1269*
1270* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1271* @param target Targeted nodes to be checked
1272* @param diff Maximum time difference (in seconds) to be accepted during time sync check
Martin Polreichf7976952019-03-04 10:06:11 +01001273* @param batch Batch param to salt (integer or string with percents)
Martin Polreich232ad902019-01-21 14:31:00 +01001274* @return bool Return true if time difference is <= diff and returns false if time difference is > diff
1275*/
1276
Martin Polreichf7976952019-03-04 10:06:11 +01001277def checkClusterTimeSync(saltId, target, batch = null) {
Martin Polreich232ad902019-01-21 14:31:00 +01001278 def common = new com.mirantis.mk.Common()
1279 def salt = new com.mirantis.mk.Salt()
1280
1281 times = []
1282 try {
1283 diff = salt.getReturnValues(salt.getPillar(saltId, 'I@salt:master', 'linux:system:time_diff'))
1284 if (diff != null && diff != "" && diff.isInteger()) {
1285 diff = diff.toInteger()
1286 } else {
1287 diff = 5
1288 }
Martin Polreichf7976952019-03-04 10:06:11 +01001289 out = salt.runSaltProcessStep(saltId, target, 'status.time', '%s', batch)
Martin Polreich232ad902019-01-21 14:31:00 +01001290 outParsed = out['return'][0]
1291 def outKeySet = outParsed.keySet()
1292 for (key in outKeySet) {
1293 def time = outParsed[key].readLines().get(0)
1294 common.infoMsg(time)
1295 if (time.isInteger()) {
1296 times.add(time.toInteger())
1297 }
1298 }
1299 if ((times.max() - times.min()) <= diff) {
1300 return true
1301 } else {
1302 return false
1303 }
1304 } catch(Exception e) {
1305 common.errorMsg("Could not check cluster time sync.")
1306 return false
1307 }
1308}
Martin Polreichb577f2d2019-02-27 09:28:35 +01001309
1310/**
1311* Finds out IP address of the given node or a list of nodes
1312*
1313* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1314* @param nodes Targeted node hostnames to be checked (String or List of strings)
1315* @param useGrains If the, the value will be taken from grains. If false, it will be taken from 'hostname' command.
1316* @return Map Return result Map in format ['nodeName1': 'ipAdress1', 'nodeName2': 'ipAdress2', ...]
1317*/
1318
1319def getIPAddressesForNodenames(saltId, nodes = [], useGrains = true) {
1320 result = [:]
1321
1322 if (nodes instanceof String) {
1323 nodes = [nodes]
1324 }
1325
1326 if (useGrains) {
1327 for (String node in nodes) {
1328 ip = getReturnValues(getGrain(saltId, node, "fqdn_ip4"))["fqdn_ip4"][0]
1329 result[node] = ip
1330 }
1331 } else {
1332 for (String node in nodes) {
1333 ip = getReturnValues(cmdRun(saltId, node, "hostname -i")).readLines()[0]
1334 result[node] = ip
1335 }
1336 }
1337 return result
Martin Polreich4512e2e2019-03-29 12:10:00 +01001338}
1339
1340/**
1341* Checks if required package is installed and returns averaged IO stats for selected disks.
1342* Allows getting averaged values of specific parameter for all disks or a specified disk.
1343* Interval between checks and its number is parametrized and configurable.
1344*
1345* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1346* @param target Node to be targeted (Should only match 1 node)
1347* @param parameterName Name of parameter from 'iostat' output (default = '' -- returns all variables)
1348* @param interval Interval between checks (default = 1)
1349* @param count Number of checks (default = 5)
1350* @param disks Disks to be checked (default = '' -- returns all disks)
1351* @param output Print Salt command return (default = true)
1352* @return Map Map containing desired values in format ['disk':'value']
1353*/
1354
1355def getIostatValues(Map params) {
1356 def common = new com.mirantis.mk.Common()
1357 def ret = [:]
Martin Polreicha7744202019-04-04 16:58:28 +02001358 if (isPackageInstalled(['saltId': params.saltId, 'target': params.target, 'packageName': 'sysstat', 'output': false])) {
Martin Polreich4512e2e2019-03-29 12:10:00 +01001359 def arg = [params.get('interval', 1), params.get('count', 5), params.get('disks', '')]
1360 def res = getReturnValues(runSaltProcessStep(params.saltId, params.target, 'disk.iostat', arg, null, params.output))
1361 if (res instanceof Map) {
1362 for (int i = 0; i < res.size(); i++) {
1363 def key = res.keySet()[i]
1364 if (params.containsKey('parameterName')) {
1365 if (res[key].containsKey(params.parameterName)){
1366 ret[key] = res[key][params.parameterName]
1367 } else {
1368 common.errorMsg("Parameter '${params.parameterName}' not found for disk '${key}'. Valid parameter for this disk are: '${res[key].keySet()}'")
1369 }
1370 } else {
1371 return res // If no parameterName is defined, return all of them.
1372 }
1373 }
1374 }
1375 } else {
1376 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>")
1377 }
1378 return ret
1379}
1380
1381/**
1382* Checks if defined package is installed on all nodes defined by target parameter.
1383*
1384* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
1385* @param target Node or nodes to be targeted
1386* @param packageName Name of package to be checked
1387* @param output Print Salt command return (default = true)
1388* @return boolean True if package is installed on all defined nodes. False if not found on at least one of defined nodes.
1389*/
1390
1391def isPackageInstalled(Map params) {
1392 def output = params.get('output', true)
Ivan Berezovskiy61a493c2019-08-06 18:50:39 +04001393 def res = runSaltProcessStep(params.saltId, params.target, "pkg.list_pkgs", [], null, output)['return'][0]
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001394 if (res) {
1395 for (int i = 0; i < res.size(); i++) {
1396 def key = res.keySet()[i]
Denis Egorenkofcc4aef2019-10-30 14:07:12 +04001397 if (!(res[key] instanceof Map && res[key].get(params.packageName.toString(), false))) {
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001398 return false
1399 }
Martin Polreich4512e2e2019-03-29 12:10:00 +01001400 }
Ivan Berezovskiy775a5532019-07-26 16:44:22 +04001401 return true
1402 } else {
1403 return false
Martin Polreich4512e2e2019-03-29 12:10:00 +01001404 }
azvyagintsev386e94e2019-06-13 13:39:04 +03001405}
Denis Egorenko3621b962019-09-23 16:13:43 +04001406
1407/**
1408* Returns nubmer of worker_threads set for Salt Master
1409*
1410* @param saltId Salt Connection object or pepperEnv
1411*
1412*/
1413def getWorkerThreads(saltId) {
1414 if (env.getEnvironment().containsKey('SALT_MASTER_OPT_WORKER_THREADS')) {
1415 return env['SALT_MASTER_OPT_WORKER_THREADS'].toString()
1416 }
1417 def threads = cmdRun(saltId, "I@salt:master", "cat /etc/salt/master.d/master.conf | grep worker_threads | cut -f 2 -d ':'", true, null, true)
1418 return threads['return'][0].values()[0].replaceAll('Salt command execution success','').trim()
1419}
1420