blob: 8afceb5d69168daaf93121807d45e0a937f1a08a [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
167/* Enforces state on given saltId and target
168 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
169 * @param target State enforcing target
170 * @param state Salt state
Jakub Josef5ade54c2017-03-10 16:14:01 +0100171 * @param output print output (optional, default true)
172 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200173 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100174 * @param optional Optional flag (if true pipeline will continue even if no minions for target found)
Petr Michalecde0ff322017-10-04 09:32:14 +0200175 * @param read_timeout http session read timeout (optional, default -1 - disabled)
176 * @param retries Retry count for salt state. (optional, default -1 - no retries)
177 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
Jakub Josef432e9d92018-02-06 18:28:37 +0100178 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
Vasyl Saienko6a396212018-06-08 09:20:08 +0300179 * @param minionRestartWaitTimeout specifies timeout that we should wait after minion restart.
Jakub Josef5ade54c2017-03-10 16:14:01 +0100180 * @return output of salt command
181 */
Vasyl Saienko6a396212018-06-08 09:20:08 +0300182def 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 +0100183 def common = new com.mirantis.mk.Common()
Jakub Josef432e9d92018-02-06 18:28:37 +0100184 // add state to salt args
Jakub Josef79ecec32017-02-17 14:36:28 +0100185 if (state instanceof String) {
Jakub Josef432e9d92018-02-06 18:28:37 +0100186 saltArgs << state
Jakub Josef79ecec32017-02-17 14:36:28 +0100187 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100188 saltArgs << state.join(',')
Jakub Josef79ecec32017-02-17 14:36:28 +0100189 }
190
Jakub Josef84f01682018-02-07 14:26:19 +0100191 common.infoMsg("Running state ${state} on ${target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300192 def out
Petr Michalecde0ff322017-10-04 09:32:14 +0200193 def kwargs = [:]
194
195 if (queue && batch == null) {
196 kwargs["queue"] = true
197 }
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300198
chnydaa0dbb252017-10-05 10:46:09 +0200199 if (optional == false || testTarget(saltId, target)){
Richard Felkl03203d62017-11-01 17:57:32 +0100200 if (retries > 0){
Jakub Josef962ba912018-04-04 17:39:19 +0200201 def retriesCounter = 0
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300202 retry(retries){
Jakub Josef962ba912018-04-04 17:39:19 +0200203 retriesCounter++
Jakub Josef432e9d92018-02-06 18:28:37 +0100204 // we have to reverse order in saltArgs because salt state have to be first
205 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
206 // failOnError should be passed as true because we need to throw exception for retry block handler
Jakub Josef962ba912018-04-04 17:39:19 +0200207 checkResult(out, true, output, true, retriesCounter < retries) //disable ask on error for every interation except last one
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300208 }
Petr Michalecde0ff322017-10-04 09:32:14 +0200209 } else {
Jakub Josef432e9d92018-02-06 18:28:37 +0100210 // we have to reverse order in saltArgs because salt state have to be first
211 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, saltArgs.reverse(), kwargs, -1, read_timeout)
Richard Felkl03203d62017-11-01 17:57:32 +0100212 checkResult(out, failOnError, output)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300213 }
Vasyl Saienko6a396212018-06-08 09:20:08 +0300214 waitForMinion(out, minionRestartWaitTimeout)
Martin Polreich1c77afa2017-07-18 11:27:02 +0200215 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200216 } else {
217 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
218 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100219}
220
Jakub Josef5ade54c2017-03-10 16:14:01 +0100221/**
222 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200223 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100224 * @param target Get pillar target
225 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200226 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200227 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200228 * @param output do you want to print output
chnyda205a92b2018-01-11 17:07:32 +0100229 * @param saltArgs additional salt args eq. ["runas=aptly"]
Jakub Josef5ade54c2017-03-10 16:14:01 +0100230 * @return output of salt command
231 */
chnyda205a92b2018-01-11 17:07:32 +0100232def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = []) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100233 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200234 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100235 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200236 if (checkResponse) {
237 cmd = cmd + " && echo Salt command execution success"
238 }
chnyda205a92b2018-01-11 17:07:32 +0100239
Jakub Josef432e9d92018-02-06 18:28:37 +0100240 // add cmd name to salt args list
chnyda205a92b2018-01-11 17:07:32 +0100241 saltArgs << cmd
242
243 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse())
Jakub Josef053df392017-05-03 15:51:05 +0200244 if (checkResponse) {
245 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200246 if (out["return"]){
247 for(int i=0;i<out["return"].size();i++){
248 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200249 for(int j=0;j<node.size();j++){
250 def nodeKey = node.keySet()[j]
Martin Polreicha2effb82018-08-01 11:35:11 +0200251 if (node[nodeKey] instanceof String) {
252 if (!node[nodeKey].contains("Salt command execution success")) {
253 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
254 }
255 } else if (node[nodeKey] instanceof Boolean) {
256 if (!node[nodeKey]) {
257 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
258 }
259 } else {
260 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns unexpected data type: ${node[nodeKey]}")
Jakub Josef053df392017-05-03 15:51:05 +0200261 }
262 }
263 }
Martin Polreicha2effb82018-08-01 11:35:11 +0200264 } else {
Jakub Josef053df392017-05-03 15:51:05 +0200265 throw new Exception("Salt Api response doesn't have return param!")
266 }
267 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200268 if (output == true) {
269 printSaltCommandResult(out)
270 }
271 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100272}
273
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200274/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200275 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200276 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
277 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200278 * @param target Get pillar target
279 * @param minion_name unique identification of a minion in salt-key command output
280 * @param waitUntilPresent return after the minion becomes present (default true)
281 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
282 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200283 * @param maxRetries finite number of iterations to check status of a command (default 200)
284 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200285 * @return output of salt command
286 */
lmercl94189272018-06-01 11:03:46 +0200287def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200288 minion_name = minion_name.replace("*", "")
289 def common = new com.mirantis.mk.Common()
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200290 common.infoMsg("Looking for minion: " + minion_name)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200291 def cmd = 'salt-key | grep ' + minion_name
292 if (waitUntilPresent){
293 def count = 0
294 while(count < maxRetries) {
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200295 try {
296 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
297 if (output) {
298 printSaltCommandResult(out)
299 }
300 def valueMap = out["return"][0]
301 def result = valueMap.get(valueMap.keySet()[0])
302 def resultsArray = result.tokenize("\n")
303 def size = resultsArray.size()
304 if (size >= answers) {
305 return out
306 }
307 count++
308 sleep(time: 1000, unit: 'MILLISECONDS')
309 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
310 } catch (Exception er) {
311 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
312 }
313 }
314 } else {
315 try {
chnydaa0dbb252017-10-05 10:46:09 +0200316 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200317 if (output) {
318 printSaltCommandResult(out)
319 }
Dzmitry Stremkouski5425d232018-06-07 00:46:00 +0200320 return out
321 } catch (Exception er) {
322 common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment')
Jiri Broulik71512bc2017-08-04 10:00:18 +0200323 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200324 }
325 // otherwise throw exception
326 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
327 throw new Exception("${cmd} signals failure of status check!")
328}
329
330/**
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200331 * Checks if salt minions are in a list of salt master's accepted keys by matching compound
332 * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100333 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
334 * @param target Performs tests on this target node
335 * @param target_minions all targeted minions to test (for ex. I@salt:minion)
336 * @param waitUntilPresent return after the minion becomes present (default true)
337 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
338 * @param output print salt command (default true)
339 * @param maxRetries finite number of iterations to check status of a command (default 200)
340 * @param answers how many minions should return (optional, default 1)
341 * @return output of salt command
342 */
343def 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 +0200344 def target_hosts = getMinionsSorted(saltId, target_minions)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100345 for (t in target_hosts) {
Dzmitry Stremkouski8a8d56b2018-05-01 12:20:04 +0200346 def tgt = stripDomainName(t)
347 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
348 }
349}
350
351/**
352 * Checks if salt minions are in a list of salt master's accepted keys by matching a list
353 * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3)
354 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
355 * @param target Performs tests on this target node
356 * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"])
357 * @param waitUntilPresent return after the minion becomes present (default true)
358 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
359 * @param output print salt command (default true)
360 * @param maxRetries finite number of iterations to check status of a command (default 200)
361 * @param answers how many minions should return (optional, default 1)
362 * @return output of salt command
363 */
364def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
365 def common = new com.mirantis.mk.Common()
366 for (tgt in target_minions) {
367 common.infoMsg("Checking if minion " + tgt + " is present")
368 minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers)
Jiri Broulikf8f96942018-02-15 10:03:42 +0100369 }
370}
371
372/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200373 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200374 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200375 * @param target Should always be salt-master
376 * @param target_nodes unique identification of a minion or group of salt minions
377 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
378 * @param wait timeout for the salt command if minions do not return (default 10)
379 * @param maxRetries finite number of iterations to check status of a command (default 200)
380 * @return output of salt command
381 */
chnydaa0dbb252017-10-05 10:46:09 +0200382def minionsReachable(saltId, target, target_nodes, batch=null, wait = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200383 def common = new com.mirantis.mk.Common()
384 def cmd = "salt -t${wait} -C '${target_nodes}' test.ping"
385 common.infoMsg("Checking if all ${target_nodes} minions are reachable")
386 def count = 0
387 while(count < maxRetries) {
388 Calendar timeout = Calendar.getInstance();
389 timeout.add(Calendar.SECOND, wait);
chnydaa0dbb252017-10-05 10:46:09 +0200390 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, wait)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200391 Calendar current = Calendar.getInstance();
392 if (current.getTime().before(timeout.getTime())) {
393 printSaltCommandResult(out)
394 return out
395 }
396 common.infoMsg("Not all of the targeted '${target_nodes}' minions returned yet. Waiting ...")
397 count++
398 sleep(time: 500, unit: 'MILLISECONDS')
399 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200400}
401
402/**
403 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200404 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200405 * @param target Get pillar target
406 * @param cmd name of a service
407 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200408 * @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 +0200409 * @param waitUntilOk return after the minion becomes present (optional, default true)
410 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
411 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200412 * @param maxRetries finite number of iterations to check status of a command (default 200)
413 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200414 * @return output of salt command
415 */
chnydaa0dbb252017-10-05 10:46:09 +0200416def 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 +0200417 def common = new com.mirantis.mk.Common()
418 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
419 if (waitUntilOk){
420 def count = 0
421 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200422 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200423 if (output) {
424 printSaltCommandResult(out)
425 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200426 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200427 def success = 0
428 if (answers == 0){
429 answers = resultMap.size()
430 }
431 for (int i=0;i<answers;i++) {
432 result = resultMap.get(resultMap.keySet()[i])
433 // if the goal is to find some string in output of the command
434 if (find) {
435 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
436 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
437 success++
438 if (success == answers) {
439 return out
440 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200441 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200442 // else the goal is to not find any string in output of the command
443 } else {
444 if(result instanceof String && result.isEmpty()) {
445 success++
446 if (success == answers) {
447 return out
chnydaa0dbb252017-10-05 10:46:09 +0200448 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200449 }
450 }
451 }
452 count++
453 sleep(time: 500, unit: 'MILLISECONDS')
454 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
455 }
456 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200457 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200458 def resultMap = out["return"][0]
459 if (output) {
460 printSaltCommandResult(out)
461 }
462 for (int i=0;i<resultMap.size();i++) {
463 result = resultMap.get(resultMap.keySet()[i])
464 // if the goal is to find some string in output of the command
465 if (find) {
466 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
467 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200468 return out
469 }
470
471 // else the goal is to not find any string in output of the command
472 } else {
473 if(result instanceof String && result.isEmpty()) {
474 return out
475 }
476 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200477 }
478 }
479 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200480 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200481 throw new Exception("${cmd} signals failure of status check!")
482}
483
Jakub Josef5ade54c2017-03-10 16:14:01 +0100484/**
485 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200486 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100487 * @param target Get pillar target
488 * @return output of salt command
489 */
chnydaa0dbb252017-10-05 10:46:09 +0200490def syncAll(saltId, target) {
491 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100492}
493
Jakub Josef5ade54c2017-03-10 16:14:01 +0100494/**
Jakub Josef432e9d92018-02-06 18:28:37 +0100495 * Perform complete salt refresh between master and target
496 * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all
497 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
498 * @param target Get pillar target
499 * @return output of salt command
500 */
501def fullRefresh(saltId, target){
502 runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], null, true)
503 runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], null, true)
504 runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], null, true)
505}
506
507/**
508 * Enforce highstate on given targets
509 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
510 * @param target Highstate enforcing target
511 * @param excludedStates states which will be excluded from main state (default empty string)
512 * @param output print output (optional, default true)
513 * @param failOnError throw exception on salt state result:false (optional, default true)
514 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
515 * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"]
516 * @return output of salt command
517 */
518def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) {
519 saltArgs << "exclude=${excludedStates}"
520 return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs)
521}
522/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100523 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200524 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100525 * @param target Highstate enforcing target
526 * @param output print output (optional, default true)
527 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200528 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100529 * @return output of salt command
530 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100531def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) {
Petr Jediný30be7032018-05-29 18:22:46 +0200532 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000533 def common = new com.mirantis.mk.Common()
534
Marek Celoud63366112017-07-25 17:27:24 +0200535 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000536
Jakub Josef374beb72017-04-27 15:45:09 +0200537 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100538 return out
539}
540
Jakub Josef5ade54c2017-03-10 16:14:01 +0100541/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100542 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200543 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100544 * @param target Get minions target
545 * @return list of active minions fitin
546 */
chnydaa0dbb252017-10-05 10:46:09 +0200547def getMinions(saltId, target) {
548 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100549 return new ArrayList<String>(minionsRaw['return'][0].keySet())
550}
551
Jiri Broulikf8f96942018-02-15 10:03:42 +0100552/**
553 * Get sorted running minions IDs according to the target
554 * @param saltId Salt Connection object or pepperEnv
555 * @param target Get minions target
556 * @return list of sorted active minions fitin
557 */
558def getMinionsSorted(saltId, target) {
559 return getMinions(saltId, target).sort()
560}
561
562/**
563 * Get first out of running minions IDs according to the target
564 * @param saltId Salt Connection object or pepperEnv
565 * @param target Get minions target
566 * @return first of active minions fitin
567 */
568def getFirstMinion(saltId, target) {
569 def minionsSorted = getMinionsSorted(saltId, target)
570 return minionsSorted[0].split("\\.")[0]
571}
572
573/**
574 * Get running salt minions IDs without it's domain name part and its numbering identifications
575 * @param saltId Salt Connection object or pepperEnv
576 * @param target Get minions target
577 * @return list of active minions fitin without it's domain name part name numbering
578 */
579def getMinionsGeneralName(saltId, target) {
580 def minionsSorted = getMinionsSorted(saltId, target)
581 return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "")
582}
583
584/**
585 * Get domain name of the env
586 * @param saltId Salt Connection object or pepperEnv
587 * @return domain name
588 */
589def getDomainName(saltId) {
590 return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain'))
591}
592
593/**
594 * Remove domain name from Salt minion ID
595 * @param name String of Salt minion ID
596 * @return Salt minion ID without its domain name
597 */
598def stripDomainName(name) {
599 return name.split("\\.")[0]
600}
601
602/**
603 * Gets return values of a salt command
604 * @param output String of Salt minion ID
605 * @return Return values of a salt command
606 */
607def getReturnValues(output) {
608 if(output.containsKey("return") && !output.get("return").isEmpty()) {
609 return output['return'][0].values()[0]
610 }
611 def common = new com.mirantis.mk.Common()
612 common.errorMsg('output does not contain return key')
613 return ''
614}
615
616/**
617 * Get minion ID of one of KVM nodes
618 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
619 * @return Salt minion ID of one of KVM nodes in env
620 */
621def getKvmMinionId(saltId) {
622 return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0]
623}
624
625/**
626 * Get Salt minion ID of KVM node hosting 'name' VM
627 * @param saltId Salt Connection object or pepperEnv
628 * @param name Name of the VM (for ex. ctl01)
629 * @return Salt minion ID of KVM node hosting 'name' VM
630 */
Jiri Broulikd2a50552018-04-25 17:17:59 +0200631def getNodeProvider(saltId, nodeName) {
632 def salt = new com.mirantis.mk.Salt()
633 def common = new com.mirantis.mk.Common()
634 def kvms = salt.getMinions(saltId, 'I@salt:control')
635 for (kvm in kvms) {
636 try {
637 vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true))
638 if (vms.toString().contains(nodeName)) {
639 return kvm
640 }
641 } catch (Exception er) {
642 common.infoMsg("${nodeName} not present on ${kvm}")
643 }
644 }
Jiri Broulikf8f96942018-02-15 10:03:42 +0100645}
646
Ales Komarek5276ebe2017-03-16 08:46:34 +0100647/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200648 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200649 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200650 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400651 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200652 */
653
chnydaa0dbb252017-10-05 10:46:09 +0200654def testTarget(saltId, target) {
655 return getMinions(saltId, target).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200656}
657
658/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100659 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200660 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100661 * @param target Key generating target
662 * @param host Key generating host
663 * @param keysize generated key size (optional, default 4096)
664 * @return output of salt command
665 */
chnydaa0dbb252017-10-05 10:46:09 +0200666def generateNodeKey(saltId, target, host, keysize = 4096) {
667 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100668}
669
Jakub Josef5ade54c2017-03-10 16:14:01 +0100670/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200671 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200672 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100673 * @param target Metadata generating target
674 * @param host Metadata generating host
675 * @param classes Reclass classes
676 * @param parameters Reclass parameters
677 * @return output of salt command
678 */
chnydaa0dbb252017-10-05 10:46:09 +0200679def generateNodeMetadata(saltId, target, host, classes, parameters) {
680 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100681}
682
Jakub Josef5ade54c2017-03-10 16:14:01 +0100683/**
684 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200685 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100686 * @param target Orchestration target
687 * @param orchestrate Salt orchestrate params
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200688 * @param kwargs Salt orchestrate params
Jakub Josef5ade54c2017-03-10 16:14:01 +0100689 * @return output of salt command
690 */
Dzmitry Stremkouskidd020d92018-07-22 12:01:07 +0200691def orchestrateSystem(saltId, target, orchestrate=[], kwargs = null) {
Oleksii Grudev9e1d97a2018-06-29 16:04:30 +0300692 //Since the runSaltCommand uses "arg" (singular) for "runner" client this won`t work correctly on old salt 2016
693 //cause this version of salt used "args" (plural) for "runner" client, see following link for reference:
694 //https://github.com/saltstack/salt/pull/32938
Oleksii Grudev0c098382018-08-08 16:16:38 +0300695 def common = new com.mirantis.mk.Common()
696 def result = runSaltCommand(saltId, 'runner', target, 'state.orchestrate', true, orchestrate, kwargs, 7200, 7200)
697 if(result != null){
698 if(result['return']){
699 def retcode = result['return'][0].get('retcode')
700 if (retcode != 0) {
701 throw new Exception("Orchestration state failed while running: "+orchestrate)
702 }else{
703 common.infoMsg("Orchestrate state "+orchestrate+" succeeded")
704 }
705 }else{
706 common.errorMsg("Salt result has no return attribute! Result: ${result}")
707 }
708 }else{
709 common.errorMsg("Cannot check salt result, given result is null")
710 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100711}
712
Jakub Josef5ade54c2017-03-10 16:14:01 +0100713/**
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200714 * Run salt pre or post orchestrate tasks
715 *
716 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
717 * @param pillar_tree Reclass pillar that has orchestrate pillar for desired stage
718 * @param extra_tgt Extra targets for compound
719 *
720 * @return output of salt command
721 */
722def orchestratePrePost(saltId, pillar_tree, extra_tgt = '') {
723
724 def common = new com.mirantis.mk.Common()
725 def salt = new com.mirantis.mk.Salt()
726 def compound = 'I@' + pillar_tree + " " + extra_tgt
727
728 common.infoMsg("Refreshing pillars")
729 runSaltProcessStep(saltId, '*', 'saltutil.refresh_pillar', [], null, true)
730
731 common.infoMsg("Looking for orchestrate pillars")
732 if (salt.testTarget(saltId, compound)) {
733 for ( node in salt.getMinionsSorted(saltId, compound) ) {
734 def pillar = salt.getPillar(saltId, node, pillar_tree)
735 if ( !pillar['return'].isEmpty() ) {
736 for ( orch_id in pillar['return'][0].values() ) {
737 def orchestrator = orch_id.values()['orchestrator']
738 def orch_enabled = orch_id.values()['enabled']
739 if ( orch_enabled ) {
740 common.infoMsg("Orchestrating: ${orchestrator}")
741 salt.printSaltCommandResult(salt.orchestrateSystem(saltId, ['expression': node], [orchestrator]))
742 }
743 }
744 }
745 }
746 }
747}
748
749/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100750 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200751 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100752 * @param tgt Salt process step target
753 * @param fun Salt process step function
754 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200755 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef432e9d92018-02-06 18:28:37 +0100756 * @param output print output (optional, default true)
Jiri Broulik48544be2017-06-14 18:33:54 +0200757 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100758 * @return output of salt command
759 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100760def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100761 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200762 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100763 def out
764
Marek Celoud63366112017-07-25 17:27:24 +0200765 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100766
Filip Pytlounf0435c02017-03-02 17:48:54 +0100767 if (batch == true) {
chnydaa0dbb252017-10-05 10:46:09 +0200768 out = runSaltCommand(saltId, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100769 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200770 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100771 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100772
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100773 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200774 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100775 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200776 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100777}
778
779/**
780 * Check result for errors and throw exception if any found
781 *
782 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200783 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200784 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200785 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef432e9d92018-02-06 18:28:37 +0100786 * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false)
Jakub Josef79ecec32017-02-17 14:36:28 +0100787 */
Jakub Josef432e9d92018-02-06 18:28:37 +0100788def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100789 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100790 if(result != null){
791 if(result['return']){
792 for (int i=0;i<result['return'].size();i++) {
793 def entry = result['return'][i]
794 if (!entry) {
795 if (failOnError) {
796 throw new Exception("Salt API returned empty response: ${result}")
797 } else {
798 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100799 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100800 }
801 for (int j=0;j<entry.size();j++) {
802 def nodeKey = entry.keySet()[j]
803 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200804 def outputResources = []
Jakub Josef47145942018-04-04 17:30:38 +0200805 def errorResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100806 common.infoMsg("Node ${nodeKey} changes:")
807 if(node instanceof Map || node instanceof List){
808 for (int k=0;k<node.size();k++) {
809 def resource;
810 def resKey;
811 if(node instanceof Map){
812 resKey = node.keySet()[k]
Richard Felkld9476ac2018-07-12 19:01:33 +0200813 if (resKey == "retcode")
814 continue
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100815 }else if(node instanceof List){
816 resKey = k
817 }
818 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200819 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200820 if(printResults){
821 if(resource instanceof Map && resource.keySet().contains("result")){
822 //clean unnesaccary fields
823 if(resource.keySet().contains("__run_num__")){
824 resource.remove("__run_num__")
825 }
826 if(resource.keySet().contains("__id__")){
827 resource.remove("__id__")
828 }
829 if(resource.keySet().contains("pchanges")){
830 resource.remove("pchanges")
831 }
832 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
833 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200834 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200835 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200836 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200837 }
838 }else{
839 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200840 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200841 }
842 }
843 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200844 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200845 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100846 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200847 common.debugMsg("checkResult: checking resource: ${resource}")
848 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josef47145942018-04-04 17:30:38 +0200849 errorResources.add(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200850 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100851 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200852 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +0200853 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200854 }
855 if(printResults && !outputResources.isEmpty()){
Jakub Josef47145942018-04-04 17:30:38 +0200856 println outputResources.stream().collect(Collectors.joining("\n"))
857 }
858 if(!errorResources.isEmpty()){
859 for(resource in errorResources){
860 def prettyResource = common.prettify(resource)
861 if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") {
862 timeout(time:1, unit:'HOURS') {
863 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
864 }
865 } else {
866 def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}"
867 if (failOnError) {
868 throw new Exception(errorMsg)
869 } else {
870 common.errorMsg(errorMsg)
871 }
872 }
873 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100874 }
875 }
Jakub Josef52f69f72017-03-14 15:18:08 +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 Josef52f69f72017-03-14 15:18:08 +0100880 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200881 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100882 }
883}
884
885/**
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200886* Parse salt API output to check minion restart and wait some time to be sure minion is up.
887* See https://mirantis.jira.com/browse/PROD-16258 for more details
888* TODO: change sleep to more tricky procedure.
889*
890* @param result Parsed response of Salt API
891*/
Vasyl Saienko6a396212018-06-08 09:20:08 +0300892def waitForMinion(result, minionRestartWaitTimeout=10) {
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200893 def common = new com.mirantis.mk.Common()
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200894 //In order to prevent multiple sleeps use bool variable to catch restart for any minion.
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200895 def isMinionRestarted = false
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200896 if(result != null){
897 if(result['return']){
898 for (int i=0;i<result['return'].size();i++) {
899 def entry = result['return'][i]
900 // exit in case of empty response.
901 if (!entry) {
902 return
903 }
904 // Loop for nodes
905 for (int j=0;j<entry.size();j++) {
906 def nodeKey = entry.keySet()[j]
907 def node=entry[nodeKey]
908 if(node instanceof Map || node instanceof List){
909 // Loop for node resources
910 for (int k=0;k<node.size();k++) {
911 def resource;
912 def resKey;
913 if(node instanceof Map){
914 resKey = node.keySet()[k]
915 }else if(node instanceof List){
916 resKey = k
917 }
918 resource = node[resKey]
Jakub Joseffb9996d2018-04-10 14:05:31 +0200919 // try to find if salt_minion service was restarted
920 if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){
Oleg Iurchenko3eedc782017-12-12 11:49:29 +0200921 if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){
922 if(resource.changes.size() > 0){
923 isMinionRestarted=true
924 }
925 }
926 }
927 }
928 }
929 }
930 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200931 }
932 }
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200933 if (isMinionRestarted){
Vasyl Saienko6a396212018-06-08 09:20:08 +0300934 common.infoMsg("Salt minion service restart detected. Sleep ${minionRestartWaitTimeout} seconds to wait minion restart")
935 sleep(minionRestartWaitTimeout)
Oleg Iurchenko7eb21502017-11-28 18:53:43 +0200936 }
937}
938
939/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100940 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100941 *
942 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100943 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100944def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100945 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100946 if(result != null){
947 if(result['return']){
948 for (int i=0; i<result['return'].size(); i++) {
949 def entry = result['return'][i]
950 for (int j=0; j<entry.size(); j++) {
951 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
952 def nodeKey = entry.keySet()[j]
953 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200954 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100955 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100956 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100957 }else{
958 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100959 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100960 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100961 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100962 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100963}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200964
965
966/**
967 * Return content of file target
968 *
chnydaa0dbb252017-10-05 10:46:09 +0200969 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200970 * @param target Compound target (should target only one host)
971 * @param file File path to read (/etc/hosts for example)
972 */
973
chnydaa0dbb252017-10-05 10:46:09 +0200974def getFileContent(saltId, target, file) {
975 result = cmdRun(saltId, target, "cat ${file}")
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +0200976 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200977}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300978
979/**
980 * Set override parameters in Salt cluster metadata
981 *
chnydaa0dbb252017-10-05 10:46:09 +0200982 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300983 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +0300984 * @param reclass_dir Directory where Reclass git repo is located
Dzmitry Stremkouskib5440702018-07-22 13:00:05 +0200985 * @param extra_tgt Extra targets for compound
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300986 */
987
Oleh Hryhorov5f96e092018-06-22 18:37:08 +0300988def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass", extra_tgt = '') {
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200989 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +0300990 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200991 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300992 def key = entry[0]
993 def value = entry[1]
994
995 common.debugMsg("Set salt override ${key}=${value}")
Oleh Hryhorov5f96e092018-06-22 18:37:08 +0300996 runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'reclass.cluster_meta_set', [key, value], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300997 }
Oleh Hryhorov5f96e092018-06-22 18:37:08 +0300998 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 +0300999}
Oleg Grigorovbec45582017-09-12 20:29:24 +03001000
1001/**
1002* Execute salt commands via salt-api with
1003* CLI client salt-pepper
1004*
1005* @param data Salt command map
1006* @param venv Path to virtualenv with
1007*/
1008
1009def runPepperCommand(data, venv) {
Jakub Josef03d4d5a2017-12-20 16:35:09 +01001010 def common = new com.mirantis.mk.Common()
Oleg Grigorovbec45582017-09-12 20:29:24 +03001011 def python = new com.mirantis.mk.Python()
1012 def dataStr = new groovy.json.JsonBuilder(data).toString()
chnyda4901a042017-11-16 12:14:56 +01001013
Jakub Josefa2491ad2018-01-15 16:26:27 +01001014 def pepperCmdFile = "${venv}/pepper-cmd.json"
1015 writeFile file: pepperCmdFile, text: dataStr
1016 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}"
Oleg Grigorovbec45582017-09-12 20:29:24 +03001017
1018 if (venv) {
Jakub Josefe2f4ebb2018-01-15 16:11:51 +01001019 output = python.runVirtualenvCommand(venv, pepperCmd, true)
Oleg Grigorovbec45582017-09-12 20:29:24 +03001020 } else {
1021 echo("[Command]: ${pepperCmd}")
1022 output = sh (
1023 script: pepperCmd,
1024 returnStdout: true
1025 ).trim()
1026 }
1027
Jakub Josef37cd4972018-02-01 16:25:25 +01001028 def outputObj
1029 try {
1030 outputObj = new groovy.json.JsonSlurperClassic().parseText(output)
1031 } catch(Exception e) {
1032 common.errorMsg("Parsing Salt API JSON response failed! Response: " + output)
1033 throw e
1034 }
1035 return outputObj
Oleg Grigorovbec45582017-09-12 20:29:24 +03001036}