blob: 2e72bb88a99731e83dc92638f422920a4c7d4186 [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 Josef5ade54c2017-03-10 16:14:01 +0100131/**
chnydaa0dbb252017-10-05 10:46:09 +0200132 * Enforces state on given saltId and target
133 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100134 * @param target State enforcing target
135 * @param state Salt state
136 * @param output print output (optional, default true)
137 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200138 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Petr Michalecde0ff322017-10-04 09:32:14 +0200139 * @param read_timeout http session read timeout (optional, default -1 - disabled)
140 * @param retries Retry count for salt state. (optional, default -1 - no retries)
141 * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH
Jakub Josef5ade54c2017-03-10 16:14:01 +0100142 * @return output of salt command
143 */
chnydaa0dbb252017-10-05 10:46:09 +0200144def enforceState(saltId, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100145 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100146 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100147
Jakub Josef79ecec32017-02-17 14:36:28 +0100148 if (state instanceof String) {
149 run_states = state
150 } else {
151 run_states = state.join(',')
152 }
153
Marek Celoud63366112017-07-25 17:27:24 +0200154 common.infoMsg("Running state ${run_states} on ${target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300155 def out
Petr Michalecde0ff322017-10-04 09:32:14 +0200156 def kwargs = [:]
157
158 if (queue && batch == null) {
159 kwargs["queue"] = true
160 }
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300161
chnydaa0dbb252017-10-05 10:46:09 +0200162 if (optional == false || testTarget(saltId, target)){
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300163 if (retries != -1){
164 retry(retries){
chnydaa0dbb252017-10-05 10:46:09 +0200165 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states], kwargs, -1, read_timeout)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300166 }
Petr Michalecde0ff322017-10-04 09:32:14 +0200167 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200168 out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states], kwargs, -1, read_timeout)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300169 }
Martin Polreich1c77afa2017-07-18 11:27:02 +0200170 checkResult(out, failOnError, output)
171 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200172 } else {
173 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
174 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100175}
176
Jakub Josef5ade54c2017-03-10 16:14:01 +0100177/**
178 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200179 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100180 * @param target Get pillar target
181 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200182 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200183 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200184 * @param output do you want to print output
Jakub Josef5ade54c2017-03-10 16:14:01 +0100185 * @return output of salt command
186 */
chnydaa0dbb252017-10-05 10:46:09 +0200187def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100188 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200189 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100190 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200191 if (checkResponse) {
192 cmd = cmd + " && echo Salt command execution success"
193 }
chnydaa0dbb252017-10-05 10:46:09 +0200194 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, [cmd])
Jakub Josef053df392017-05-03 15:51:05 +0200195 if (checkResponse) {
196 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200197 if (out["return"]){
198 for(int i=0;i<out["return"].size();i++){
199 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200200 for(int j=0;j<node.size();j++){
201 def nodeKey = node.keySet()[j]
202 if (!node[nodeKey].contains("Salt command execution success")) {
203 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
204 }
205 }
206 }
207 }else{
208 throw new Exception("Salt Api response doesn't have return param!")
209 }
210 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200211 if (output == true) {
212 printSaltCommandResult(out)
213 }
214 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100215}
216
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200217/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200218 * Checks if salt minion is in a list of salt master's accepted keys
chnydaa0dbb252017-10-05 10:46:09 +0200219 * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3)
220 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200221 * @param target Get pillar target
222 * @param minion_name unique identification of a minion in salt-key command output
223 * @param waitUntilPresent return after the minion becomes present (default true)
224 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
225 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200226 * @param maxRetries finite number of iterations to check status of a command (default 200)
227 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200228 * @return output of salt command
229 */
chnydaa0dbb252017-10-05 10:46:09 +0200230def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200231 minion_name = minion_name.replace("*", "")
232 def common = new com.mirantis.mk.Common()
233 def cmd = 'salt-key | grep ' + minion_name
234 if (waitUntilPresent){
235 def count = 0
236 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200237 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200238 if (output) {
239 printSaltCommandResult(out)
240 }
241 def valueMap = out["return"][0]
242 def result = valueMap.get(valueMap.keySet()[0])
243 def resultsArray = result.tokenize("\n")
244 def size = resultsArray.size()
245 if (size >= answers) {
chnydaa0dbb252017-10-05 10:46:09 +0200246 return out
Jiri Broulik71512bc2017-08-04 10:00:18 +0200247 }
248 count++
249 sleep(time: 500, unit: 'MILLISECONDS')
250 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
251 }
252 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200253 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200254 if (output) {
255 printSaltCommandResult(out)
256 }
257 return out
258 }
259 // otherwise throw exception
260 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
261 throw new Exception("${cmd} signals failure of status check!")
262}
263
264/**
265 * You can call this function when salt-master already contains salt keys of the target_nodes
chnydaa0dbb252017-10-05 10:46:09 +0200266 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200267 * @param target Should always be salt-master
268 * @param target_nodes unique identification of a minion or group of salt minions
269 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
270 * @param wait timeout for the salt command if minions do not return (default 10)
271 * @param maxRetries finite number of iterations to check status of a command (default 200)
272 * @return output of salt command
273 */
chnydaa0dbb252017-10-05 10:46:09 +0200274def minionsReachable(saltId, target, target_nodes, batch=null, wait = 10, maxRetries = 200) {
Jiri Broulik71512bc2017-08-04 10:00:18 +0200275 def common = new com.mirantis.mk.Common()
276 def cmd = "salt -t${wait} -C '${target_nodes}' test.ping"
277 common.infoMsg("Checking if all ${target_nodes} minions are reachable")
278 def count = 0
279 while(count < maxRetries) {
280 Calendar timeout = Calendar.getInstance();
281 timeout.add(Calendar.SECOND, wait);
chnydaa0dbb252017-10-05 10:46:09 +0200282 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, wait)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200283 Calendar current = Calendar.getInstance();
284 if (current.getTime().before(timeout.getTime())) {
285 printSaltCommandResult(out)
286 return out
287 }
288 common.infoMsg("Not all of the targeted '${target_nodes}' minions returned yet. Waiting ...")
289 count++
290 sleep(time: 500, unit: 'MILLISECONDS')
291 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200292}
293
294/**
295 * Run command on salt minion (salt cmd.run wrapper)
chnydaa0dbb252017-10-05 10:46:09 +0200296 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200297 * @param target Get pillar target
298 * @param cmd name of a service
299 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200300 * @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 +0200301 * @param waitUntilOk return after the minion becomes present (optional, default true)
302 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
303 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200304 * @param maxRetries finite number of iterations to check status of a command (default 200)
305 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200306 * @return output of salt command
307 */
chnydaa0dbb252017-10-05 10:46:09 +0200308def 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 +0200309 def common = new com.mirantis.mk.Common()
310 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
311 if (waitUntilOk){
312 def count = 0
313 while(count < maxRetries) {
chnydaa0dbb252017-10-05 10:46:09 +0200314 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200315 if (output) {
316 printSaltCommandResult(out)
317 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200318 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200319 def success = 0
320 if (answers == 0){
321 answers = resultMap.size()
322 }
323 for (int i=0;i<answers;i++) {
324 result = resultMap.get(resultMap.keySet()[i])
325 // if the goal is to find some string in output of the command
326 if (find) {
327 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
328 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
329 success++
330 if (success == answers) {
331 return out
332 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200333 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200334 // else the goal is to not find any string in output of the command
335 } else {
336 if(result instanceof String && result.isEmpty()) {
337 success++
338 if (success == answers) {
339 return out
chnydaa0dbb252017-10-05 10:46:09 +0200340 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200341 }
342 }
343 }
344 count++
345 sleep(time: 500, unit: 'MILLISECONDS')
346 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
347 }
348 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200349 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200350 def resultMap = out["return"][0]
351 if (output) {
352 printSaltCommandResult(out)
353 }
354 for (int i=0;i<resultMap.size();i++) {
355 result = resultMap.get(resultMap.keySet()[i])
356 // if the goal is to find some string in output of the command
357 if (find) {
358 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
359 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200360 return out
361 }
362
363 // else the goal is to not find any string in output of the command
364 } else {
365 if(result instanceof String && result.isEmpty()) {
366 return out
367 }
368 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200369 }
370 }
371 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200372 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200373 throw new Exception("${cmd} signals failure of status check!")
374}
375
Jakub Josef5ade54c2017-03-10 16:14:01 +0100376/**
377 * Perform complete salt sync between master and target
chnydaa0dbb252017-10-05 10:46:09 +0200378 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100379 * @param target Get pillar target
380 * @return output of salt command
381 */
chnydaa0dbb252017-10-05 10:46:09 +0200382def syncAll(saltId, target) {
383 return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100384}
385
Jakub Josef5ade54c2017-03-10 16:14:01 +0100386/**
387 * Enforce highstate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200388 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100389 * @param target Highstate enforcing target
390 * @param output print output (optional, default true)
391 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200392 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100393 * @return output of salt command
394 */
chnydaa0dbb252017-10-05 10:46:09 +0200395def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null) {
396 def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000397 def common = new com.mirantis.mk.Common()
398
Marek Celoud63366112017-07-25 17:27:24 +0200399 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000400
Jakub Josef374beb72017-04-27 15:45:09 +0200401 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100402 return out
403}
404
Jakub Josef5ade54c2017-03-10 16:14:01 +0100405/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100406 * Get running minions IDs according to the target
chnydaa0dbb252017-10-05 10:46:09 +0200407 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Ales Komarek5276ebe2017-03-16 08:46:34 +0100408 * @param target Get minions target
409 * @return list of active minions fitin
410 */
chnydaa0dbb252017-10-05 10:46:09 +0200411def getMinions(saltId, target) {
412 def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100413 return new ArrayList<String>(minionsRaw['return'][0].keySet())
414}
415
416
417/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200418 * Test if there are any minions to target
chnydaa0dbb252017-10-05 10:46:09 +0200419 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200420 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400421 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200422 */
423
chnydaa0dbb252017-10-05 10:46:09 +0200424def testTarget(saltId, target) {
425 return getMinions(saltId, target).size() > 0
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200426}
427
428/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100429 * Generates node key using key.gen_accept call
chnydaa0dbb252017-10-05 10:46:09 +0200430 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100431 * @param target Key generating target
432 * @param host Key generating host
433 * @param keysize generated key size (optional, default 4096)
434 * @return output of salt command
435 */
chnydaa0dbb252017-10-05 10:46:09 +0200436def generateNodeKey(saltId, target, host, keysize = 4096) {
437 return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100438}
439
Jakub Josef5ade54c2017-03-10 16:14:01 +0100440/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200441 * Generates node reclass metadata
chnydaa0dbb252017-10-05 10:46:09 +0200442 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100443 * @param target Metadata generating target
444 * @param host Metadata generating host
445 * @param classes Reclass classes
446 * @param parameters Reclass parameters
447 * @return output of salt command
448 */
chnydaa0dbb252017-10-05 10:46:09 +0200449def generateNodeMetadata(saltId, target, host, classes, parameters) {
450 return runSaltCommand(saltId, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100451}
452
Jakub Josef5ade54c2017-03-10 16:14:01 +0100453/**
454 * Run salt orchestrate on given targets
chnydaa0dbb252017-10-05 10:46:09 +0200455 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100456 * @param target Orchestration target
457 * @param orchestrate Salt orchestrate params
458 * @return output of salt command
459 */
chnydaa0dbb252017-10-05 10:46:09 +0200460def orchestrateSystem(saltId, target, orchestrate) {
461 return runSaltCommand(saltId, 'runner', target, 'state.orchestrate', [orchestrate])
Jakub Josef79ecec32017-02-17 14:36:28 +0100462}
463
Jakub Josef5ade54c2017-03-10 16:14:01 +0100464/**
465 * Run salt process step
chnydaa0dbb252017-10-05 10:46:09 +0200466 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100467 * @param tgt Salt process step target
468 * @param fun Salt process step function
469 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200470 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100471 * @param output print output (optional, default false)
Jiri Broulik48544be2017-06-14 18:33:54 +0200472 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100473 * @return output of salt command
474 */
chnydaa0dbb252017-10-05 10:46:09 +0200475def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = false, timeout = -1, kwargs = null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100476 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200477 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100478 def out
479
Marek Celoud63366112017-07-25 17:27:24 +0200480 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100481
Filip Pytlounf0435c02017-03-02 17:48:54 +0100482 if (batch == true) {
chnydaa0dbb252017-10-05 10:46:09 +0200483 out = runSaltCommand(saltId, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, kwargs, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100484 } else {
chnydaa0dbb252017-10-05 10:46:09 +0200485 out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100486 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100487
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100488 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200489 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100490 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200491 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100492}
493
494/**
495 * Check result for errors and throw exception if any found
496 *
497 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200498 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200499 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200500 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef79ecec32017-02-17 14:36:28 +0100501 */
Jakub Josef374beb72017-04-27 15:45:09 +0200502def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100503 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100504 if(result != null){
505 if(result['return']){
506 for (int i=0;i<result['return'].size();i++) {
507 def entry = result['return'][i]
508 if (!entry) {
509 if (failOnError) {
510 throw new Exception("Salt API returned empty response: ${result}")
511 } else {
512 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100513 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100514 }
515 for (int j=0;j<entry.size();j++) {
516 def nodeKey = entry.keySet()[j]
517 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200518 def outputResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100519 common.infoMsg("Node ${nodeKey} changes:")
520 if(node instanceof Map || node instanceof List){
521 for (int k=0;k<node.size();k++) {
522 def resource;
523 def resKey;
524 if(node instanceof Map){
525 resKey = node.keySet()[k]
526 }else if(node instanceof List){
527 resKey = k
528 }
529 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200530 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200531 if(printResults){
532 if(resource instanceof Map && resource.keySet().contains("result")){
533 //clean unnesaccary fields
534 if(resource.keySet().contains("__run_num__")){
535 resource.remove("__run_num__")
536 }
537 if(resource.keySet().contains("__id__")){
538 resource.remove("__id__")
539 }
540 if(resource.keySet().contains("pchanges")){
541 resource.remove("pchanges")
542 }
543 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
544 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200545 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200546 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200547 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200548 }
549 }else{
550 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200551 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200552 }
553 }
554 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200555 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200556 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100557 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200558 common.debugMsg("checkResult: checking resource: ${resource}")
559 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josefbceaa322017-06-13 18:28:27 +0200560 def prettyResource = common.prettify(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200561 if(env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true"){
562 timeout(time:1, unit:'HOURS') {
563 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
564 }
565 }else{
Jakub Josefd97d7db2017-05-11 19:11:53 +0200566 common.errorMsg(String.format("Resource: %s\n%s", resKey, prettyResource))
Jakub Josefd9001df2017-05-11 16:45:28 +0200567 def errorMsg = "Salt state on node ${nodeKey} failed: ${prettyResource}."
Jakub Josefc4c40202017-04-28 12:04:24 +0200568 if (failOnError) {
569 throw new Exception(errorMsg)
570 } else {
571 common.errorMsg(errorMsg)
572 }
573 }
574 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100575 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200576 }else if(node!=null && node!=""){
Jakub Josef62f6c842017-08-04 16:36:35 +0200577 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200578 }
579 if(printResults && !outputResources.isEmpty()){
Jakub Josefe6c562e2017-08-09 14:41:03 +0200580 print outputResources.stream().collect(Collectors.joining("\n"))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100581 }
582 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100583 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100584 }else{
585 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100586 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100587 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200588 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100589 }
590}
591
592/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100593 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100594 *
595 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100596 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100597def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100598 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100599 if(result != null){
600 if(result['return']){
601 for (int i=0; i<result['return'].size(); i++) {
602 def entry = result['return'][i]
603 for (int j=0; j<entry.size(); j++) {
604 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
605 def nodeKey = entry.keySet()[j]
606 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200607 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100608 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100609 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100610 }else{
611 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100612 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100613 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100614 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100615 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100616}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200617
618
619/**
620 * Return content of file target
621 *
chnydaa0dbb252017-10-05 10:46:09 +0200622 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200623 * @param target Compound target (should target only one host)
624 * @param file File path to read (/etc/hosts for example)
625 */
626
chnydaa0dbb252017-10-05 10:46:09 +0200627def getFileContent(saltId, target, file) {
628 result = cmdRun(saltId, target, "cat ${file}")
Tomáš Kukrálf1a692a2017-08-11 13:29:28 +0200629 return result['return'][0].values()[0].replaceAll('Salt command execution success','')
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200630}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300631
632/**
633 * Set override parameters in Salt cluster metadata
634 *
chnydaa0dbb252017-10-05 10:46:09 +0200635 * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300636 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +0300637 * @param reclass_dir Directory where Reclass git repo is located
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300638 */
639
chnydaa0dbb252017-10-05 10:46:09 +0200640def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass") {
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200641 def common = new com.mirantis.mk.Common()
Mykyta Karpin1c165e22017-08-22 18:27:01 +0300642 def salt_overrides_map = readYaml text: salt_overrides
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200643 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300644 def key = entry[0]
645 def value = entry[1]
646
647 common.debugMsg("Set salt override ${key}=${value}")
chnydaa0dbb252017-10-05 10:46:09 +0200648 runSaltProcessStep(saltId, 'I@salt:master', 'reclass.cluster_meta_set', ["${key}", "${value}"], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300649 }
chnydaa0dbb252017-10-05 10:46:09 +0200650 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 +0300651}
Oleg Grigorovbec45582017-09-12 20:29:24 +0300652
653/**
654* Execute salt commands via salt-api with
655* CLI client salt-pepper
656*
657* @param data Salt command map
658* @param venv Path to virtualenv with
659*/
660
661def runPepperCommand(data, venv) {
662 def python = new com.mirantis.mk.Python()
663 def dataStr = new groovy.json.JsonBuilder(data).toString()
664
665 def pepperCmd = "pepper -c ${venv}/pepperrc --make-token --json \'${dataStr}\'"
666
667 if (venv) {
668 output = python.runVirtualenvCommand(venv, pepperCmd)
669 } else {
670 echo("[Command]: ${pepperCmd}")
671 output = sh (
672 script: pepperCmd,
673 returnStdout: true
674 ).trim()
675 }
676
677 return new groovy.json.JsonSlurperClassic().parseText(output)
678}