blob: f0d0cc82770ebf38520656bce0e2c553d7812fef [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)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100165 * @return output of salt command
166 */
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200167def cmdRun(master, target, cmd, checkResponse = true, batch=null, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100168 def common = new com.mirantis.mk.Common()
Jakub Josef053df392017-05-03 15:51:05 +0200169 def originalCmd = cmd
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100170 common.infoMsg("Running command ${cmd} on ${target}")
Jakub Josef053df392017-05-03 15:51:05 +0200171 if (checkResponse) {
172 cmd = cmd + " && echo Salt command execution success"
173 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200174 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, [cmd])
Jakub Josef053df392017-05-03 15:51:05 +0200175 if (checkResponse) {
176 // iterate over all affected nodes and check success return code
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200177 if (out["return"]){
178 for(int i=0;i<out["return"].size();i++){
179 def node = out["return"][i];
Jakub Josef053df392017-05-03 15:51:05 +0200180 for(int j=0;j<node.size();j++){
181 def nodeKey = node.keySet()[j]
182 if (!node[nodeKey].contains("Salt command execution success")) {
183 throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}")
184 }
185 }
186 }
187 }else{
188 throw new Exception("Salt Api response doesn't have return param!")
189 }
190 }
Jiri Broulik16e9ce72017-05-17 13:28:31 +0200191 if (output == true) {
192 printSaltCommandResult(out)
193 }
194 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100195}
196
Jakub Josef5ade54c2017-03-10 16:14:01 +0100197/**
198 * Perform complete salt sync between master and target
199 * @param master Salt connection object
200 * @param target Get pillar target
201 * @return output of salt command
202 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100203def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100204 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100205}
206
Jakub Josef5ade54c2017-03-10 16:14:01 +0100207/**
208 * Enforce highstate on given targets
209 * @param master Salt connection object
210 * @param target Highstate enforcing target
211 * @param output print output (optional, default true)
212 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200213 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100214 * @return output of salt command
215 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200216def enforceHighstate(master, target, output = false, failOnError = true, batch = null) {
217 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch)
Alexander Noskov657ccfc2017-07-14 11:35:52 +0000218 def common = new com.mirantis.mk.Common()
219
220 common.infoMsg("Running step state.highstate on ${target}")
221
Jakub Josef374beb72017-04-27 15:45:09 +0200222 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100223 return out
224}
225
Jakub Josef5ade54c2017-03-10 16:14:01 +0100226/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100227 * Get running minions IDs according to the target
228 * @param master Salt connection object
229 * @param target Get minions target
230 * @return list of active minions fitin
231 */
232def getMinions(master, target) {
Tomáš Kukrál18ac50f2017-07-13 10:22:09 +0200233 def minionsRaw = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'test.ping')
Ales Komarek5276ebe2017-03-16 08:46:34 +0100234 return new ArrayList<String>(minionsRaw['return'][0].keySet())
235}
236
237
238/**
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200239 * Test if there are any minions to target
240 * @param master Salt connection object
241 * @param target Target to test
vrovachev1c4770b2017-07-05 13:25:21 +0400242 * @return bool indicating if target was succesful
Tomáš Kukrálb12ff9f2017-07-12 12:32:34 +0200243 */
244
245def testTarget(master, target) {
246 return getMinions(master, target).size() > 0
247}
248
249/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100250 * Generates node key using key.gen_accept call
251 * @param master Salt connection object
252 * @param target Key generating target
253 * @param host Key generating host
254 * @param keysize generated key size (optional, default 4096)
255 * @return output of salt command
256 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100257def generateNodeKey(master, target, host, keysize = 4096) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100258 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100259}
260
Jakub Josef5ade54c2017-03-10 16:14:01 +0100261/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200262 * Generates node reclass metadata
Jakub Josef5ade54c2017-03-10 16:14:01 +0100263 * @param master Salt connection object
264 * @param target Metadata generating target
265 * @param host Metadata generating host
266 * @param classes Reclass classes
267 * @param parameters Reclass parameters
268 * @return output of salt command
269 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100270def generateNodeMetadata(master, target, host, classes, parameters) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100271 return runSaltCommand(master, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100272}
273
Jakub Josef5ade54c2017-03-10 16:14:01 +0100274/**
275 * Run salt orchestrate on given targets
276 * @param master Salt connection object
277 * @param target Orchestration target
278 * @param orchestrate Salt orchestrate params
279 * @return output of salt command
280 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100281def orchestrateSystem(master, target, orchestrate) {
282 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
283}
284
Jakub Josef5ade54c2017-03-10 16:14:01 +0100285/**
286 * Run salt process step
287 * @param master Salt connection object
288 * @param tgt Salt process step target
289 * @param fun Salt process step function
290 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200291 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100292 * @param output print output (optional, default false)
Jiri Broulik48544be2017-06-14 18:33:54 +0200293 * @param timeout Additional argument salt api timeout
Jakub Josef5ade54c2017-03-10 16:14:01 +0100294 * @return output of salt command
295 */
Jiri Broulik48544be2017-06-14 18:33:54 +0200296def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false, timeout = -1) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100297 def common = new com.mirantis.mk.Common()
Jiri Broulik48544be2017-06-14 18:33:54 +0200298 def salt = new com.mirantis.mk.Salt()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100299 def out
300
Tomas Kukrale90bb342017-03-02 21:30:35 +0000301 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100302
Filip Pytlounf0435c02017-03-02 17:48:54 +0100303 if (batch == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200304 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, null, timeout)
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100305 } else {
Jiri Broulik48544be2017-06-14 18:33:54 +0200306 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, null, timeout)
Jakub Josef79ecec32017-02-17 14:36:28 +0100307 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100308
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100309 if (output == true) {
Jiri Broulik48544be2017-06-14 18:33:54 +0200310 salt.printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100311 }
Jiri Broulikae19c262017-05-16 19:06:52 +0200312 return out
Jakub Josef79ecec32017-02-17 14:36:28 +0100313}
314
315/**
316 * Check result for errors and throw exception if any found
317 *
318 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200319 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200320 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200321 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef79ecec32017-02-17 14:36:28 +0100322 */
Jakub Josef374beb72017-04-27 15:45:09 +0200323def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100324 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100325 if(result != null){
326 if(result['return']){
327 for (int i=0;i<result['return'].size();i++) {
328 def entry = result['return'][i]
329 if (!entry) {
330 if (failOnError) {
331 throw new Exception("Salt API returned empty response: ${result}")
332 } else {
333 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100334 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100335 }
336 for (int j=0;j<entry.size();j++) {
337 def nodeKey = entry.keySet()[j]
338 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200339 def outputResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100340 common.infoMsg("Node ${nodeKey} changes:")
341 if(node instanceof Map || node instanceof List){
342 for (int k=0;k<node.size();k++) {
343 def resource;
344 def resKey;
345 if(node instanceof Map){
346 resKey = node.keySet()[k]
347 }else if(node instanceof List){
348 resKey = k
349 }
350 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200351 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200352 if(printResults){
353 if(resource instanceof Map && resource.keySet().contains("result")){
354 //clean unnesaccary fields
355 if(resource.keySet().contains("__run_num__")){
356 resource.remove("__run_num__")
357 }
358 if(resource.keySet().contains("__id__")){
359 resource.remove("__id__")
360 }
361 if(resource.keySet().contains("pchanges")){
362 resource.remove("pchanges")
363 }
364 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
365 if(resource["result"] != null){
Jakub Josefbceaa322017-06-13 18:28:27 +0200366 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200367 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200368 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200369 }
370 }else{
371 if(!printOnlyChanges || resource.changes.size() > 0){
Jakub Josefbceaa322017-06-13 18:28:27 +0200372 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200373 }
374 }
375 }else{
Jakub Josefbceaa322017-06-13 18:28:27 +0200376 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200377 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100378 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200379 common.debugMsg("checkResult: checking resource: ${resource}")
380 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
Jakub Josefbceaa322017-06-13 18:28:27 +0200381 def prettyResource = common.prettify(resource)
Jakub Josefc4c40202017-04-28 12:04:24 +0200382 if(env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true"){
383 timeout(time:1, unit:'HOURS') {
384 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
385 }
386 }else{
Jakub Josefd97d7db2017-05-11 19:11:53 +0200387 common.errorMsg(String.format("Resource: %s\n%s", resKey, prettyResource))
Jakub Josefd9001df2017-05-11 16:45:28 +0200388 def errorMsg = "Salt state on node ${nodeKey} failed: ${prettyResource}."
Jakub Josefc4c40202017-04-28 12:04:24 +0200389 if (failOnError) {
390 throw new Exception(errorMsg)
391 } else {
392 common.errorMsg(errorMsg)
393 }
394 }
395 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100396 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200397 }else if(node!=null && node!=""){
Jakub Josefbceaa322017-06-13 18:28:27 +0200398 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(node)))
Jakub Josefa87941c2017-04-20 17:14:58 +0200399 }
400 if(printResults && !outputResources.isEmpty()){
Jakub Josefb77c0812017-03-27 14:11:01 +0200401 wrap([$class: 'AnsiColorBuildWrapper']) {
402 print outputResources.stream().collect(Collectors.joining("\n"))
403 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100404 }
405 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100406 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100407 }else{
408 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100409 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100410 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200411 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100412 }
413}
414
415/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100416 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100417 *
418 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100419 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100420def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100421 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100422 if(result != null){
423 if(result['return']){
424 for (int i=0; i<result['return'].size(); i++) {
425 def entry = result['return'][i]
426 for (int j=0; j<entry.size(); j++) {
427 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
428 def nodeKey = entry.keySet()[j]
429 def node=entry[nodeKey]
Jakub Josefbceaa322017-06-13 18:28:27 +0200430 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100431 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100432 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100433 }else{
434 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100435 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100436 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100437 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100438 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100439}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200440
441
442/**
443 * Return content of file target
444 *
445 * @param master Salt master object
446 * @param target Compound target (should target only one host)
447 * @param file File path to read (/etc/hosts for example)
448 */
449
450def getFileContent(master, target, file) {
451 result = cmdRun(master, target, "cat ${file}")
452 return result['return'][0].values()[0]
453}
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300454
455/**
456 * Set override parameters in Salt cluster metadata
457 *
458 * @param master Salt master object
459 * @param salt_overrides YAML formatted string containing key: value, one per line
460 */
461
462def setSaltOverrides(master, salt_overrides, debug=false) {
463 def mcpcommon = new com.mirantis.mcp.Common()
Tomáš Kukrálf178f052017-07-11 11:31:00 +0200464 def common = new com.mirantis.mk.Common()
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300465
466 def salt_overrides_map = mcpcommon.loadYAML(salt_overrides)
Tomáš Kukrál243cf842017-07-11 13:11:56 +0200467 for (entry in common.entries(salt_overrides_map)) {
Matthew Mosesohn9e880852017-07-04 21:17:53 +0300468 def key = entry[0]
469 def value = entry[1]
470
471 common.debugMsg("Set salt override ${key}=${value}")
472 runSaltProcessStep(master, 'I@salt:master', 'reclass.cluster_meta_set', ["${key}", "${value}"], false, debug)
473 }
474}