blob: 97f86abdad9177f28b5ebc73833c9f44b34216aa [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)
25
26 return params
27}
28
29/**
30 * Login to Salt API, return auth token
31 *
32 * @param master Salt connection object
33 */
34def saltLogin(master) {
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010035 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010036 data = [
37 'username': master.creds.username,
38 'password': master.creds.password.toString(),
39 'eauth': 'pam'
40 ]
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010041 authToken = http.restGet(master, '/login', data)['return'][0]['token']
Jakub Josef79ecec32017-02-17 14:36:28 +010042 return authToken
43}
44
45/**
46 * Run action using Salt API
47 *
48 * @param master Salt connection object
49 * @param client Client type
50 * @param target Target specification, eg. for compound matches by Pillar
51 * data: ['expression': 'I@openssh:server', 'type': 'compound'])
52 * @param function Function to execute (eg. "state.sls")
Jakub Josef2f25cf22017-03-28 13:34:57 +020053 * @param batch Batch param to salt (integer or string with percents)
Jakub Josef79ecec32017-02-17 14:36:28 +010054 * @param args Additional arguments to function
55 * @param kwargs Additional key-value arguments to function
Jiri Broulik48544be2017-06-14 18:33:54 +020056 * @param timeout Additional argument salt api timeout
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +030057 * @param read_timeout http session read timeout
Jakub Josef79ecec32017-02-17 14:36:28 +010058 */
59@NonCPS
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +030060def runSaltCommand(master, client, target, function, batch = null, args = null, kwargs = null, timeout = -1, read_timeout = -1) {
iberezovskiyd4240b52017-02-20 17:18:28 +040061 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010062
63 data = [
64 'tgt': target.expression,
65 'fun': function,
66 'client': client,
67 'expr_form': target.type,
68 ]
69
Jakub Josef5f838212017-04-06 12:43:58 +020070 if(batch != null && ( (batch instanceof Integer && batch > 0) || (batch instanceof String && batch.contains("%")))){
Jakub Josef2f25cf22017-03-28 13:34:57 +020071 data['client']= "local_batch"
72 data['batch'] = batch
Jakub Josef79ecec32017-02-17 14:36:28 +010073 }
74
75 if (args) {
76 data['arg'] = args
77 }
78
79 if (kwargs) {
80 data['kwarg'] = kwargs
81 }
82
Jiri Broulik48544be2017-06-14 18:33:54 +020083 if (timeout != -1) {
84 data['timeout'] = timeout
85 }
86
Jakub Josef79ecec32017-02-17 14:36:28 +010087 headers = [
88 'X-Auth-Token': "${master.authToken}"
89 ]
90
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +030091 return http.sendHttpPostRequest("${master.url}/", data, headers, read_timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +010092}
93
Jakub Josef5ade54c2017-03-10 16:14:01 +010094/**
95 * Return pillar for given master and target
96 * @param master Salt connection object
97 * @param target Get pillar target
98 * @param pillar pillar name (optional)
99 * @return output of salt command
100 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100101def getPillar(master, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +0100102 if (pillar != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100103 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +0100104 } else {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100105 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +0100106 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100107}
108
Jakub Josef5ade54c2017-03-10 16:14:01 +0100109/**
110 * Return grain for given master and target
111 * @param master Salt connection object
112 * @param target Get grain target
113 * @param grain grain name (optional)
114 * @return output of salt command
115 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100116def getGrain(master, target, grain = null) {
117 if(grain != null) {
Jiri Broulik852dfd52017-05-16 13:38:55 +0200118 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grains.item', null, [grain])
Jakub Josef5ade54c2017-03-10 16:14:01 +0100119 } else {
Jiri Broulik852dfd52017-05-16 13:38:55 +0200120 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grains.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100121 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100122}
123
Jakub Josef5ade54c2017-03-10 16:14:01 +0100124/**
125 * Enforces state on given master and target
126 * @param master Salt connection object
127 * @param target State enforcing target
128 * @param state Salt state
129 * @param output print output (optional, default true)
130 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200131 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300132 * @param read_timeout http session read timeout
133 * @param retries Retry count for salt state.
Jakub Josef5ade54c2017-03-10 16:14:01 +0100134 * @return output of salt command
135 */
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300136def enforceState(master, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100137 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100138 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100139
Jakub Josef79ecec32017-02-17 14:36:28 +0100140 if (state instanceof String) {
141 run_states = state
142 } else {
143 run_states = state.join(',')
144 }
145
Marek Celoud63366112017-07-25 17:27:24 +0200146 common.infoMsg("Running state ${run_states} on ${target}")
Vasyl Saienkoe36ab7c2017-07-17 14:35:48 +0300147 def out
148
149 if (optional == false || testTarget(master, target)){
150 if (retries != -1){
151 retry(retries){
152 out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states], null, -1, read_timeout)
153 }
154 }
155 else {
156 out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states], null, -1, read_timeout)
157 }
Martin Polreich1c77afa2017-07-18 11:27:02 +0200158 checkResult(out, failOnError, output)
159 return out
Martin Polreich1c77afa2017-07-18 11:27:02 +0200160 } else {
161 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
162 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100163}
164
Jakub Josef5ade54c2017-03-10 16:14:01 +0100165/**
166 * Run command on salt minion (salt cmd.run wrapper)
167 * @param master Salt connection object
168 * @param target Get pillar target
169 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200170 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200171 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200172 * @param output do you want to print output
Jakub Josef5ade54c2017-03-10 16:14:01 +0100173 * @return output of salt command
174 */
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200175def cmdRun(master, target, cmd, checkResponse = true, batch=null, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100176 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200177 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100178 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200179 if (checkResponse) {
180 cmd = cmd + " && echo Salt command execution success"
181 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200182 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, [cmd])
Jakub Josef053df392017-05-03 15:51:05 +0200183 if (checkResponse) {
184 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200185 if (out["return"]){
186 for(int i=0;i<out["return"].size();i++){
187 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200188 for(int j=0;j<node.size();j++){
189 def nodeKey = node.keySet()[j]
190 if (!node[nodeKey].contains("Salt command execution success")) {
191 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
192 }
193 }
194 }
195 }else{
196 throw new Exception("Salt Api response doesn't have return param!")
197 }
198 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200199 if (output == true) {
200 printSaltCommandResult(out)
201 }
202 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100203}
204
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200205/**
Jiri Broulik71512bc2017-08-04 10:00:18 +0200206 * Checks if salt minion is in a list of salt master's accepted keys
207 * @usage minionPresent(saltMaster, 'I@salt:master', 'ntw', true, null, true, 200, 3)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200208 * @param master Salt connection object
209 * @param target Get pillar target
210 * @param minion_name unique identification of a minion in salt-key command output
211 * @param waitUntilPresent return after the minion becomes present (default true)
212 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
213 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200214 * @param maxRetries finite number of iterations to check status of a command (default 200)
215 * @param answers how many minions should return (optional, default 1)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200216 * @return output of salt command
217 */
Jiri Broulik71512bc2017-08-04 10:00:18 +0200218def minionPresent(master, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) {
219 minion_name = minion_name.replace("*", "")
220 def common = new com.mirantis.mk.Common()
221 def cmd = 'salt-key | grep ' + minion_name
222 if (waitUntilPresent){
223 def count = 0
224 while(count < maxRetries) {
225 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
226 if (output) {
227 printSaltCommandResult(out)
228 }
229 def valueMap = out["return"][0]
230 def result = valueMap.get(valueMap.keySet()[0])
231 def resultsArray = result.tokenize("\n")
232 def size = resultsArray.size()
233 if (size >= answers) {
234 return out
235 }
236 count++
237 sleep(time: 500, unit: 'MILLISECONDS')
238 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
239 }
240 } else {
241 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
242 if (output) {
243 printSaltCommandResult(out)
244 }
245 return out
246 }
247 // otherwise throw exception
248 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
249 throw new Exception("${cmd} signals failure of status check!")
250}
251
252/**
253 * You can call this function when salt-master already contains salt keys of the target_nodes
254 * @param master Salt connection object
255 * @param target Should always be salt-master
256 * @param target_nodes unique identification of a minion or group of salt minions
257 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
258 * @param wait timeout for the salt command if minions do not return (default 10)
259 * @param maxRetries finite number of iterations to check status of a command (default 200)
260 * @return output of salt command
261 */
262def minionsReachable(master, target, target_nodes, batch=null, wait = 10, maxRetries = 200) {
263 def common = new com.mirantis.mk.Common()
264 def cmd = "salt -t${wait} -C '${target_nodes}' test.ping"
265 common.infoMsg("Checking if all ${target_nodes} minions are reachable")
266 def count = 0
267 while(count < maxRetries) {
268 Calendar timeout = Calendar.getInstance();
269 timeout.add(Calendar.SECOND, wait);
270 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, wait)
271 Calendar current = Calendar.getInstance();
272 if (current.getTime().before(timeout.getTime())) {
273 printSaltCommandResult(out)
274 return out
275 }
276 common.infoMsg("Not all of the targeted '${target_nodes}' minions returned yet. Waiting ...")
277 count++
278 sleep(time: 500, unit: 'MILLISECONDS')
279 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200280}
281
282/**
283 * Run command on salt minion (salt cmd.run wrapper)
284 * @param master Salt connection object
285 * @param target Get pillar target
286 * @param cmd name of a service
287 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
Jiri Broulikcf1f2332017-07-25 11:30:03 +0200288 * @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 +0200289 * @param waitUntilOk return after the minion becomes present (optional, default true)
290 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
291 * @param output print salt command (default true)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200292 * @param maxRetries finite number of iterations to check status of a command (default 200)
293 * @param answers how many minions should return (optional, default 0)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200294 * @return output of salt command
295 */
Jiri Broulik71512bc2017-08-04 10:00:18 +0200296def commandStatus(master, target, cmd, correct_state='running', find = true, waitUntilOk = true, batch=null, output = true, maxRetries = 200, answers = 0) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200297 def common = new com.mirantis.mk.Common()
298 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
299 if (waitUntilOk){
300 def count = 0
301 while(count < maxRetries) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200302 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
Jiri Broulik71512bc2017-08-04 10:00:18 +0200303 if (output) {
304 printSaltCommandResult(out)
305 }
Jakub Josef115a78f2017-07-18 15:04:00 +0200306 def resultMap = out["return"][0]
Jiri Broulik71512bc2017-08-04 10:00:18 +0200307 def success = 0
308 if (answers == 0){
309 answers = resultMap.size()
310 }
311 for (int i=0;i<answers;i++) {
312 result = resultMap.get(resultMap.keySet()[i])
313 // if the goal is to find some string in output of the command
314 if (find) {
315 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
316 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
317 success++
318 if (success == answers) {
319 return out
320 }
Jiri Broulikd0c27572017-07-24 20:01:10 +0200321 }
Jiri Broulik71512bc2017-08-04 10:00:18 +0200322 // else the goal is to not find any string in output of the command
323 } else {
324 if(result instanceof String && result.isEmpty()) {
325 success++
326 if (success == answers) {
327 return out
328 }
329 }
330 }
331 }
332 count++
333 sleep(time: 500, unit: 'MILLISECONDS')
334 common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state")
335 }
336 } else {
337 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5)
338 def resultMap = out["return"][0]
339 if (output) {
340 printSaltCommandResult(out)
341 }
342 for (int i=0;i<resultMap.size();i++) {
343 result = resultMap.get(resultMap.keySet()[i])
344 // if the goal is to find some string in output of the command
345 if (find) {
346 if(result == null || result instanceof Boolean || result.isEmpty()) { result='' }
347 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulikd0c27572017-07-24 20:01:10 +0200348 return out
349 }
350
351 // else the goal is to not find any string in output of the command
352 } else {
353 if(result instanceof String && result.isEmpty()) {
354 return out
355 }
356 }
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200357 }
358 }
359 // otherwise throw exception
Jiri Broulikd0c27572017-07-24 20:01:10 +0200360 common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.")
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200361 throw new Exception("${cmd} signals failure of status check!")
362}
363
Jakub Josef5ade54c2017-03-10 16:14:01 +0100364/**
365 * Perform complete salt sync between master and target
366 * @param master Salt connection object
367 * @param target Get pillar target
368 * @return output of salt command
369 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100370def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100371 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100372}
373
Jakub Josef5ade54c2017-03-10 16:14:01 +0100374/**
375 * Enforce highstate on given targets
376 * @param master Salt connection object
377 * @param target Highstate enforcing target
378 * @param output print output (optional, default true)
379 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200380 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100381 * @return output of salt command
382 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200383def enforceHighstate(master, target, output = false, failOnError = true, batch = null) {
384 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000385 def common = new com.mirantis.mk.Common()
386
Marek Celoud63366112017-07-25 17:27:24 +0200387 common.infoMsg("Running state highstate on ${target}")
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000388
Jakub Josef374beb72017-04-27 15:45:09 +0200389 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100390 return out
391}
392
Jakub Josef5ade54c2017-03-10 16:14:01 +0100393/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100394 * Get running minions IDs according to the target
395 * @param master Salt connection object
396 * @param target Get minions target
397 * @return list of active minions fitin
398 */
399def getMinions(master, target) {
Tomáš Kukrál18ac50f2017-07-13 10:22:09 +0200400 def minionsRaw = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100401 return new ArrayList<String>(minionsRaw['return'][0].keySet())
402}
403
404
405/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200406 * Test if there are any minions to target
407 * @param master Salt connection object
408 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400409 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200410 */
411
412def testTarget(master, target) {
413 return getMinions(master, target).size() > 0
414}
415
416/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100417 * Generates node key using key.gen_accept call
418 * @param master Salt connection object
419 * @param target Key generating target
420 * @param host Key generating host
421 * @param keysize generated key size (optional, default 4096)
422 * @return output of salt command
423 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100424def generateNodeKey(master, target, host, keysize = 4096) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100425 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100426}
427
Jakub Josef5ade54c2017-03-10 16:14:01 +0100428/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200429 * Generates node reclass metadata
Jakub Josef5ade54c2017-03-10 16:14:01 +0100430 * @param master Salt connection object
431 * @param target Metadata generating target
432 * @param host Metadata generating host
433 * @param classes Reclass classes
434 * @param parameters Reclass parameters
435 * @return output of salt command
436 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100437def generateNodeMetadata(master, target, host, classes, parameters) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100438 return runSaltCommand(master, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100439}
440
Jakub Josef5ade54c2017-03-10 16:14:01 +0100441/**
442 * Run salt orchestrate on given targets
443 * @param master Salt connection object
444 * @param target Orchestration target
445 * @param orchestrate Salt orchestrate params
446 * @return output of salt command
447 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100448def orchestrateSystem(master, target, orchestrate) {
449 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
450}
451
Jakub Josef5ade54c2017-03-10 16:14:01 +0100452/**
453 * Run salt process step
454 * @param master Salt connection object
455 * @param tgt Salt process step target
456 * @param fun Salt process step function
457 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200458 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100459 * @param output print output (optional, default false)
Jiri Broulik48544be2017-06-14 18:33:54 +0200460 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100461 * @return output of salt command
462 */
Jiri Broulik48544be2017-06-14 18:33:54 +0200463def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false, timeout = -1) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100464 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200465 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100466 def out
467
Marek Celoud63366112017-07-25 17:27:24 +0200468 common.infoMsg("Running step ${fun} ${arg} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100469
Filip Pytlounf0435c02017-03-02 17:48:54 +0100470 if (batch == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200471 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, null, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100472 } else {
Jiri Broulik48544be2017-06-14 18:33:54 +0200473 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, null, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100474 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100475
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100476 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200477 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100478 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200479 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100480}
481
482/**
483 * Check result for errors and throw exception if any found
484 *
485 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200486 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200487 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200488 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef79ecec32017-02-17 14:36:28 +0100489 */
Jakub Josef374beb72017-04-27 15:45:09 +0200490def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100491 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100492 if(result != null){
493 if(result['return']){
494 for (int i=0;i<result['return'].size();i++) {
495 def entry = result['return'][i]
496 if (!entry) {
497 if (failOnError) {
498 throw new Exception("Salt API returned empty response: ${result}")
499 } else {
500 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100501 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100502 }
503 for (int j=0;j<entry.size();j++) {
504 def nodeKey = entry.keySet()[j]
505 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200506 def outputResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100507 common.infoMsg("Node ${nodeKey} changes:")
508 if(node instanceof Map || node instanceof List){
509 for (int k=0;k<node.size();k++) {
510 def resource;
511 def resKey;
512 if(node instanceof Map){
513 resKey = node.keySet()[k]
514 }else if(node instanceof List){
515 resKey = k
516 }
517 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200518 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200519 if(printResults){
520 if(resource instanceof Map && resource.keySet().contains("result")){
521 //clean unnesaccary fields
522 if(resource.keySet().contains("__run_num__")){
523 resource.remove("__run_num__")
524 }
525 if(resource.keySet().contains("__id__")){
526 resource.remove("__id__")
527 }
528 if(resource.keySet().contains("pchanges")){
529 resource.remove("pchanges")
530 }
531 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
532 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200533 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200534 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200535 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200536 }
537 }else{
538 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200539 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200540 }
541 }
542 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200543 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200544 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100545 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200546 common.debugMsg("checkResult: checking resource: ${resource}")
547 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josefbceaa322017-06-13 18:28:27 +0200548 def prettyResource = common.prettify(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200549 if(env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true"){
550 timeout(time:1, unit:'HOURS') {
551 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
552 }
553 }else{
Jakub Josefd97d7db2017-05-11 19:11:53 +0200554 common.errorMsg(String.format("Resource: %s\n%s", resKey, prettyResource))
Jakub Josefd9001df2017-05-11 16:45:28 +0200555 def errorMsg = "Salt state on node ${nodeKey} failed: ${prettyResource}."
Jakub Josefc4c40202017-04-28 12:04:24 +0200556 if (failOnError) {
557 throw new Exception(errorMsg)
558 } else {
559 common.errorMsg(errorMsg)
560 }
561 }
562 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100563 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200564 }else if(node!=null && node!=""){
Jakub Josefbceaa322017-06-13 18:28:27 +0200565 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200566 }
567 if(printResults && !outputResources.isEmpty()){
Jakub Josefb77c0812017-03-27 14:11:01 +0200568 wrap([$class: 'AnsiColorBuildWrapper']) {
569 print outputResources.stream().collect(Collectors.joining("\n"))
570 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100571 }
572 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100573 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100574 }else{
575 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100576 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100577 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200578 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100579 }
580}
581
582/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100583 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100584 *
585 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100586 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100587def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100588 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100589 if(result != null){
590 if(result['return']){
591 for (int i=0; i<result['return'].size(); i++) {
592 def entry = result['return'][i]
593 for (int j=0; j<entry.size(); j++) {
594 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
595 def nodeKey = entry.keySet()[j]
596 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200597 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100598 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100599 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100600 }else{
601 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100602 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100603 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100604 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100605 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100606}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200607
608
609/**
610 * Return content of file target
611 *
612 * @param master Salt master object
613 * @param target Compound target (should target only one host)
614 * @param file File path to read (/etc/hosts for example)
615 */
616
617def getFileContent(master, target, file) {
618 result = cmdRun(master, target, "cat ${file}")
619 return result['return'][0].values()[0]
620}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300621
622/**
623 * Set override parameters in Salt cluster metadata
624 *
625 * @param master Salt master object
626 * @param salt_overrides YAML formatted string containing key: value, one per line
Matthew Mosesohne5646842017-07-19 16:54:57 +0300627 * @param reclass_dir Directory where Reclass git repo is located
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300628 */
629
Matthew Mosesohne5646842017-07-19 16:54:57 +0300630def setSaltOverrides(master, salt_overrides, reclass_dir="/srv/salt/reclass") {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300631 def mcpcommon = new com.mirantis.mcp.Common()
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200632 def common = new com.mirantis.mk.Common()
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300633
634 def salt_overrides_map = mcpcommon.loadYAML(salt_overrides)
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200635 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300636 def key = entry[0]
637 def value = entry[1]
638
639 common.debugMsg("Set salt override ${key}=${value}")
Matthew Mosesohn29c9e332017-07-25 14:00:17 +0300640 runSaltProcessStep(master, 'I@salt:master', 'reclass.cluster_meta_set', ["${key}", "${value}"], false)
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300641 }
Matthew Mosesohne5646842017-07-19 16:54:57 +0300642 runSaltProcessStep(master, 'I@salt:master', 'cmd.run', ["git -C ${reclass_dir} update-index --skip-worktree classes/cluster/overrides.yml"])
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300643}