blob: 84659f63a041c835f618717962abf9ebf8a10c62 [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 ]
Jakub Josef5f838212017-04-06 12:43:58 +020067 if(batch != null && ( (batch instanceof Integer && batch > 0) || (batch instanceof String && batch.contains("%")))){
Jakub Josef2f25cf22017-03-28 13:34:57 +020068 data['client']= "local_batch"
69 data['batch'] = batch
Jakub Josef79ecec32017-02-17 14:36:28 +010070 }
71
72 if (args) {
73 data['arg'] = args
74 }
75
76 if (kwargs) {
77 data['kwarg'] = kwargs
78 }
79
Jiri Broulik48544be2017-06-14 18:33:54 +020080 if (timeout != -1) {
81 data['timeout'] = timeout
82 }
83
chnydaa0dbb252017-10-05 10:46:09 +020084 // Command will be sent using HttpRequest
85 if (saltId instanceof HashMap && saltId.containsKey("authToken") ) {
Jakub Josef79ecec32017-02-17 14:36:28 +010086
chnydaa0dbb252017-10-05 10:46:09 +020087 def headers = [
88 'X-Auth-Token': "${saltId.authToken}"
89 ]
90
91 def http = new com.mirantis.mk.Http()
92 return http.sendHttpPostRequest("${saltId.url}/", data, headers, read_timeout)
93 } else if (saltId instanceof HashMap) {
94 throw new Exception("Invalid saltId")
95 }
96
97 // Command will be sent using Pepper
98 return runPepperCommand(data, saltId)
Jakub Josef79ecec32017-02-17 14:36:28 +010099}
100
Jakub Josef5ade54c2017-03-10 16:14:01 +0100101/**
chnydaa0dbb252017-10-05 10:46:09 +0200102 * Return pillar for given saltId and target
103 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100104 * @param target Get pillar target
105 * @param pillar pillar name (optional)
106 * @return output of salt command
107 */
chnydaa0dbb252017-10-05 10:46:09 +0200108def getPillar(saltId, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +0100109 if (pillar != null) {
chnydaa0dbb252017-10-05 10:46:09 +0200110 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +0100111 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200112 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +0100113 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100114}
115
Jakub Josef5ade54c2017-03-10 16:14:01 +0100116/**
chnydaa0dbb252017-10-05 10:46:09 +0200117 * Return grain for given saltId and target
118 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100119 * @param target Get grain target
120 * @param grain grain name (optional)
121 * @return output of salt command
122 */
chnydaa0dbb252017-10-05 10:46:09 +0200123def getGrain(saltId, target, grain = null) {
Ales Komarekcec24d42017-03-08 10:25:45 +0100124 if(grain != null) {
chnydaa0dbb252017-10-05 10:46:09 +0200125 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.item', null, [grain])
Jakub Josef5ade54c2017-03-10 16:14:01 +0100126 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200127 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100128 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100129}
130
Jakub Josef432e9d92018-02-06 18:28:37 +0100131
Jakub Josef5ade54c2017-03-10 16:14:01 +0100132/**
chnydaa0dbb252017-10-05 10:46:09 +0200133 * Enforces state on given saltId and target
134 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100135 * @param target State enforcing target
136 * @param state Salt state
Jakub Josef432e9d92018-02-06 18:28:37 +0100137 * @param excludedStates states which will be excluded from main state (default empty string)
138 * @param output print output (optional, default true)
139 * @param failOnError throw exception on salt state result:false (optional, default true)
140 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
141 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
142 * @param read_timeout http session read timeout (optional, default -1 - disabled)
143 * @param retries Retry count for salt state. (optional, default -1 - no retries)
144 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
145 * @param saltArgs additional salt args eq. ["runas=aptly"]
146 * @return output of salt command
147 */
148def enforceStateWithExclude(saltId, target, state, excludedStates = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[]) {
149 saltArgs << "exclude=${excludedStates}"
150 return enforceState(saltId, target, state, output, failOnError, batch, optional, read_timeout, retries, queue, saltArgs)
151}
152
153/* Enforces state on given saltId and target
154 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
155 * @param target State enforcing target
156 * @param state Salt state
Jakub Josef5ade54c2017-03-10 16:14:01 +0100157 * @param output print output (optional, default true)
158 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200159 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100160 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
Petr Michalecde0ff322017-10-04 09:32:14 +0200161 * @param read_timeout http session read timeout (optional, default -1 - disabled)
162 * @param retries Retry count for salt state. (optional, default -1 - no retries)
163 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
Jakub Josef432e9d92018-02-06 18:28:37 +0100164 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
Jakub Josef5ade54c2017-03-10 16:14:01 +0100165 * @return output of salt command
166 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100167def enforceState(saltId, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100168 def common = new com.mirantis.mk.Common()
Jakub Josef432e9d92018-02-06 18:28:37 +0100169 // add state to salt args
Jakub Josef79ecec32017-02-17 14:36:28 +0100170 if (state instanceof String) {
Jakub Josef432e9d92018-02-06 18:28:37 +0100171 saltArgs << state
Jakub Josef79ecec32017-02-17 14:36:28 +0100172 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100173 saltArgs << state.join(',')
Jakub Josef79ecec32017-02-17 14:36:28 +0100174 }
175
Jakub Josef84f01682018-02-07 14:26:19 +0100176 common.infoMsg("Running state ${state} on ${target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300177 def out
Petr Michalecde0ff322017-10-04 09:32:14 +0200178 def kwargs = [:]
179
180 if (queue && batch == null) {
181 kwargs["queue"] = true
182 }
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300183
chnydaa0dbb252017-10-05 10:46:09 +0200184 if (optional == false || testTarget(saltId, target)){
Richard Felkl03203d62017-11-01 17:57:32 +0100185 if (retries > 0){
Jakub Josef962ba912018-04-04 17:39:19 +0200186 def retriesCounter = 0
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300187 retry(retries){
Jakub Josef962ba912018-04-04 17:39:19 +0200188 retriesCounter++
Jakub Josef432e9d92018-02-06 18:28:37 +0100189 // we have to reverse order in saltArgs because salt state have to be first
190 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
191 // failOnError should be passed as true because we need to throw exception for retry block handler
Jakub Josef962ba912018-04-04 17:39:19 +0200192 checkResult(out, true, output, true, retriesCounter < retries) //disable ask on error for every interation except last one
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300193 }
Petr Michalecde0ff322017-10-04 09:32:14 +0200194 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100195 // we have to reverse order in saltArgs because salt state have to be first
196 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
Richard Felkl03203d62017-11-01 17:57:32 +0100197 checkResult(out, failOnError, output)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300198 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200199 waitForMinion(out)
Martin Polreich1c77afa2017-07-18 11:27:02 +0200200 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200201 } else {
202 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
203 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100204}
205
Jakub Josef5ade54c2017-03-10 16:14:01 +0100206/**
207 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200208 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100209 * @param target Get pillar target
210 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200211 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200212 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200213 * @param output do you want to print output
chnyda205a92b2018-01-11 17:07:32 +0100214 * @param saltArgs additional salt args eq. ["runas=aptly"]
Jakub Josef5ade54c2017-03-10 16:14:01 +0100215 * @return output of salt command
216 */
chnyda205a92b2018-01-11 17:07:32 +0100217def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100218 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200219 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100220 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200221 if (checkResponse) {
222 cmd = cmd + " && echo Salt command execution success"
223 }
chnyda205a92b2018-01-11 17:07:32 +0100224
Jakub Josef432e9d92018-02-06 18:28:37 +0100225 // add cmd name to salt args list
chnyda205a92b2018-01-11 17:07:32 +0100226 saltArgs << cmd
227
228 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse())
Jakub Josef053df392017-05-03 15:51:05 +0200229 if (checkResponse) {
230 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200231 if (out["return"]){
232 for(int i=0;i<out["return"].size();i++){
233 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200234 for(int j=0;j<node.size();j++){
235 def nodeKey = node.keySet()[j]
236 if (!node[nodeKey].contains("Salt command execution success")) {
237 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
238 }
239 }
240 }
241 }else{
242 throw new Exception("Salt Api response doesn't have return param!")
243 }
244 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200245 if (output == true) {
246 printSaltCommandResult(out)
247 }
248 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100249}
250
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200251/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200252 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200253 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
254 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200255 * @param target Get pillar target
256 * @param minion_name unique identification of a minion in salt-key command output
257 * @param waitUntilPresent return after the minion becomes present (default true)
258 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
259 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200260 * @param maxRetries finite number of iterations to check status of a command (default 200)
261 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200262 * @return output of salt command
263 */
lmercl94189272018-06-01 11:03:46 +0200264def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200265 minion_name = minion_name.replace("*", "")
266 def common = new com.mirantis.mk.Common()
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200267 common.infoMsg("Looking for minion: " + minion_name)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200268 def cmd = 'salt-key | grep ' + minion_name
269 if (waitUntilPresent){
270 def count = 0
271 while(count < maxRetries) {
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200272 try {
273 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
274 if (output) {
275 printSaltCommandResult(out)
276 }
277 def valueMap = out["return"][0]
278 def result = valueMap.get(valueMap.keySet()[0])
279 def resultsArray = result.tokenize("\n")
280 def size = resultsArray.size()
281 if (size >= answers) {
282 return out
283 }
284 count++
285 sleep(time: 1000, unit: 'MILLISECONDS')
286 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
287 } catch (Exception er) {
288 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
289 }
290 }
291 } else {
292 try {
chnydaa0dbb252017-10-05 10:46:09 +0200293 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200294 if (output) {
295 printSaltCommandResult(out)
296 }
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200297 return out
298 } catch (Exception er) {
299 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
Jiri Broulik71512bc2017-08-04 10:00:18 +0200300 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200301 }
302 // otherwise throw exception
303 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
304 throw new Exception("${cmd} signals failure of status check!")
305}
306
307/**
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200308 * Checks if salt minions are in a list of salt master's accepted keys by matching compound
309 * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100310 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
311 * @param target Performs tests on this target node
312 * @param target_minions all targeted minions to test (for ex. I@salt:minion)
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)
316 * @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)
318 * @return output of salt command
319 */
320def 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 +0200321 def target_hosts = getMinionsSorted(saltId, target_minions)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100322 for (t in target_hosts) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200323 def tgt = stripDomainName(t)
324 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
325 }
326}
327
328/**
329 * Checks if salt minions are in a list of salt master's accepted keys by matching a list
330 * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3)
331 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
332 * @param target Performs tests on this target node
333 * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"])
334 * @param waitUntilPresent return after the minion becomes present (default true)
335 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
336 * @param output print salt command (default true)
337 * @param maxRetries finite number of iterations to check status of a command (default 200)
338 * @param answers how many minions should return (optional, default 1)
339 * @return output of salt command
340 */
341def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
342 def common = new com.mirantis.mk.Common()
343 for (tgt in target_minions) {
344 common.infoMsg("Checking if minion " + tgt + " is present")
345 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100346 }
347}
348
349/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200350 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200351 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200352 * @param target Should always be salt-master
353 * @param target_nodes unique identification of a minion or group of salt minions
354 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
355 * @param wait timeout for the salt command if minions do not return (default 10)
356 * @param maxRetries finite number of iterations to check status of a command (default 200)
357 * @return output of salt command
358 */
chnydaa0dbb252017-10-05 10:46:09 +0200359def minionsReachable(saltId, target, target_nodes, batch=null, wait = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200360 def common = new com.mirantis.mk.Common()
361 def cmd = "salt -t${wait} -C '${target_nodes}' test.ping"
362 common.infoMsg("Checking if all ${target_nodes} minions are reachable")
363 def count = 0
364 while(count < maxRetries) {
365 Calendar timeout = Calendar.getInstance();
366 timeout.add(Calendar.SECOND, wait);
chnydaa0dbb252017-10-05 10:46:09 +0200367 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, wait)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200368 Calendar current = Calendar.getInstance();
369 if (current.getTime().before(timeout.getTime())) {
370 printSaltCommandResult(out)
371 return out
372 }
373 common.infoMsg("Not all of the targeted '${target_nodes}' minions returned yet. Waiting ...")
374 count++
375 sleep(time: 500, unit: 'MILLISECONDS')
376 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200377}
378
379/**
380 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200381 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200382 * @param target Get pillar target
383 * @param cmd name of a service
384 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200385 * @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 +0200386 * @param waitUntilOk return after the minion becomes present (optional, default true)
387 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
388 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200389 * @param maxRetries finite number of iterations to check status of a command (default 200)
390 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200391 * @return output of salt command
392 */
chnydaa0dbb252017-10-05 10:46:09 +0200393def 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 +0200394 def common = new com.mirantis.mk.Common()
395 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
396 if (waitUntilOk){
397 def count = 0
398 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200399 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200400 if (output) {
401 printSaltCommandResult(out)
402 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200403 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200404 def success = 0
405 if (answers == 0){
406 answers = resultMap.size()
407 }
408 for (int i=0;i<answers;i++) {
409 result = resultMap.get(resultMap.keySet()[i])
410 // if the goal is to find some string in output of the command
411 if (find) {
412 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
413 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
414 success++
415 if (success == answers) {
416 return out
417 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200418 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200419 // else the goal is to not find any string in output of the command
420 } else {
421 if(result instanceof String && result.isEmpty()) {
422 success++
423 if (success == answers) {
424 return out
chnydaa0dbb252017-10-05 10:46:09 +0200425 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200426 }
427 }
428 }
429 count++
430 sleep(time: 500, unit: 'MILLISECONDS')
431 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
432 }
433 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200434 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200435 def resultMap = out["return"][0]
436 if (output) {
437 printSaltCommandResult(out)
438 }
439 for (int i=0;i<resultMap.size();i++) {
440 result = resultMap.get(resultMap.keySet()[i])
441 // if the goal is to find some string in output of the command
442 if (find) {
443 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
444 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200445 return out
446 }
447
448 // else the goal is to not find any string in output of the command
449 } else {
450 if(result instanceof String && result.isEmpty()) {
451 return out
452 }
453 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200454 }
455 }
456 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200457 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200458 throw new Exception("${cmd} signals failure of status check!")
459}
460
Jakub Josef5ade54c2017-03-10 16:14:01 +0100461/**
462 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200463 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100464 * @param target Get pillar target
465 * @return output of salt command
466 */
chnydaa0dbb252017-10-05 10:46:09 +0200467def syncAll(saltId, target) {
468 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100469}
470
Jakub Josef5ade54c2017-03-10 16:14:01 +0100471/**
Jakub Josef432e9d92018-02-06 18:28:37 +0100472 * Perform complete salt refresh between master and target
473 * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all
474 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
475 * @param target Get pillar target
476 * @return output of salt command
477 */
478def fullRefresh(saltId, target){
479 runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], null, true)
480 runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], null, true)
481 runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], null, true)
482}
483
484/**
485 * Enforce highstate on given targets
486 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
487 * @param target Highstate enforcing target
488 * @param excludedStates states which will be excluded from main state (default empty string)
489 * @param output print output (optional, default true)
490 * @param failOnError throw exception on salt state result:false (optional, default true)
491 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
492 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
493 * @return output of salt command
494 */
495def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) {
496 saltArgs << "exclude=${excludedStates}"
497 return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs)
498}
499/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100500 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200501 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100502 * @param target Highstate enforcing target
503 * @param output print output (optional, default true)
504 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200505 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100506 * @return output of salt command
507 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100508def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) {
Petr Jediný30be7032018-05-29 18:22:46 +0200509 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000510 def common = new com.mirantis.mk.Common()
511
Marek Celoud63366112017-07-25 17:27:24 +0200512 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000513
Jakub Josef374beb72017-04-27 15:45:09 +0200514 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100515 return out
516}
517
Jakub Josef5ade54c2017-03-10 16:14:01 +0100518/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100519 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200520 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100521 * @param target Get minions target
522 * @return list of active minions fitin
523 */
chnydaa0dbb252017-10-05 10:46:09 +0200524def getMinions(saltId, target) {
525 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100526 return new ArrayList<String>(minionsRaw['return'][0].keySet())
527}
528
Jiri Broulikf8f96942018-02-15 10:03:42 +0100529/**
530 * Get sorted running minions IDs according to the target
531 * @param saltId Salt Connection object or pepperEnv
532 * @param target Get minions target
533 * @return list of sorted active minions fitin
534 */
535def getMinionsSorted(saltId, target) {
536 return getMinions(saltId, target).sort()
537}
538
539/**
540 * Get first out of running minions IDs according to the target
541 * @param saltId Salt Connection object or pepperEnv
542 * @param target Get minions target
543 * @return first of active minions fitin
544 */
545def getFirstMinion(saltId, target) {
546 def minionsSorted = getMinionsSorted(saltId, target)
547 return minionsSorted[0].split("\\.")[0]
548}
549
550/**
551 * Get running salt minions IDs without it's domain name part and its numbering identifications
552 * @param saltId Salt Connection object or pepperEnv
553 * @param target Get minions target
554 * @return list of active minions fitin without it's domain name part name numbering
555 */
556def getMinionsGeneralName(saltId, target) {
557 def minionsSorted = getMinionsSorted(saltId, target)
558 return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "")
559}
560
561/**
562 * Get domain name of the env
563 * @param saltId Salt Connection object or pepperEnv
564 * @return domain name
565 */
566def getDomainName(saltId) {
567 return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain'))
568}
569
570/**
571 * Remove domain name from Salt minion ID
572 * @param name String of Salt minion ID
573 * @return Salt minion ID without its domain name
574 */
575def stripDomainName(name) {
576 return name.split("\\.")[0]
577}
578
579/**
580 * Gets return values of a salt command
581 * @param output String of Salt minion ID
582 * @return Return values of a salt command
583 */
584def getReturnValues(output) {
585 if(output.containsKey("return") && !output.get("return").isEmpty()) {
586 return output['return'][0].values()[0]
587 }
588 def common = new com.mirantis.mk.Common()
589 common.errorMsg('output does not contain return key')
590 return ''
591}
592
593/**
594 * Get minion ID of one of KVM nodes
595 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
596 * @return Salt minion ID of one of KVM nodes in env
597 */
598def getKvmMinionId(saltId) {
599 return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0]
600}
601
602/**
603 * Get Salt minion ID of KVM node hosting 'name' VM
604 * @param saltId Salt Connection object or pepperEnv
605 * @param name Name of the VM (for ex. ctl01)
606 * @return Salt minion ID of KVM node hosting 'name' VM
607 */
Jiri Broulikd2a50552018-04-25 17:17:59 +0200608def getNodeProvider(saltId, nodeName) {
609 def salt = new com.mirantis.mk.Salt()
610 def common = new com.mirantis.mk.Common()
611 def kvms = salt.getMinions(saltId, 'I@salt:control')
612 for (kvm in kvms) {
613 try {
614 vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true))
615 if (vms.toString().contains(nodeName)) {
616 return kvm
617 }
618 } catch (Exception er) {
619 common.infoMsg("${nodeName} not present on ${kvm}")
620 }
621 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100622}
623
Ales Komarek5276ebe2017-03-16 08:46:34 +0100624/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200625 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200626 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200627 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400628 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200629 */
630
chnydaa0dbb252017-10-05 10:46:09 +0200631def testTarget(saltId, target) {
632 return getMinions(saltId, target).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200633}
634
635/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100636 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200637 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100638 * @param target Key generating target
639 * @param host Key generating host
640 * @param keysize generated key size (optional, default 4096)
641 * @return output of salt command
642 */
chnydaa0dbb252017-10-05 10:46:09 +0200643def generateNodeKey(saltId, target, host, keysize = 4096) {
644 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100645}
646
Jakub Josef5ade54c2017-03-10 16:14:01 +0100647/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200648 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200649 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100650 * @param target Metadata generating target
651 * @param host Metadata generating host
652 * @param classes Reclass classes
653 * @param parameters Reclass parameters
654 * @return output of salt command
655 */
chnydaa0dbb252017-10-05 10:46:09 +0200656def generateNodeMetadata(saltId, target, host, classes, parameters) {
657 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100658}
659
Jakub Josef5ade54c2017-03-10 16:14:01 +0100660/**
661 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200662 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100663 * @param target Orchestration target
664 * @param orchestrate Salt orchestrate params
665 * @return output of salt command
666 */
chnydaa0dbb252017-10-05 10:46:09 +0200667def orchestrateSystem(saltId, target, orchestrate) {
668 return runSaltCommand(saltId, 'runner', target, 'state.orchestrate', [orchestrate])
Jakub Josef79ecec32017-02-17 14:36:28 +0100669}
670
Jakub Josef5ade54c2017-03-10 16:14:01 +0100671/**
672 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200673 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100674 * @param tgt Salt process step target
675 * @param fun Salt process step function
676 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200677 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100678 * @param output print output (optional, default true)
Jiri Broulik48544be2017-06-14 18:33:54 +0200679 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100680 * @return output of salt command
681 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100682def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100683 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200684 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100685 def out
686
Marek Celoud63366112017-07-25 17:27:24 +0200687 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100688
Filip Pytlounf0435c02017-03-02 17:48:54 +0100689 if (batch == true) {
chnydaa0dbb252017-10-05 10:46:09 +0200690 out = runSaltCommand(saltId, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100691 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200692 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100693 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100694
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100695 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200696 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100697 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200698 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100699}
700
701/**
702 * Check result for errors and throw exception if any found
703 *
704 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200705 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200706 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200707 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef432e9d92018-02-06 18:28:37 +0100708 * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false)
Jakub Josef79ecec32017-02-17 14:36:28 +0100709 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100710def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100711 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100712 if(result != null){
713 if(result['return']){
714 for (int i=0;i<result['return'].size();i++) {
715 def entry = result['return'][i]
716 if (!entry) {
717 if (failOnError) {
718 throw new Exception("Salt API returned empty response: ${result}")
719 } else {
720 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100721 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100722 }
723 for (int j=0;j<entry.size();j++) {
724 def nodeKey = entry.keySet()[j]
725 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200726 def outputResources = []
Jakub Josef47145942018-04-04 17:30:38 +0200727 def errorResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100728 common.infoMsg("Node ${nodeKey} changes:")
729 if(node instanceof Map || node instanceof List){
730 for (int k=0;k<node.size();k++) {
731 def resource;
732 def resKey;
733 if(node instanceof Map){
734 resKey = node.keySet()[k]
735 }else if(node instanceof List){
736 resKey = k
737 }
738 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200739 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200740 if(printResults){
741 if(resource instanceof Map && resource.keySet().contains("result")){
742 //clean unnesaccary fields
743 if(resource.keySet().contains("__run_num__")){
744 resource.remove("__run_num__")
745 }
746 if(resource.keySet().contains("__id__")){
747 resource.remove("__id__")
748 }
749 if(resource.keySet().contains("pchanges")){
750 resource.remove("pchanges")
751 }
752 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
753 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200754 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200755 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200756 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200757 }
758 }else{
759 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200760 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200761 }
762 }
763 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200764 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200765 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100766 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200767 common.debugMsg("checkResult: checking resource: ${resource}")
768 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josef47145942018-04-04 17:30:38 +0200769 errorResources.add(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200770 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100771 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200772 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +0200773 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200774 }
775 if(printResults && !outputResources.isEmpty()){
Jakub Josef47145942018-04-04 17:30:38 +0200776 println outputResources.stream().collect(Collectors.joining("\n"))
777 }
778 if(!errorResources.isEmpty()){
779 for(resource in errorResources){
780 def prettyResource = common.prettify(resource)
781 if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") {
782 timeout(time:1, unit:'HOURS') {
783 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
784 }
785 } else {
786 def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}"
787 if (failOnError) {
788 throw new Exception(errorMsg)
789 } else {
790 common.errorMsg(errorMsg)
791 }
792 }
793 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100794 }
795 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100796 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100797 }else{
798 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100799 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100800 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200801 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100802 }
803}
804
805/**
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200806* Parse salt API output to check minion restart and wait some time to be sure minion is up.
807* See https://mirantis.jira.com/browse/PROD-16258 for more details
808* TODO: change sleep to more tricky procedure.
809*
810* @param result Parsed response of Salt API
811*/
812def waitForMinion(result) {
813 def common = new com.mirantis.mk.Common()
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200814 //In order to prevent multiple sleeps use bool variable to catch restart for any minion.
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200815 def isMinionRestarted = false
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200816 if(result != null){
817 if(result['return']){
818 for (int i=0;i<result['return'].size();i++) {
819 def entry = result['return'][i]
820 // exit in case of empty response.
821 if (!entry) {
822 return
823 }
824 // Loop for nodes
825 for (int j=0;j<entry.size();j++) {
826 def nodeKey = entry.keySet()[j]
827 def node=entry[nodeKey]
828 if(node instanceof Map || node instanceof List){
829 // Loop for node resources
830 for (int k=0;k<node.size();k++) {
831 def resource;
832 def resKey;
833 if(node instanceof Map){
834 resKey = node.keySet()[k]
835 }else if(node instanceof List){
836 resKey = k
837 }
838 resource = node[resKey]
Jakub Joseffb9996d2018-04-10 14:05:31 +0200839 // try to find if salt_minion service was restarted
840 if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200841 if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){
842 if(resource.changes.size() > 0){
843 isMinionRestarted=true
844 }
845 }
846 }
847 }
848 }
849 }
850 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200851 }
852 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200853 if (isMinionRestarted){
854 common.infoMsg("Salt minion service restart detected. Sleep 10 seconds to wait minion restart")
855 sleep(10)
856 }
857}
858
859/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100860 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100861 *
862 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100863 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100864def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100865 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100866 if(result != null){
867 if(result['return']){
868 for (int i=0; i<result['return'].size(); i++) {
869 def entry = result['return'][i]
870 for (int j=0; j<entry.size(); j++) {
871 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
872 def nodeKey = entry.keySet()[j]
873 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200874 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100875 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100876 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100877 }else{
878 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100879 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100880 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100881 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100882 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100883}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200884
885
886/**
887 * Return content of file target
888 *
chnydaa0dbb252017-10-05 10:46:09 +0200889 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200890 * @param target Compound target (should target only one host)
891 * @param file File path to read (/etc/hosts for example)
892 */
893
chnydaa0dbb252017-10-05 10:46:09 +0200894def getFileContent(saltId, target, file) {
895 result = cmdRun(saltId, target, "cat ${file}")
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +0200896 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200897}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300898
899/**
900 * Set override parameters in Salt cluster metadata
901 *
chnydaa0dbb252017-10-05 10:46:09 +0200902 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300903 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +0300904 * @param reclass_dir Directory where Reclass git repo is located
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300905 */
906
chnydaa0dbb252017-10-05 10:46:09 +0200907def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass") {
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200908 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +0300909 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200910 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300911 def key = entry[0]
912 def value = entry[1]
913
914 common.debugMsg("Set salt override ${key}=${value}")
Mykyta Karpind4a42d02017-11-16 16:24:37 +0200915 runSaltProcessStep(saltId, 'I@salt:master', 'reclass.cluster_meta_set', [key, value], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300916 }
chnydaa0dbb252017-10-05 10:46:09 +0200917 runSaltProcessStep(saltId, 'I@salt:master', 'cmd.run', ["git -C ${reclass_dir} update-index --skip-worktree classes/cluster/overrides.yml"])
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300918}
Oleg Grigorovbec45582017-09-12 20:29:24 +0300919
920/**
921* Execute salt commands via salt-api with
922* CLI client salt-pepper
923*
924* @param data Salt command map
925* @param venv Path to virtualenv with
926*/
927
928def runPepperCommand(data, venv) {
Jakub Josef03d4d5a2017-12-20 16:35:09 +0100929 def common = new com.mirantis.mk.Common()
Oleg Grigorovbec45582017-09-12 20:29:24 +0300930 def python = new com.mirantis.mk.Python()
931 def dataStr = new groovy.json.JsonBuilder(data).toString()
chnyda4901a042017-11-16 12:14:56 +0100932
Jakub Josefa2491ad2018-01-15 16:26:27 +0100933 def pepperCmdFile = "${venv}/pepper-cmd.json"
934 writeFile file: pepperCmdFile, text: dataStr
935 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}"
Oleg Grigorovbec45582017-09-12 20:29:24 +0300936
937 if (venv) {
Jakub Josefe2f4ebb2018-01-15 16:11:51 +0100938 output = python.runVirtualenvCommand(venv, pepperCmd, true)
Oleg Grigorovbec45582017-09-12 20:29:24 +0300939 } else {
940 echo("[Command]: ${pepperCmd}")
941 output = sh (
942 script: pepperCmd,
943 returnStdout: true
944 ).trim()
945 }
946
Jakub Josef37cd4972018-02-01 16:25:25 +0100947 def outputObj
948 try {
949 outputObj = new groovy.json.JsonSlurperClassic().parseText(output)
950 } catch(Exception e) {
951 common.errorMsg("Parsing Salt API JSON response failed! Response: " + output)
952 throw e
953 }
954 return outputObj
Oleg Grigorovbec45582017-09-12 20:29:24 +0300955}