blob: c040fb5c0cddb5e8a93ca1c8f9ee9bb932232851 [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
Jakub Josef79ecec32017-02-17 14:36:28 +010057 */
58@NonCPS
Jiri Broulik48544be2017-06-14 18:33:54 +020059def runSaltCommand(master, client, target, function, batch = null, args = null, kwargs = null, timeout = -1) {
iberezovskiyd4240b52017-02-20 17:18:28 +040060 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010061
62 data = [
63 'tgt': target.expression,
64 'fun': function,
65 'client': client,
66 'expr_form': target.type,
67 ]
68
Jakub Josef5f838212017-04-06 12:43:58 +020069 if(batch != null && ( (batch instanceof Integer && batch > 0) || (batch instanceof String && batch.contains("%")))){
Jakub Josef2f25cf22017-03-28 13:34:57 +020070 data['client']= "local_batch"
71 data['batch'] = batch
Jakub Josef79ecec32017-02-17 14:36:28 +010072 }
73
74 if (args) {
75 data['arg'] = args
76 }
77
78 if (kwargs) {
79 data['kwarg'] = kwargs
80 }
81
Jiri Broulik48544be2017-06-14 18:33:54 +020082 if (timeout != -1) {
83 data['timeout'] = timeout
84 }
85
Jakub Josef79ecec32017-02-17 14:36:28 +010086 headers = [
87 'X-Auth-Token': "${master.authToken}"
88 ]
89
90 return http.sendHttpPostRequest("${master.url}/", data, headers)
91}
92
Jakub Josef5ade54c2017-03-10 16:14:01 +010093/**
94 * Return pillar for given master and target
95 * @param master Salt connection object
96 * @param target Get pillar target
97 * @param pillar pillar name (optional)
98 * @return output of salt command
99 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100100def getPillar(master, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +0100101 if (pillar != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100102 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +0100103 } else {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100104 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +0100105 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100106}
107
Jakub Josef5ade54c2017-03-10 16:14:01 +0100108/**
109 * Return grain for given master and target
110 * @param master Salt connection object
111 * @param target Get grain target
112 * @param grain grain name (optional)
113 * @return output of salt command
114 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100115def getGrain(master, target, grain = null) {
116 if(grain != null) {
Jiri Broulik852dfd52017-05-16 13:38:55 +0200117 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grains.item', null, [grain])
Jakub Josef5ade54c2017-03-10 16:14:01 +0100118 } else {
Jiri Broulik852dfd52017-05-16 13:38:55 +0200119 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grains.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100120 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100121}
122
Jakub Josef5ade54c2017-03-10 16:14:01 +0100123/**
124 * Enforces state on given master and target
125 * @param master Salt connection object
126 * @param target State enforcing target
127 * @param state Salt state
128 * @param output print output (optional, default true)
129 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200130 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Martin Polreich1c77afa2017-07-18 11:27:02 +0200131 * @param optional don't fail on empty response from salt caused by 'No minions matched the targed' if set to true (default false)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100132 * @return output of salt command
133 */
Martin Polreich1c77afa2017-07-18 11:27:02 +0200134def enforceState(master, target, state, output = true, failOnError = true, batch = null, optional = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100135 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100136 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100137
Jakub Josef79ecec32017-02-17 14:36:28 +0100138 if (state instanceof String) {
139 run_states = state
140 } else {
141 run_states = state.join(',')
142 }
143
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100144 common.infoMsg("Enforcing state ${run_states} on ${target}")
Martin Polreich1c77afa2017-07-18 11:27:02 +0200145 if (optional==false){
146 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states])
147 checkResult(out, failOnError, output)
148 return out
149 } else if (testTarget(master, target)) {
150 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states])
151 checkResult(out, failOnError, output)
152 return out
153 } else {
154 common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ")
155 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100156}
157
Jakub Josef5ade54c2017-03-10 16:14:01 +0100158/**
159 * Run command on salt minion (salt cmd.run wrapper)
160 * @param master Salt connection object
161 * @param target Get pillar target
162 * @param cmd command
Jakub Josef053df392017-05-03 15:51:05 +0200163 * @param checkResponse test command success execution (default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200164 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200165 * @param output do you want to print output
Jakub Josef5ade54c2017-03-10 16:14:01 +0100166 * @return output of salt command
167 */
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200168def cmdRun(master, target, cmd, checkResponse = true, batch=null, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100169 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200170 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100171 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200172 if (checkResponse) {
173 cmd = cmd + " && echo Salt command execution success"
174 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200175 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, [cmd])
Jakub Josef053df392017-05-03 15:51:05 +0200176 if (checkResponse) {
177 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200178 if (out["return"]){
179 for(int i=0;i<out["return"].size();i++){
180 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200181 for(int j=0;j<node.size();j++){
182 def nodeKey = node.keySet()[j]
183 if (!node[nodeKey].contains("Salt command execution success")) {
184 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
185 }
186 }
187 }
188 }else{
189 throw new Exception("Salt Api response doesn't have return param!")
190 }
191 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200192 if (output == true) {
193 printSaltCommandResult(out)
194 }
195 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100196}
197
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200198
199/**
200 * Run command on salt minion (salt cmd.run wrapper)
201 * @param master Salt connection object
202 * @param target Get pillar target
203 * @param minion_name unique identification of a minion in salt-key command output
204 * @param waitUntilPresent return after the minion becomes present (default true)
205 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
206 * @param output print salt command (default true)
207 * @return output of salt command
208 */
Jakub Josef115a78f2017-07-18 15:04:00 +0200209def minionPresent(master, target, minion_name, waitUntilPresent = true, batch=null, output = true) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200210 return command_status(master, target, 'salt-key | grep ' + minion_name, minion_name, waitUntilPresent, batch, output)
211}
212
213/**
214 * Run command on salt minion (salt cmd.run wrapper)
215 * @param master Salt connection object
216 * @param target Get pillar target
217 * @param cmd name of a service
218 * @param correct_state string that command must contain if status is in correct state (optional, default 'running')
219 * @param waitUntilOk return after the minion becomes present (optional, default true)
220 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
221 * @param output print salt command (default true)
222 * @return output of salt command
223 */
Jakub Josef115a78f2017-07-18 15:04:00 +0200224def commandStatus(master, target, cmd, correct_state='running', waitUntilOk = true, batch=null, output = true, maxRetries = 200) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200225 def common = new com.mirantis.mk.Common()
226 common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state")
227 if (waitUntilOk){
228 def count = 0
229 while(count < maxRetries) {
230 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd])
Jakub Josef115a78f2017-07-18 15:04:00 +0200231 def resultMap = out["return"][0]
232 def result = resultMap.get(resultMap.keySet()[0])
233 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200234 if (output) {
235 printSaltCommandResult(out)
236 }
237 return out
238 }
239 count++
240 sleep(time: 500, unit: 'MILLISECONDS')
241 }
242 } else {
243 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd])
Jakub Josef115a78f2017-07-18 15:04:00 +0200244 def resultMap = out["return"][0]
245 def result = resultMap.get(resultMap.keySet()[0])
246 if (result.toLowerCase().contains(correct_state.toLowerCase())) {
Jiri Broulik2c69f3d2017-07-18 14:23:58 +0200247 if (output) {
248 printSaltCommandResult(out)
249 }
250 return out
251 }
252 }
253 // otherwise throw exception
254 throw new Exception("${cmd} signals failure of status check!")
255}
256
257
Jakub Josef5ade54c2017-03-10 16:14:01 +0100258/**
259 * Perform complete salt sync between master and target
260 * @param master Salt connection object
261 * @param target Get pillar target
262 * @return output of salt command
263 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100264def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100265 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100266}
267
Jakub Josef5ade54c2017-03-10 16:14:01 +0100268/**
269 * Enforce highstate on given targets
270 * @param master Salt connection object
271 * @param target Highstate enforcing target
272 * @param output print output (optional, default true)
273 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200274 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100275 * @return output of salt command
276 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200277def enforceHighstate(master, target, output = false, failOnError = true, batch = null) {
278 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000279 def common = new com.mirantis.mk.Common()
280
281 common.infoMsg("Running step state.highstate on ${target}")
282
Jakub Josef374beb72017-04-27 15:45:09 +0200283 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100284 return out
285}
286
Jakub Josef5ade54c2017-03-10 16:14:01 +0100287/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100288 * Get running minions IDs according to the target
289 * @param master Salt connection object
290 * @param target Get minions target
291 * @return list of active minions fitin
292 */
293def getMinions(master, target) {
Tomáš Kukrál18ac50f2017-07-13 10:22:09 +0200294 def minionsRaw = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100295 return new ArrayList<String>(minionsRaw['return'][0].keySet())
296}
297
298
299/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200300 * Test if there are any minions to target
301 * @param master Salt connection object
302 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400303 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200304 */
305
306def testTarget(master, target) {
307 return getMinions(master, target).size() > 0
308}
309
310/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100311 * Generates node key using key.gen_accept call
312 * @param master Salt connection object
313 * @param target Key generating target
314 * @param host Key generating host
315 * @param keysize generated key size (optional, default 4096)
316 * @return output of salt command
317 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100318def generateNodeKey(master, target, host, keysize = 4096) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100319 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100320}
321
Jakub Josef5ade54c2017-03-10 16:14:01 +0100322/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200323 * Generates node reclass metadata
Jakub Josef5ade54c2017-03-10 16:14:01 +0100324 * @param master Salt connection object
325 * @param target Metadata generating target
326 * @param host Metadata generating host
327 * @param classes Reclass classes
328 * @param parameters Reclass parameters
329 * @return output of salt command
330 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100331def generateNodeMetadata(master, target, host, classes, parameters) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100332 return runSaltCommand(master, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100333}
334
Jakub Josef5ade54c2017-03-10 16:14:01 +0100335/**
336 * Run salt orchestrate on given targets
337 * @param master Salt connection object
338 * @param target Orchestration target
339 * @param orchestrate Salt orchestrate params
340 * @return output of salt command
341 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100342def orchestrateSystem(master, target, orchestrate) {
343 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
344}
345
Jakub Josef5ade54c2017-03-10 16:14:01 +0100346/**
347 * Run salt process step
348 * @param master Salt connection object
349 * @param tgt Salt process step target
350 * @param fun Salt process step function
351 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200352 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100353 * @param output print output (optional, default false)
Jiri Broulik48544be2017-06-14 18:33:54 +0200354 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100355 * @return output of salt command
356 */
Jiri Broulik48544be2017-06-14 18:33:54 +0200357def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false, timeout = -1) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100358 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200359 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100360 def out
361
Tomas Kukrale90bb342017-03-02 21:30:35 +0000362 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100363
Filip Pytlounf0435c02017-03-02 17:48:54 +0100364 if (batch == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200365 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, null, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100366 } else {
Jiri Broulik48544be2017-06-14 18:33:54 +0200367 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, null, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100368 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100369
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100370 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200371 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100372 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200373 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100374}
375
376/**
377 * Check result for errors and throw exception if any found
378 *
379 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200380 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200381 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200382 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef79ecec32017-02-17 14:36:28 +0100383 */
Jakub Josef374beb72017-04-27 15:45:09 +0200384def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100385 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100386 if(result != null){
387 if(result['return']){
388 for (int i=0;i<result['return'].size();i++) {
389 def entry = result['return'][i]
390 if (!entry) {
391 if (failOnError) {
392 throw new Exception("Salt API returned empty response: ${result}")
393 } else {
394 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100395 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100396 }
397 for (int j=0;j<entry.size();j++) {
398 def nodeKey = entry.keySet()[j]
399 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200400 def outputResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100401 common.infoMsg("Node ${nodeKey} changes:")
402 if(node instanceof Map || node instanceof List){
403 for (int k=0;k<node.size();k++) {
404 def resource;
405 def resKey;
406 if(node instanceof Map){
407 resKey = node.keySet()[k]
408 }else if(node instanceof List){
409 resKey = k
410 }
411 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200412 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200413 if(printResults){
414 if(resource instanceof Map && resource.keySet().contains("result")){
415 //clean unnesaccary fields
416 if(resource.keySet().contains("__run_num__")){
417 resource.remove("__run_num__")
418 }
419 if(resource.keySet().contains("__id__")){
420 resource.remove("__id__")
421 }
422 if(resource.keySet().contains("pchanges")){
423 resource.remove("pchanges")
424 }
425 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
426 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200427 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200428 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200429 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200430 }
431 }else{
432 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200433 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200434 }
435 }
436 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200437 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200438 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100439 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200440 common.debugMsg("checkResult: checking resource: ${resource}")
441 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josefbceaa322017-06-13 18:28:27 +0200442 def prettyResource = common.prettify(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200443 if(env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true"){
444 timeout(time:1, unit:'HOURS') {
445 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
446 }
447 }else{
Jakub Josefd97d7db2017-05-11 19:11:53 +0200448 common.errorMsg(String.format("Resource: %s\n%s", resKey, prettyResource))
Jakub Josefd9001df2017-05-11 16:45:28 +0200449 def errorMsg = "Salt state on node ${nodeKey} failed: ${prettyResource}."
Jakub Josefc4c40202017-04-28 12:04:24 +0200450 if (failOnError) {
451 throw new Exception(errorMsg)
452 } else {
453 common.errorMsg(errorMsg)
454 }
455 }
456 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100457 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200458 }else if(node!=null && node!=""){
Jakub Josefbceaa322017-06-13 18:28:27 +0200459 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200460 }
461 if(printResults && !outputResources.isEmpty()){
Jakub Josefb77c0812017-03-27 14:11:01 +0200462 wrap([$class: 'AnsiColorBuildWrapper']) {
463 print outputResources.stream().collect(Collectors.joining("\n"))
464 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100465 }
466 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100467 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100468 }else{
469 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100470 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100471 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200472 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100473 }
474}
475
476/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100477 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100478 *
479 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100480 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100481def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100482 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100483 if(result != null){
484 if(result['return']){
485 for (int i=0; i<result['return'].size(); i++) {
486 def entry = result['return'][i]
487 for (int j=0; j<entry.size(); j++) {
488 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
489 def nodeKey = entry.keySet()[j]
490 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200491 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100492 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100493 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100494 }else{
495 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100496 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100497 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100498 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100499 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100500}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200501
502
503/**
504 * Return content of file target
505 *
506 * @param master Salt master object
507 * @param target Compound target (should target only one host)
508 * @param file File path to read (/etc/hosts for example)
509 */
510
511def getFileContent(master, target, file) {
512 result = cmdRun(master, target, "cat ${file}")
513 return result['return'][0].values()[0]
514}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300515
516/**
517 * Set override parameters in Salt cluster metadata
518 *
519 * @param master Salt master object
520 * @param salt_overrides YAML formatted string containing key: value, one per line
521 */
522
523def setSaltOverrides(master, salt_overrides, debug=false) {
524 def mcpcommon = new com.mirantis.mcp.Common()
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200525 def common = new com.mirantis.mk.Common()
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300526
527 def salt_overrides_map = mcpcommon.loadYAML(salt_overrides)
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200528 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300529 def key = entry[0]
530 def value = entry[1]
531
532 common.debugMsg("Set salt override ${key}=${value}")
533 runSaltProcessStep(master, 'I@salt:master', 'reclass.cluster_meta_set', ["${key}", "${value}"], false, debug)
534 }
535}