blob: 2273ebd956504b6c233488f2f3531c07e4bdc658 [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
2
Jakub Josefbceaa322017-06-13 18:28:27 +02003import com.cloudbees.groovy.cps.NonCPS
Jakub Josefb77c0812017-03-27 14:11:01 +02004import java.util.stream.Collectors
Jakub Josef79ecec32017-02-17 14:36:28 +01005/**
6 * Salt functions
7 *
8*/
9
10/**
11 * Salt connection and context parameters
12 *
13 * @param url Salt API server URL
14 * @param credentialsID ID of credentials store entry
15 */
16def connection(url, credentialsId = "salt") {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010017 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +010018 params = [
19 "url": url,
20 "credentialsId": credentialsId,
21 "authToken": null,
22 "creds": common.getCredentials(credentialsId)
23 ]
24 params["authToken"] = saltLogin(params)
Jakub Josef79ecec32017-02-17 14:36:28 +010025 return params
26}
27
28/**
29 * Login to Salt API, return auth token
30 *
31 * @param master Salt connection object
32 */
33def saltLogin(master) {
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010034 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010035 data = [
36 'username': master.creds.username,
37 'password': master.creds.password.toString(),
38 'eauth': 'pam'
39 ]
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010040 authToken = http.restGet(master, '/login', data)['return'][0]['token']
Jakub Josef79ecec32017-02-17 14:36:28 +010041 return authToken
42}
43
44/**
chnydaa0dbb252017-10-05 10:46:09 +020045 * Run action using Salt API (using plain HTTP request from Jenkins master) or Pepper (from slave shell)
Jakub Josef79ecec32017-02-17 14:36:28 +010046 *
chnydaa0dbb252017-10-05 10:46:09 +020047 * @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 +010048 * @param client Client type
49 * @param target Target specification, eg. for compound matches by Pillar
50 * data: ['expression': 'I@openssh:server', 'type': 'compound'])
51 * @param function Function to execute (eg. "state.sls")
Jakub Josef2f25cf22017-03-28 13:34:57 +020052 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef79ecec32017-02-17 14:36:28 +010053 * @param args Additional arguments to function
54 * @param kwargs Additional key-value arguments to function
Jiri Broulik48544be2017-06-14 18:33:54 +020055 * @param timeout Additional argument salt api timeout
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +030056 * @param read_timeout http session read timeout
Jakub Josef79ecec32017-02-17 14:36:28 +010057 */
58@NonCPS
chnydaa0dbb252017-10-05 10:46:09 +020059def runSaltCommand(saltId, client, target, function, batch = null, args = null, kwargs = null, timeout = -1, read_timeout = -1) {
Jakub Josef79ecec32017-02-17 14:36:28 +010060
61 data = [
62 'tgt': target.expression,
63 'fun': function,
64 'client': client,
65 'expr_form': target.type,
66 ]
Richard Felkld9476ac2018-07-12 19:01:33 +020067
68 if(batch != null){
69 batch = batch.toString()
70 if( (batch.isInteger() && batch.toInteger() > 0) || (batch.contains("%"))){
71 data['client']= "local_batch"
72 data['batch'] = batch
73 }
Jakub Josef79ecec32017-02-17 14:36:28 +010074 }
75
76 if (args) {
77 data['arg'] = args
78 }
79
80 if (kwargs) {
81 data['kwarg'] = kwargs
82 }
83
Jiri Broulik48544be2017-06-14 18:33:54 +020084 if (timeout != -1) {
85 data['timeout'] = timeout
86 }
87
chnydaa0dbb252017-10-05 10:46:09 +020088 // Command will be sent using HttpRequest
89 if (saltId instanceof HashMap && saltId.containsKey("authToken") ) {
Jakub Josef79ecec32017-02-17 14:36:28 +010090
chnydaa0dbb252017-10-05 10:46:09 +020091 def headers = [
92 'X-Auth-Token': "${saltId.authToken}"
93 ]
94
95 def http = new com.mirantis.mk.Http()
96 return http.sendHttpPostRequest("${saltId.url}/", data, headers, read_timeout)
97 } else if (saltId instanceof HashMap) {
98 throw new Exception("Invalid saltId")
99 }
100
101 // Command will be sent using Pepper
102 return runPepperCommand(data, saltId)
Jakub Josef79ecec32017-02-17 14:36:28 +0100103}
104
Jakub Josef5ade54c2017-03-10 16:14:01 +0100105/**
chnydaa0dbb252017-10-05 10:46:09 +0200106 * Return pillar for given saltId and target
107 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100108 * @param target Get pillar target
109 * @param pillar pillar name (optional)
110 * @return output of salt command
111 */
chnydaa0dbb252017-10-05 10:46:09 +0200112def getPillar(saltId, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +0100113 if (pillar != null) {
chnydaa0dbb252017-10-05 10:46:09 +0200114 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +0100115 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200116 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +0100117 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100118}
119
Jakub Josef5ade54c2017-03-10 16:14:01 +0100120/**
chnydaa0dbb252017-10-05 10:46:09 +0200121 * Return grain for given saltId and target
122 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100123 * @param target Get grain target
124 * @param grain grain name (optional)
125 * @return output of salt command
126 */
chnydaa0dbb252017-10-05 10:46:09 +0200127def getGrain(saltId, target, grain = null) {
Ales Komarekcec24d42017-03-08 10:25:45 +0100128 if(grain != null) {
chnydaa0dbb252017-10-05 10:46:09 +0200129 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.item', null, [grain])
Jakub Josef5ade54c2017-03-10 16:14:01 +0100130 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200131 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100132 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100133}
134
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300135/**
136 * Return config items for given saltId and target
137 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
138 * @param target Get grain target
139 * @param config grain name (optional)
140 * @return output of salt command
141 */
142def getConfig(saltId, target, config) {
143 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'config.get', null, [config.replace('.', ':')], '--out=json')
144}
Jakub Josef432e9d92018-02-06 18:28:37 +0100145
Jakub Josef5ade54c2017-03-10 16:14:01 +0100146/**
chnydaa0dbb252017-10-05 10:46:09 +0200147 * Enforces state on given saltId and target
148 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100149 * @param target State enforcing target
150 * @param state Salt state
Jakub Josef432e9d92018-02-06 18:28:37 +0100151 * @param excludedStates states which will be excluded from main state (default empty string)
152 * @param output print output (optional, default true)
153 * @param failOnError throw exception on salt state result:false (optional, default true)
154 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
155 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
156 * @param read_timeout http session read timeout (optional, default -1 - disabled)
157 * @param retries Retry count for salt state. (optional, default -1 - no retries)
158 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
159 * @param saltArgs additional salt args eq. ["runas=aptly"]
160 * @return output of salt command
161 */
162def enforceStateWithExclude(saltId, target, state, excludedStates = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[]) {
163 saltArgs << "exclude=${excludedStates}"
164 return enforceState(saltId, target, state, output, failOnError, batch, optional, read_timeout, retries, queue, saltArgs)
165}
166
Martin Polreich75e40642018-08-13 16:05:08 +0200167/**
168 * Allows to test the given target for reachability and if reachable enforces the state
169* @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
170 * @param target State enforcing target
171 * @param state Salt state
172 * @param testTargetMatcher Salt compound matcher to be tested (default is empty string). If empty string, param `target` will be used for tests
173 * @param output print output (optional, default true)
174 * @param failOnError throw exception on salt state result:false (optional, default true)
175 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
176 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
177 * @param read_timeout http session read timeout (optional, default -1 - disabled)
178 * @param retries Retry count for salt state. (optional, default -1 - no retries)
179 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
180 * @param saltArgs additional salt args eq. ["runas=aptly"]
181 * @return output of salt command
182 */
183def enforceStateWithTest(saltId, target, state, testTargetMatcher = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[]) {
184 def common = new com.mirantis.mk.Common()
185 if (!testTargetMatcher) {
186 testTargetMatcher = target
187 }
188 if (testTarget(saltId, testTargetMatcher)) {
189 return enforceState(saltId, target, state, output, failOnError, batch, false, read_timeout, retries, queue, saltArgs)
190 } else {
191 if (!optional) {
Martin Polreich92db3e12018-09-27 15:29:23 +0200192 common.infoMsg("No Minions matched the target matcher: ${testTargetMatcher}, and 'optional' param was set to false. - This may signify missing pillar definition!!")
193// 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 +0200194 } else {
Martin Polreich92db3e12018-09-27 15:29:23 +0200195 common.infoMsg("No Minions matched the target matcher: ${testTargetMatcher}, but 'optional' param was set to true - Pipeline continues. ")
Martin Polreich75e40642018-08-13 16:05:08 +0200196 }
197 }
198}
199
Jakub Josef432e9d92018-02-06 18:28:37 +0100200/* Enforces state on given saltId and target
201 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
202 * @param target State enforcing target
203 * @param state Salt state
Jakub Josef5ade54c2017-03-10 16:14:01 +0100204 * @param output print output (optional, default true)
205 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200206 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100207 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
Petr Michalecde0ff322017-10-04 09:32:14 +0200208 * @param read_timeout http session read timeout (optional, default -1 - disabled)
209 * @param retries Retry count for salt state. (optional, default -1 - no retries)
210 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
Jakub Josef432e9d92018-02-06 18:28:37 +0100211 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
Vasyl Saienko6a396212018-06-08 09:20:08 +0300212 * @param minionRestartWaitTimeout specifies timeout that we should wait after minion restart.
Jakub Josef5ade54c2017-03-10 16:14:01 +0100213 * @return output of salt command
214 */
Vasyl Saienko6a396212018-06-08 09:20:08 +0300215def enforceState(saltId, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs = [], minionRestartWaitTimeout=10) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100216 def common = new com.mirantis.mk.Common()
Jakub Josef432e9d92018-02-06 18:28:37 +0100217 // add state to salt args
Jakub Josef79ecec32017-02-17 14:36:28 +0100218 if (state instanceof String) {
Jakub Josef432e9d92018-02-06 18:28:37 +0100219 saltArgs << state
Jakub Josef79ecec32017-02-17 14:36:28 +0100220 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100221 saltArgs << state.join(',')
Jakub Josef79ecec32017-02-17 14:36:28 +0100222 }
223
Jakub Josef84f01682018-02-07 14:26:19 +0100224 common.infoMsg("Running state ${state} on ${target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300225 def out
Petr Michalecde0ff322017-10-04 09:32:14 +0200226 def kwargs = [:]
227
228 if (queue && batch == null) {
229 kwargs["queue"] = true
230 }
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300231
chnydaa0dbb252017-10-05 10:46:09 +0200232 if (optional == false || testTarget(saltId, target)){
Richard Felkl03203d62017-11-01 17:57:32 +0100233 if (retries > 0){
Jakub Josef962ba912018-04-04 17:39:19 +0200234 def retriesCounter = 0
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300235 retry(retries){
Jakub Josef962ba912018-04-04 17:39:19 +0200236 retriesCounter++
Jakub Josef432e9d92018-02-06 18:28:37 +0100237 // we have to reverse order in saltArgs because salt state have to be first
238 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
239 // failOnError should be passed as true because we need to throw exception for retry block handler
Jakub Josef962ba912018-04-04 17:39:19 +0200240 checkResult(out, true, output, true, retriesCounter < retries) //disable ask on error for every interation except last one
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300241 }
Petr Michalecde0ff322017-10-04 09:32:14 +0200242 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100243 // we have to reverse order in saltArgs because salt state have to be first
244 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
Richard Felkl03203d62017-11-01 17:57:32 +0100245 checkResult(out, failOnError, output)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300246 }
Vasyl Saienko6a396212018-06-08 09:20:08 +0300247 waitForMinion(out, minionRestartWaitTimeout)
Martin Polreich1c77afa2017-07-18 11:27:02 +0200248 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200249 } else {
250 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
251 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100252}
253
Jakub Josef5ade54c2017-03-10 16:14:01 +0100254/**
255 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200256 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100257 * @param target Get pillar target
258 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200259 * @param checkResponse test command success execution (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)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200261 * @param output do you want to print output
chnyda205a92b2018-01-11 17:07:32 +0100262 * @param saltArgs additional salt args eq. ["runas=aptly"]
Jakub Josef5ade54c2017-03-10 16:14:01 +0100263 * @return output of salt command
264 */
chnyda205a92b2018-01-11 17:07:32 +0100265def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100266 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200267 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100268 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200269 if (checkResponse) {
270 cmd = cmd + " && echo Salt command execution success"
271 }
chnyda205a92b2018-01-11 17:07:32 +0100272
Jakub Josef432e9d92018-02-06 18:28:37 +0100273 // add cmd name to salt args list
chnyda205a92b2018-01-11 17:07:32 +0100274 saltArgs << cmd
275
276 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse())
Jakub Josef053df392017-05-03 15:51:05 +0200277 if (checkResponse) {
278 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200279 if (out["return"]){
280 for(int i=0;i<out["return"].size();i++){
281 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200282 for(int j=0;j<node.size();j++){
283 def nodeKey = node.keySet()[j]
Martin Polreicha2effb82018-08-01 11:35:11 +0200284 if (node[nodeKey] instanceof String) {
285 if (!node[nodeKey].contains("Salt command execution success")) {
286 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
287 }
288 } else if (node[nodeKey] instanceof Boolean) {
289 if (!node[nodeKey]) {
290 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
291 }
292 } else {
293 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns unexpected data type: ${node[nodeKey]}")
Jakub Josef053df392017-05-03 15:51:05 +0200294 }
295 }
296 }
Martin Polreicha2effb82018-08-01 11:35:11 +0200297 } else {
Jakub Josef053df392017-05-03 15:51:05 +0200298 throw new Exception("Salt Api response doesn't have return param!")
299 }
300 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200301 if (output == true) {
302 printSaltCommandResult(out)
303 }
304 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100305}
306
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200307/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200308 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200309 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
310 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200311 * @param target Get pillar target
312 * @param minion_name unique identification of a minion in salt-key command output
313 * @param waitUntilPresent return after the minion becomes present (default true)
314 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
315 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200316 * @param maxRetries finite number of iterations to check status of a command (default 200)
317 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200318 * @return output of salt command
319 */
lmercl94189272018-06-01 11:03:46 +0200320def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200321 minion_name = minion_name.replace("*", "")
322 def common = new com.mirantis.mk.Common()
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200323 common.infoMsg("Looking for minion: " + minion_name)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200324 def cmd = 'salt-key | grep ' + minion_name
325 if (waitUntilPresent){
326 def count = 0
327 while(count < maxRetries) {
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200328 try {
329 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
330 if (output) {
331 printSaltCommandResult(out)
332 }
333 def valueMap = out["return"][0]
334 def result = valueMap.get(valueMap.keySet()[0])
335 def resultsArray = result.tokenize("\n")
336 def size = resultsArray.size()
337 if (size >= answers) {
338 return out
339 }
340 count++
341 sleep(time: 1000, unit: 'MILLISECONDS')
342 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
343 } catch (Exception er) {
344 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
345 }
346 }
347 } else {
348 try {
chnydaa0dbb252017-10-05 10:46:09 +0200349 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200350 if (output) {
351 printSaltCommandResult(out)
352 }
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200353 return out
354 } catch (Exception er) {
355 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
Jiri Broulik71512bc2017-08-04 10:00:18 +0200356 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200357 }
358 // otherwise throw exception
359 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
360 throw new Exception("${cmd} signals failure of status check!")
361}
362
363/**
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200364 * Checks if salt minions are in a list of salt master's accepted keys by matching compound
365 * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100366 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
367 * @param target Performs tests on this target node
368 * @param target_minions all targeted minions to test (for ex. I@salt:minion)
369 * @param waitUntilPresent return after the minion becomes present (default true)
370 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
371 * @param output print salt command (default true)
372 * @param maxRetries finite number of iterations to check status of a command (default 200)
373 * @param answers how many minions should return (optional, default 1)
374 * @return output of salt command
375 */
376def minionsPresent(saltId, target = 'I@salt:master', target_minions = '', waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200377 def target_hosts = getMinionsSorted(saltId, target_minions)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100378 for (t in target_hosts) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200379 def tgt = stripDomainName(t)
380 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
381 }
382}
383
384/**
385 * Checks if salt minions are in a list of salt master's accepted keys by matching a list
386 * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3)
387 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
388 * @param target Performs tests on this target node
389 * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"])
390 * @param waitUntilPresent return after the minion becomes present (default true)
391 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
392 * @param output print salt command (default true)
393 * @param maxRetries finite number of iterations to check status of a command (default 200)
394 * @param answers how many minions should return (optional, default 1)
395 * @return output of salt command
396 */
397def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
398 def common = new com.mirantis.mk.Common()
399 for (tgt in target_minions) {
400 common.infoMsg("Checking if minion " + tgt + " is present")
401 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100402 }
403}
404
405/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200406 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200407 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200408 * @param target Should always be salt-master
409 * @param target_nodes unique identification of a minion or group of salt minions
410 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
411 * @param wait timeout for the salt command if minions do not return (default 10)
412 * @param maxRetries finite number of iterations to check status of a command (default 200)
413 * @return output of salt command
414 */
chnydaa0dbb252017-10-05 10:46:09 +0200415def minionsReachable(saltId, target, target_nodes, batch=null, wait = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200416 def common = new com.mirantis.mk.Common()
417 def cmd = "salt -t${wait} -C '${target_nodes}' test.ping"
418 common.infoMsg("Checking if all ${target_nodes} minions are reachable")
419 def count = 0
420 while(count < maxRetries) {
421 Calendar timeout = Calendar.getInstance();
422 timeout.add(Calendar.SECOND, wait);
chnydaa0dbb252017-10-05 10:46:09 +0200423 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, wait)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200424 Calendar current = Calendar.getInstance();
425 if (current.getTime().before(timeout.getTime())) {
426 printSaltCommandResult(out)
427 return out
428 }
429 common.infoMsg("Not all of the targeted '${target_nodes}' minions returned yet. Waiting ...")
430 count++
431 sleep(time: 500, unit: 'MILLISECONDS')
432 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200433}
434
435/**
436 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200437 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200438 * @param target Get pillar target
439 * @param cmd name of a service
440 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200441 * @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 +0200442 * @param waitUntilOk return after the minion becomes present (optional, default true)
443 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
444 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200445 * @param maxRetries finite number of iterations to check status of a command (default 200)
446 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200447 * @return output of salt command
448 */
chnydaa0dbb252017-10-05 10:46:09 +0200449def 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 +0200450 def common = new com.mirantis.mk.Common()
451 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
452 if (waitUntilOk){
453 def count = 0
454 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200455 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200456 if (output) {
457 printSaltCommandResult(out)
458 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200459 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200460 def success = 0
461 if (answers == 0){
462 answers = resultMap.size()
463 }
464 for (int i=0;i<answers;i++) {
465 result = resultMap.get(resultMap.keySet()[i])
466 // if the goal is to find some string in output of the command
467 if (find) {
468 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
469 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
470 success++
471 if (success == answers) {
472 return out
473 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200474 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200475 // else the goal is to not find any string in output of the command
476 } else {
477 if(result instanceof String && result.isEmpty()) {
478 success++
479 if (success == answers) {
480 return out
chnydaa0dbb252017-10-05 10:46:09 +0200481 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200482 }
483 }
484 }
485 count++
486 sleep(time: 500, unit: 'MILLISECONDS')
487 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
488 }
489 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200490 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200491 def resultMap = out["return"][0]
492 if (output) {
493 printSaltCommandResult(out)
494 }
495 for (int i=0;i<resultMap.size();i++) {
496 result = resultMap.get(resultMap.keySet()[i])
497 // if the goal is to find some string in output of the command
498 if (find) {
499 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
500 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200501 return out
502 }
503
504 // else the goal is to not find any string in output of the command
505 } else {
506 if(result instanceof String && result.isEmpty()) {
507 return out
508 }
509 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200510 }
511 }
512 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200513 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200514 throw new Exception("${cmd} signals failure of status check!")
515}
516
Jakub Josef5ade54c2017-03-10 16:14:01 +0100517/**
518 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200519 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100520 * @param target Get pillar target
521 * @return output of salt command
522 */
chnydaa0dbb252017-10-05 10:46:09 +0200523def syncAll(saltId, target) {
524 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100525}
526
Jakub Josef5ade54c2017-03-10 16:14:01 +0100527/**
Jakub Josef432e9d92018-02-06 18:28:37 +0100528 * Perform complete salt refresh between master and target
529 * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all
530 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
531 * @param target Get pillar target
532 * @return output of salt command
533 */
534def fullRefresh(saltId, target){
535 runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], null, true)
536 runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], null, true)
537 runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], null, true)
538}
539
540/**
541 * Enforce highstate on given targets
542 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
543 * @param target Highstate enforcing target
544 * @param excludedStates states which will be excluded from main state (default empty string)
545 * @param output print output (optional, default true)
546 * @param failOnError throw exception on salt state result:false (optional, default true)
547 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
548 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
549 * @return output of salt command
550 */
551def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) {
552 saltArgs << "exclude=${excludedStates}"
553 return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs)
554}
555/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100556 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200557 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100558 * @param target Highstate enforcing target
559 * @param output print output (optional, default true)
560 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200561 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100562 * @return output of salt command
563 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100564def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) {
Petr Jediný30be7032018-05-29 18:22:46 +0200565 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000566 def common = new com.mirantis.mk.Common()
567
Marek Celoud63366112017-07-25 17:27:24 +0200568 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000569
Jakub Josef374beb72017-04-27 15:45:09 +0200570 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100571 return out
572}
573
Jakub Josef5ade54c2017-03-10 16:14:01 +0100574/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100575 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200576 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100577 * @param target Get minions target
578 * @return list of active minions fitin
579 */
chnydaa0dbb252017-10-05 10:46:09 +0200580def getMinions(saltId, target) {
581 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100582 return new ArrayList<String>(minionsRaw['return'][0].keySet())
583}
584
Jiri Broulikf8f96942018-02-15 10:03:42 +0100585/**
586 * Get sorted running minions IDs according to the target
587 * @param saltId Salt Connection object or pepperEnv
588 * @param target Get minions target
589 * @return list of sorted active minions fitin
590 */
591def getMinionsSorted(saltId, target) {
592 return getMinions(saltId, target).sort()
593}
594
595/**
596 * Get first out of running minions IDs according to the target
597 * @param saltId Salt Connection object or pepperEnv
598 * @param target Get minions target
599 * @return first of active minions fitin
600 */
601def getFirstMinion(saltId, target) {
602 def minionsSorted = getMinionsSorted(saltId, target)
Dmitry Ukovd72cd2a2018-09-04 17:31:46 +0400603 return minionsSorted[0]
Jiri Broulikf8f96942018-02-15 10:03:42 +0100604}
605
606/**
607 * Get running salt minions IDs without it's domain name part and its numbering identifications
608 * @param saltId Salt Connection object or pepperEnv
609 * @param target Get minions target
610 * @return list of active minions fitin without it's domain name part name numbering
611 */
612def getMinionsGeneralName(saltId, target) {
613 def minionsSorted = getMinionsSorted(saltId, target)
614 return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "")
615}
616
617/**
618 * Get domain name of the env
619 * @param saltId Salt Connection object or pepperEnv
620 * @return domain name
621 */
622def getDomainName(saltId) {
623 return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain'))
624}
625
626/**
627 * Remove domain name from Salt minion ID
628 * @param name String of Salt minion ID
629 * @return Salt minion ID without its domain name
630 */
631def stripDomainName(name) {
632 return name.split("\\.")[0]
633}
634
635/**
636 * Gets return values of a salt command
637 * @param output String of Salt minion ID
638 * @return Return values of a salt command
639 */
640def getReturnValues(output) {
641 if(output.containsKey("return") && !output.get("return").isEmpty()) {
642 return output['return'][0].values()[0]
643 }
644 def common = new com.mirantis.mk.Common()
645 common.errorMsg('output does not contain return key')
646 return ''
647}
648
649/**
650 * Get minion ID of one of KVM nodes
651 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
652 * @return Salt minion ID of one of KVM nodes in env
653 */
654def getKvmMinionId(saltId) {
655 return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0]
656}
657
658/**
659 * Get Salt minion ID of KVM node hosting 'name' VM
660 * @param saltId Salt Connection object or pepperEnv
661 * @param name Name of the VM (for ex. ctl01)
662 * @return Salt minion ID of KVM node hosting 'name' VM
663 */
Jiri Broulikd2a50552018-04-25 17:17:59 +0200664def getNodeProvider(saltId, nodeName) {
665 def salt = new com.mirantis.mk.Salt()
666 def common = new com.mirantis.mk.Common()
667 def kvms = salt.getMinions(saltId, 'I@salt:control')
668 for (kvm in kvms) {
669 try {
670 vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true))
671 if (vms.toString().contains(nodeName)) {
672 return kvm
673 }
674 } catch (Exception er) {
675 common.infoMsg("${nodeName} not present on ${kvm}")
676 }
677 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100678}
679
Ales Komarek5276ebe2017-03-16 08:46:34 +0100680/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200681 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200682 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200683 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400684 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200685 */
686
chnydaa0dbb252017-10-05 10:46:09 +0200687def testTarget(saltId, target) {
688 return getMinions(saltId, target).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200689}
690
691/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100692 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200693 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100694 * @param target Key generating target
695 * @param host Key generating host
696 * @param keysize generated key size (optional, default 4096)
697 * @return output of salt command
698 */
chnydaa0dbb252017-10-05 10:46:09 +0200699def generateNodeKey(saltId, target, host, keysize = 4096) {
700 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100701}
702
Jakub Josef5ade54c2017-03-10 16:14:01 +0100703/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200704 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200705 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100706 * @param target Metadata generating target
707 * @param host Metadata generating host
708 * @param classes Reclass classes
709 * @param parameters Reclass parameters
710 * @return output of salt command
711 */
chnydaa0dbb252017-10-05 10:46:09 +0200712def generateNodeMetadata(saltId, target, host, classes, parameters) {
713 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100714}
715
Jakub Josef5ade54c2017-03-10 16:14:01 +0100716/**
717 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200718 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100719 * @param target Orchestration target
720 * @param orchestrate Salt orchestrate params
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200721 * @param kwargs Salt orchestrate params
Jakub Josef5ade54c2017-03-10 16:14:01 +0100722 * @return output of salt command
723 */
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200724def orchestrateSystem(saltId, target, orchestrate=[], kwargs = null) {
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300725 //Since the runSaltCommand uses "arg" (singular) for "runner" client this won`t work correctly on old salt 2016
726 //cause this version of salt used "args" (plural) for "runner" client, see following link for reference:
727 //https://github.com/saltstack/salt/pull/32938
Oleksii Grudev0c098382018-08-08 16:16:38 +0300728 def common = new com.mirantis.mk.Common()
729 def result = runSaltCommand(saltId, 'runner', target, 'state.orchestrate', true, orchestrate, kwargs, 7200, 7200)
730 if(result != null){
731 if(result['return']){
732 def retcode = result['return'][0].get('retcode')
733 if (retcode != 0) {
734 throw new Exception("Orchestration state failed while running: "+orchestrate)
735 }else{
736 common.infoMsg("Orchestrate state "+orchestrate+" succeeded")
737 }
738 }else{
739 common.errorMsg("Salt result has no return attribute! Result: ${result}")
740 }
741 }else{
742 common.errorMsg("Cannot check salt result, given result is null")
743 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100744}
745
Jakub Josef5ade54c2017-03-10 16:14:01 +0100746/**
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200747 * Run salt pre or post orchestrate tasks
748 *
749 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
750 * @param pillar_tree Reclass pillar that has orchestrate pillar for desired stage
751 * @param extra_tgt Extra targets for compound
752 *
753 * @return output of salt command
754 */
755def orchestratePrePost(saltId, pillar_tree, extra_tgt = '') {
756
757 def common = new com.mirantis.mk.Common()
758 def salt = new com.mirantis.mk.Salt()
759 def compound = 'I@' + pillar_tree + " " + extra_tgt
760
761 common.infoMsg("Refreshing pillars")
762 runSaltProcessStep(saltId, '*', 'saltutil.refresh_pillar', [], null, true)
763
764 common.infoMsg("Looking for orchestrate pillars")
765 if (salt.testTarget(saltId, compound)) {
766 for ( node in salt.getMinionsSorted(saltId, compound) ) {
767 def pillar = salt.getPillar(saltId, node, pillar_tree)
768 if ( !pillar['return'].isEmpty() ) {
769 for ( orch_id in pillar['return'][0].values() ) {
770 def orchestrator = orch_id.values()['orchestrator']
771 def orch_enabled = orch_id.values()['enabled']
772 if ( orch_enabled ) {
773 common.infoMsg("Orchestrating: ${orchestrator}")
774 salt.printSaltCommandResult(salt.orchestrateSystem(saltId, ['expression': node], [orchestrator]))
775 }
776 }
777 }
778 }
779 }
780}
781
782/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100783 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200784 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100785 * @param tgt Salt process step target
786 * @param fun Salt process step function
787 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200788 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100789 * @param output print output (optional, default true)
Jiri Broulik48544be2017-06-14 18:33:54 +0200790 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100791 * @return output of salt command
792 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100793def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100794 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200795 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100796 def out
797
Marek Celoud63366112017-07-25 17:27:24 +0200798 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100799
Filip Pytlounf0435c02017-03-02 17:48:54 +0100800 if (batch == true) {
chnydaa0dbb252017-10-05 10:46:09 +0200801 out = runSaltCommand(saltId, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100802 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200803 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100804 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100805
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100806 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200807 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100808 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200809 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100810}
811
812/**
813 * Check result for errors and throw exception if any found
814 *
815 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200816 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200817 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200818 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef432e9d92018-02-06 18:28:37 +0100819 * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false)
Jakub Josef79ecec32017-02-17 14:36:28 +0100820 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100821def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100822 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100823 if(result != null){
824 if(result['return']){
825 for (int i=0;i<result['return'].size();i++) {
826 def entry = result['return'][i]
827 if (!entry) {
828 if (failOnError) {
829 throw new Exception("Salt API returned empty response: ${result}")
830 } else {
831 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100832 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100833 }
834 for (int j=0;j<entry.size();j++) {
835 def nodeKey = entry.keySet()[j]
836 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200837 def outputResources = []
Jakub Josef47145942018-04-04 17:30:38 +0200838 def errorResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100839 common.infoMsg("Node ${nodeKey} changes:")
840 if(node instanceof Map || node instanceof List){
841 for (int k=0;k<node.size();k++) {
842 def resource;
843 def resKey;
844 if(node instanceof Map){
845 resKey = node.keySet()[k]
Richard Felkld9476ac2018-07-12 19:01:33 +0200846 if (resKey == "retcode")
847 continue
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100848 }else if(node instanceof List){
849 resKey = k
850 }
851 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200852 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200853 if(printResults){
854 if(resource instanceof Map && resource.keySet().contains("result")){
855 //clean unnesaccary fields
856 if(resource.keySet().contains("__run_num__")){
857 resource.remove("__run_num__")
858 }
859 if(resource.keySet().contains("__id__")){
860 resource.remove("__id__")
861 }
862 if(resource.keySet().contains("pchanges")){
863 resource.remove("pchanges")
864 }
865 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
866 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200867 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200868 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200869 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200870 }
871 }else{
872 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200873 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200874 }
875 }
876 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200877 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200878 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100879 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200880 common.debugMsg("checkResult: checking resource: ${resource}")
881 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josef47145942018-04-04 17:30:38 +0200882 errorResources.add(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200883 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100884 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200885 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +0200886 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200887 }
888 if(printResults && !outputResources.isEmpty()){
Jakub Josef47145942018-04-04 17:30:38 +0200889 println outputResources.stream().collect(Collectors.joining("\n"))
890 }
891 if(!errorResources.isEmpty()){
892 for(resource in errorResources){
893 def prettyResource = common.prettify(resource)
894 if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") {
895 timeout(time:1, unit:'HOURS') {
896 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
897 }
898 } else {
899 def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}"
900 if (failOnError) {
901 throw new Exception(errorMsg)
902 } else {
903 common.errorMsg(errorMsg)
904 }
905 }
906 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100907 }
908 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100909 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100910 }else{
911 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100912 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100913 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200914 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100915 }
916}
917
918/**
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200919* Parse salt API output to check minion restart and wait some time to be sure minion is up.
920* See https://mirantis.jira.com/browse/PROD-16258 for more details
921* TODO: change sleep to more tricky procedure.
922*
923* @param result Parsed response of Salt API
924*/
Vasyl Saienko6a396212018-06-08 09:20:08 +0300925def waitForMinion(result, minionRestartWaitTimeout=10) {
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200926 def common = new com.mirantis.mk.Common()
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200927 //In order to prevent multiple sleeps use bool variable to catch restart for any minion.
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200928 def isMinionRestarted = false
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200929 if(result != null){
930 if(result['return']){
931 for (int i=0;i<result['return'].size();i++) {
932 def entry = result['return'][i]
933 // exit in case of empty response.
934 if (!entry) {
935 return
936 }
937 // Loop for nodes
938 for (int j=0;j<entry.size();j++) {
939 def nodeKey = entry.keySet()[j]
940 def node=entry[nodeKey]
941 if(node instanceof Map || node instanceof List){
942 // Loop for node resources
943 for (int k=0;k<node.size();k++) {
944 def resource;
945 def resKey;
946 if(node instanceof Map){
947 resKey = node.keySet()[k]
948 }else if(node instanceof List){
949 resKey = k
950 }
951 resource = node[resKey]
Jakub Joseffb9996d2018-04-10 14:05:31 +0200952 // try to find if salt_minion service was restarted
953 if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200954 if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){
955 if(resource.changes.size() > 0){
956 isMinionRestarted=true
957 }
958 }
959 }
960 }
961 }
962 }
963 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200964 }
965 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200966 if (isMinionRestarted){
Vasyl Saienko6a396212018-06-08 09:20:08 +0300967 common.infoMsg("Salt minion service restart detected. Sleep ${minionRestartWaitTimeout} seconds to wait minion restart")
968 sleep(minionRestartWaitTimeout)
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200969 }
970}
971
972/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100973 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100974 *
975 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100976 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100977def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100978 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100979 if(result != null){
980 if(result['return']){
981 for (int i=0; i<result['return'].size(); i++) {
982 def entry = result['return'][i]
983 for (int j=0; j<entry.size(); j++) {
984 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
985 def nodeKey = entry.keySet()[j]
986 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200987 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100988 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100989 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100990 }else{
991 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100992 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100993 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100994 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100995 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100996}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200997
998
999/**
1000 * Return content of file target
1001 *
chnydaa0dbb252017-10-05 10:46:09 +02001002 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001003 * @param target Compound target (should target only one host)
1004 * @param file File path to read (/etc/hosts for example)
1005 */
1006
chnydaa0dbb252017-10-05 10:46:09 +02001007def getFileContent(saltId, target, file) {
1008 result = cmdRun(saltId, target, "cat ${file}")
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +02001009 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +02001010}
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001011
1012/**
1013 * Set override parameters in Salt cluster metadata
1014 *
chnydaa0dbb252017-10-05 10:46:09 +02001015 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001016 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +03001017 * @param reclass_dir Directory where Reclass git repo is located
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +02001018 * @param extra_tgt Extra targets for compound
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001019 */
1020
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001021def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass", extra_tgt = '') {
Tomáš Kukrálf178f052017-07-11 11:31:00 +02001022 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +03001023 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +02001024 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001025 def key = entry[0]
1026 def value = entry[1]
1027
1028 common.debugMsg("Set salt override ${key}=${value}")
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001029 runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'reclass.cluster_meta_set', [key, value], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +03001030 }
Oleh Hryhorov5f96e092018-06-22 18:37:08 +03001031 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 +03001032}
Oleg Grigorovbec45582017-09-12 20:29:24 +03001033
1034/**
1035* Execute salt commands via salt-api with
1036* CLI client salt-pepper
1037*
1038* @param data Salt command map
1039* @param venv Path to virtualenv with
1040*/
1041
1042def runPepperCommand(data, venv) {
Jakub Josef03d4d5a2017-12-20 16:35:09 +01001043 def common = new com.mirantis.mk.Common()
Oleg Grigorovbec45582017-09-12 20:29:24 +03001044 def python = new com.mirantis.mk.Python()
1045 def dataStr = new groovy.json.JsonBuilder(data).toString()
chnyda4901a042017-11-16 12:14:56 +01001046
Jakub Josefa2491ad2018-01-15 16:26:27 +01001047 def pepperCmdFile = "${venv}/pepper-cmd.json"
1048 writeFile file: pepperCmdFile, text: dataStr
1049 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}"
Oleg Grigorovbec45582017-09-12 20:29:24 +03001050
1051 if (venv) {
Jakub Josefe2f4ebb2018-01-15 16:11:51 +01001052 output = python.runVirtualenvCommand(venv, pepperCmd, true)
Oleg Grigorovbec45582017-09-12 20:29:24 +03001053 } else {
1054 echo("[Command]: ${pepperCmd}")
1055 output = sh (
1056 script: pepperCmd,
1057 returnStdout: true
1058 ).trim()
1059 }
1060
Jakub Josef37cd4972018-02-01 16:25:25 +01001061 def outputObj
1062 try {
1063 outputObj = new groovy.json.JsonSlurperClassic().parseText(output)
1064 } catch(Exception e) {
1065 common.errorMsg("Parsing Salt API JSON response failed! Response: " + output)
1066 throw e
1067 }
1068 return outputObj
Oleg Grigorovbec45582017-09-12 20:29:24 +03001069}