blob: 3e870faffb7685756ce50a75be21f45d28b28fb4 [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
2
Jakub Josefb77c0812017-03-27 14:11:01 +02003import java.util.stream.Collectors
Jakub Josef79ecec32017-02-17 14:36:28 +01004/**
5 * Salt functions
6 *
7*/
8
9/**
10 * Salt connection and context parameters
11 *
12 * @param url Salt API server URL
13 * @param credentialsID ID of credentials store entry
14 */
15def connection(url, credentialsId = "salt") {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010016 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +010017 params = [
18 "url": url,
19 "credentialsId": credentialsId,
20 "authToken": null,
21 "creds": common.getCredentials(credentialsId)
22 ]
23 params["authToken"] = saltLogin(params)
24
25 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/**
45 * Run action using Salt API
46 *
47 * @param master Salt connection object
48 * @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
55 */
56@NonCPS
57def runSaltCommand(master, client, target, function, batch = null, args = null, kwargs = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +040058 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010059
60 data = [
61 'tgt': target.expression,
62 'fun': function,
63 'client': client,
64 'expr_form': target.type,
65 ]
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
80 headers = [
81 'X-Auth-Token': "${master.authToken}"
82 ]
83
84 return http.sendHttpPostRequest("${master.url}/", data, headers)
85}
86
Jakub Josef5ade54c2017-03-10 16:14:01 +010087/**
88 * Return pillar for given master and target
89 * @param master Salt connection object
90 * @param target Get pillar target
91 * @param pillar pillar name (optional)
92 * @return output of salt command
93 */
Ales Komarekcec24d42017-03-08 10:25:45 +010094def getPillar(master, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +010095 if (pillar != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +010096 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +010097 } else {
Jakub Josef5ade54c2017-03-10 16:14:01 +010098 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +010099 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100100}
101
Jakub Josef5ade54c2017-03-10 16:14:01 +0100102/**
103 * Return grain for given master and target
104 * @param master Salt connection object
105 * @param target Get grain target
106 * @param grain grain name (optional)
107 * @return output of salt command
108 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100109def getGrain(master, target, grain = null) {
110 if(grain != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100111 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.item', null, [grain])
112 } else {
113 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100114 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100115}
116
Jakub Josef5ade54c2017-03-10 16:14:01 +0100117/**
118 * Enforces state on given master and target
119 * @param master Salt connection object
120 * @param target State enforcing target
121 * @param state Salt state
122 * @param output print output (optional, default true)
123 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200124 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100125 * @return output of salt command
126 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200127def enforceState(master, target, state, output = true, failOnError = true, batch = null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100128 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100129 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100130
Jakub Josef79ecec32017-02-17 14:36:28 +0100131 if (state instanceof String) {
132 run_states = state
133 } else {
134 run_states = state.join(',')
135 }
136
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100137 common.infoMsg("Enforcing state ${run_states} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100138
Jakub Josef2f25cf22017-03-28 13:34:57 +0200139 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', batch, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100140
Jakub Josef374beb72017-04-27 15:45:09 +0200141 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100142 return out
143}
144
Jakub Josef5ade54c2017-03-10 16:14:01 +0100145/**
146 * Run command on salt minion (salt cmd.run wrapper)
147 * @param master Salt connection object
148 * @param target Get pillar target
149 * @param cmd command
Jakub Josef2f25cf22017-03-28 13:34:57 +0200150 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100151 * @return output of salt command
152 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200153def cmdRun(master, target, cmd, batch=null) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100154 def common = new com.mirantis.mk.Common()
155
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100156 common.infoMsg("Running command ${cmd} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100157
Jakub Josef2f25cf22017-03-28 13:34:57 +0200158 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100159}
160
Jakub Josef5ade54c2017-03-10 16:14:01 +0100161/**
162 * Perform complete salt sync between master and target
163 * @param master Salt connection object
164 * @param target Get pillar target
165 * @return output of salt command
166 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100167def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100168 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100169}
170
Jakub Josef5ade54c2017-03-10 16:14:01 +0100171/**
172 * Enforce highstate on given targets
173 * @param master Salt connection object
174 * @param target Highstate enforcing target
175 * @param output print output (optional, default true)
176 * @param failOnError throw exception on salt state result:false (optional, default true)
Jakub Josef2f25cf22017-03-28 13:34:57 +0200177 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100178 * @return output of salt command
179 */
Jakub Josef2f25cf22017-03-28 13:34:57 +0200180def enforceHighstate(master, target, output = false, failOnError = true, batch = null) {
181 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch)
Jakub Josef374beb72017-04-27 15:45:09 +0200182 checkResult(out, failOnError, output)
Jakub Josef79ecec32017-02-17 14:36:28 +0100183 return out
184}
185
Jakub Josef5ade54c2017-03-10 16:14:01 +0100186/**
Ales Komarek5276ebe2017-03-16 08:46:34 +0100187 * Get running minions IDs according to the target
188 * @param master Salt connection object
189 * @param target Get minions target
190 * @return list of active minions fitin
191 */
192def getMinions(master, target) {
193 def minionsRaw = runSaltCommand(master, 'local', target, 'test.ping')
194 return new ArrayList<String>(minionsRaw['return'][0].keySet())
195}
196
197
198/**
Jakub Josef5ade54c2017-03-10 16:14:01 +0100199 * Generates node key using key.gen_accept call
200 * @param master Salt connection object
201 * @param target Key generating target
202 * @param host Key generating host
203 * @param keysize generated key size (optional, default 4096)
204 * @return output of salt command
205 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100206def generateNodeKey(master, target, host, keysize = 4096) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100207 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100208}
209
Jakub Josef5ade54c2017-03-10 16:14:01 +0100210/**
Jakub Josef2f25cf22017-03-28 13:34:57 +0200211 * Generates node reclass metadata
Jakub Josef5ade54c2017-03-10 16:14:01 +0100212 * @param master Salt connection object
213 * @param target Metadata generating target
214 * @param host Metadata generating host
215 * @param classes Reclass classes
216 * @param parameters Reclass parameters
217 * @return output of salt command
218 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100219def generateNodeMetadata(master, target, host, classes, parameters) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100220 return runSaltCommand(master, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100221}
222
Jakub Josef5ade54c2017-03-10 16:14:01 +0100223/**
224 * Run salt orchestrate on given targets
225 * @param master Salt connection object
226 * @param target Orchestration target
227 * @param orchestrate Salt orchestrate params
228 * @return output of salt command
229 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100230def orchestrateSystem(master, target, orchestrate) {
231 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
232}
233
Jakub Josef5ade54c2017-03-10 16:14:01 +0100234/**
235 * Run salt process step
236 * @param master Salt connection object
237 * @param tgt Salt process step target
238 * @param fun Salt process step function
239 * @param arg process step arguments (optional, default [])
Jakub Josef2f25cf22017-03-28 13:34:57 +0200240 * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch)
Jakub Josef5ade54c2017-03-10 16:14:01 +0100241 * @param output print output (optional, default false)
242 * @return output of salt command
243 */
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100244def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100245 def common = new com.mirantis.mk.Common()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100246 def out
247
Tomas Kukrale90bb342017-03-02 21:30:35 +0000248 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100249
Filip Pytlounf0435c02017-03-02 17:48:54 +0100250 if (batch == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100251 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
252 } else {
253 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100254 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100255
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100256 if (output == true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100257 printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100258 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100259}
260
261/**
262 * Check result for errors and throw exception if any found
263 *
264 * @param result Parsed response of Salt API
Jakub Josef8021c002017-03-27 15:41:28 +0200265 * @param failOnError Do you want to throw exception if salt-call fails (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200266 * @param printResults Do you want to print salt results (optional, default true)
Jakub Josefa87941c2017-04-20 17:14:58 +0200267 * @param printOnlyChanges If true (default), print only changed resources
Jakub Josef79ecec32017-02-17 14:36:28 +0100268 */
Jakub Josef374beb72017-04-27 15:45:09 +0200269def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100270 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100271 if(result != null){
272 if(result['return']){
273 for (int i=0;i<result['return'].size();i++) {
274 def entry = result['return'][i]
275 if (!entry) {
276 if (failOnError) {
277 throw new Exception("Salt API returned empty response: ${result}")
278 } else {
279 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefece32af2017-03-14 19:20:08 +0100280 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100281 }
282 for (int j=0;j<entry.size();j++) {
283 def nodeKey = entry.keySet()[j]
284 def node=entry[nodeKey]
Jakub Josefa87941c2017-04-20 17:14:58 +0200285 def outputResources = []
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100286 common.infoMsg("Node ${nodeKey} changes:")
287 if(node instanceof Map || node instanceof List){
288 for (int k=0;k<node.size();k++) {
289 def resource;
290 def resKey;
291 if(node instanceof Map){
292 resKey = node.keySet()[k]
293 }else if(node instanceof List){
294 resKey = k
295 }
296 resource = node[resKey]
Jakub Josefc4c40202017-04-28 12:04:24 +0200297 // print
Jakub Josefa87941c2017-04-20 17:14:58 +0200298 if(printResults){
299 if(resource instanceof Map && resource.keySet().contains("result")){
300 //clean unnesaccary fields
301 if(resource.keySet().contains("__run_num__")){
302 resource.remove("__run_num__")
303 }
304 if(resource.keySet().contains("__id__")){
305 resource.remove("__id__")
306 }
307 if(resource.keySet().contains("pchanges")){
308 resource.remove("pchanges")
309 }
310 if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
311 if(resource["result"] != null){
312 outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettyPrint(resource)))
313 }else{
314 outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettyPrint(resource)))
315 }
316 }else{
317 if(!printOnlyChanges || resource.changes.size() > 0){
318 outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettyPrint(resource)))
319 }
320 }
321 }else{
322 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettyPrint(resource)))
323 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100324 }
Jakub Josefc4c40202017-04-28 12:04:24 +0200325 common.debugMsg("checkResult: checking resource: ${resource}")
326 if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){
327 def prettyResource = common.prettyPrint(resource)
328 if(env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true"){
329 timeout(time:1, unit:'HOURS') {
330 input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?"
331 }
332 }else{
333 print(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, prettyResource))
334 def errorMsg = "Salt state on node ${nodeKey} failed: ${prettyResource}. State output: ${node}"
335 if (failOnError) {
336 throw new Exception(errorMsg)
337 } else {
338 common.errorMsg(errorMsg)
339 }
340 }
341 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100342 }
Jakub Josefa87941c2017-04-20 17:14:58 +0200343 }else if(node!=null && node!=""){
344 outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettyPrint(node)))
345 }
346 if(printResults && !outputResources.isEmpty()){
Jakub Josefb77c0812017-03-27 14:11:01 +0200347 wrap([$class: 'AnsiColorBuildWrapper']) {
348 print outputResources.stream().collect(Collectors.joining("\n"))
349 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100350 }
351 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100352 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100353 }else{
354 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100355 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100356 }else{
Jakub Josefa87941c2017-04-20 17:14:58 +0200357 common.errorMsg("Cannot check salt result, given result is null")
Jakub Josef79ecec32017-02-17 14:36:28 +0100358 }
359}
360
361/**
Jakub Josef7852fe12017-03-15 16:02:41 +0100362 * Print salt command run results in human-friendly form
Jakub Josef79ecec32017-02-17 14:36:28 +0100363 *
364 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100365 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100366def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100367 def common = new com.mirantis.mk.Common()
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100368 if(result != null){
369 if(result['return']){
370 for (int i=0; i<result['return'].size(); i++) {
371 def entry = result['return'][i]
372 for (int j=0; j<entry.size(); j++) {
373 common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}")
374 def nodeKey = entry.keySet()[j]
375 def node=entry[nodeKey]
Jakub Josefb41c8d52017-03-24 13:52:24 +0100376 common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettyPrint(node)))
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100377 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100378 }
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100379 }else{
380 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100381 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100382 }else{
Jakub Josefd9afd0e2017-03-15 19:19:23 +0100383 common.errorMsg("Cannot print salt command result, given result is null")
Jakub Josef52f69f72017-03-14 15:18:08 +0100384 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100385}
Tomáš Kukrálb12eedd2017-04-21 10:45:13 +0200386
387
388/**
389 * Return content of file target
390 *
391 * @param master Salt master object
392 * @param target Compound target (should target only one host)
393 * @param file File path to read (/etc/hosts for example)
394 */
395
396def getFileContent(master, target, file) {
397 result = cmdRun(master, target, "cat ${file}")
398 return result['return'][0].values()[0]
399}