blob: 285de0037eae5f787689954e5b7686b802cb7d57 [file] [log] [blame]
Jakub Josef79ecec32017-02-17 14:36:28 +01001package com.mirantis.mk
2
3/**
4 * Salt functions
5 *
6*/
7
8/**
9 * Salt connection and context parameters
10 *
11 * @param url Salt API server URL
12 * @param credentialsID ID of credentials store entry
13 */
14def connection(url, credentialsId = "salt") {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010015 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +010016 params = [
17 "url": url,
18 "credentialsId": credentialsId,
19 "authToken": null,
20 "creds": common.getCredentials(credentialsId)
21 ]
22 params["authToken"] = saltLogin(params)
23
24 return params
25}
26
27/**
28 * Login to Salt API, return auth token
29 *
30 * @param master Salt connection object
31 */
32def saltLogin(master) {
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010033 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010034 data = [
35 'username': master.creds.username,
36 'password': master.creds.password.toString(),
37 'eauth': 'pam'
38 ]
Tomáš Kukrál7bec0532017-02-20 15:39:31 +010039 authToken = http.restGet(master, '/login', data)['return'][0]['token']
Jakub Josef79ecec32017-02-17 14:36:28 +010040 return authToken
41}
42
43/**
44 * Run action using Salt API
45 *
46 * @param master Salt connection object
47 * @param client Client type
48 * @param target Target specification, eg. for compound matches by Pillar
49 * data: ['expression': 'I@openssh:server', 'type': 'compound'])
50 * @param function Function to execute (eg. "state.sls")
Filip Pytlounf0435c02017-03-02 17:48:54 +010051 * @param batch
Jakub Josef79ecec32017-02-17 14:36:28 +010052 * @param args Additional arguments to function
53 * @param kwargs Additional key-value arguments to function
54 */
55@NonCPS
56def runSaltCommand(master, client, target, function, batch = null, args = null, kwargs = null) {
iberezovskiyd4240b52017-02-20 17:18:28 +040057 def http = new com.mirantis.mk.Http()
Jakub Josef79ecec32017-02-17 14:36:28 +010058
59 data = [
60 'tgt': target.expression,
61 'fun': function,
62 'client': client,
63 'expr_form': target.type,
64 ]
65
Filip Pytlounf0435c02017-03-02 17:48:54 +010066 if (batch == true) {
67 data['batch'] = "local_batch"
Jakub Josef79ecec32017-02-17 14:36:28 +010068 }
69
70 if (args) {
71 data['arg'] = args
72 }
73
74 if (kwargs) {
75 data['kwarg'] = kwargs
76 }
77
78 headers = [
79 'X-Auth-Token': "${master.authToken}"
80 ]
81
82 return http.sendHttpPostRequest("${master.url}/", data, headers)
83}
84
Jakub Josef5ade54c2017-03-10 16:14:01 +010085/**
86 * Return pillar for given master and target
87 * @param master Salt connection object
88 * @param target Get pillar target
89 * @param pillar pillar name (optional)
90 * @return output of salt command
91 */
Ales Komarekcec24d42017-03-08 10:25:45 +010092def getPillar(master, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +010093 if (pillar != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +010094 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Tomáš Kukráld2589702017-03-10 16:30:46 +010095 } else {
Jakub Josef5ade54c2017-03-10 16:14:01 +010096 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komareka3c7e502017-03-13 11:20:44 +010097 }
Jakub Josef79ecec32017-02-17 14:36:28 +010098}
99
Jakub Josef5ade54c2017-03-10 16:14:01 +0100100/**
101 * Return grain for given master and target
102 * @param master Salt connection object
103 * @param target Get grain target
104 * @param grain grain name (optional)
105 * @return output of salt command
106 */
Ales Komarekcec24d42017-03-08 10:25:45 +0100107def getGrain(master, target, grain = null) {
108 if(grain != null) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100109 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.item', null, [grain])
110 } else {
111 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.items')
Ales Komarekcec24d42017-03-08 10:25:45 +0100112 }
Ales Komarekcec24d42017-03-08 10:25:45 +0100113}
114
Jakub Josef5ade54c2017-03-10 16:14:01 +0100115/**
116 * Enforces state on given master and target
117 * @param master Salt connection object
118 * @param target State enforcing target
119 * @param state Salt state
120 * @param output print output (optional, default true)
121 * @param failOnError throw exception on salt state result:false (optional, default true)
122 * @return output of salt command
123 */
124def enforceState(master, target, state, output = true, failOnError = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100125 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100126 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100127
Jakub Josef79ecec32017-02-17 14:36:28 +0100128 if (state instanceof String) {
129 run_states = state
130 } else {
131 run_states = state.join(',')
132 }
133
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100134 common.infoMsg("Enforcing state ${run_states} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100135
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100136 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', null, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100137
Jakub Josef79ecec32017-02-17 14:36:28 +0100138 try {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100139 checkResult(out, failOnError)
Jakub Josef79ecec32017-02-17 14:36:28 +0100140 } finally {
141 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100142 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100143 }
144 }
145 return out
146}
147
Jakub Josef5ade54c2017-03-10 16:14:01 +0100148/**
149 * Run command on salt minion (salt cmd.run wrapper)
150 * @param master Salt connection object
151 * @param target Get pillar target
152 * @param cmd command
153 * @return output of salt command
154 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100155def cmdRun(master, target, cmd) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100156 def common = new com.mirantis.mk.Common()
157
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100158 common.infoMsg("Running command ${cmd} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100159
Jakub Josef5ade54c2017-03-10 16:14:01 +0100160 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100161}
162
Jakub Josef5ade54c2017-03-10 16:14:01 +0100163/**
164 * Perform complete salt sync between master and target
165 * @param master Salt connection object
166 * @param target Get pillar target
167 * @return output of salt command
168 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100169def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100170 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100171}
172
Jakub Josef5ade54c2017-03-10 16:14:01 +0100173/**
174 * Enforce highstate on given targets
175 * @param master Salt connection object
176 * @param target Highstate enforcing target
177 * @param output print output (optional, default true)
178 * @param failOnError throw exception on salt state result:false (optional, default true)
179 * @return output of salt command
180 */
181def enforceHighstate(master, target, output = false, failOnError = true) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100182 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
Jakub Josef79ecec32017-02-17 14:36:28 +0100183 try {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100184 checkResult(out, failOnError)
Jakub Josef79ecec32017-02-17 14:36:28 +0100185 } finally {
186 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100187 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100188 }
189 }
190 return out
191}
192
Jakub Josef5ade54c2017-03-10 16:14:01 +0100193/**
194 * Generates node key using key.gen_accept call
195 * @param master Salt connection object
196 * @param target Key generating target
197 * @param host Key generating host
198 * @param keysize generated key size (optional, default 4096)
199 * @return output of salt command
200 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100201def generateNodeKey(master, target, host, keysize = 4096) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100202 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize])
Jakub Josef79ecec32017-02-17 14:36:28 +0100203}
204
Jakub Josef5ade54c2017-03-10 16:14:01 +0100205/**
206 * Generates node reclass metadata
207 * @param master Salt connection object
208 * @param target Metadata generating target
209 * @param host Metadata generating host
210 * @param classes Reclass classes
211 * @param parameters Reclass parameters
212 * @return output of salt command
213 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100214def generateNodeMetadata(master, target, host, classes, parameters) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100215 return runSaltCommand(master, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters])
Jakub Josef79ecec32017-02-17 14:36:28 +0100216}
217
Jakub Josef5ade54c2017-03-10 16:14:01 +0100218/**
219 * Run salt orchestrate on given targets
220 * @param master Salt connection object
221 * @param target Orchestration target
222 * @param orchestrate Salt orchestrate params
223 * @return output of salt command
224 */
Jakub Josef79ecec32017-02-17 14:36:28 +0100225def orchestrateSystem(master, target, orchestrate) {
226 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
227}
228
Jakub Josef5ade54c2017-03-10 16:14:01 +0100229/**
230 * Run salt process step
231 * @param master Salt connection object
232 * @param tgt Salt process step target
233 * @param fun Salt process step function
234 * @param arg process step arguments (optional, default [])
235 * @param batch using batch (optional, default false)
236 * @param output print output (optional, default false)
237 * @return output of salt command
238 */
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100239def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100240 def common = new com.mirantis.mk.Common()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100241 def out
242
Tomas Kukrale90bb342017-03-02 21:30:35 +0000243 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100244
Filip Pytlounf0435c02017-03-02 17:48:54 +0100245 if (batch == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100246 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
247 } else {
248 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100249 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100250
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100251 if (output == true) {
Jakub Josef5ade54c2017-03-10 16:14:01 +0100252 printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100253 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100254}
255
256/**
257 * Check result for errors and throw exception if any found
258 *
259 * @param result Parsed response of Salt API
Jakub Josef5ade54c2017-03-10 16:14:01 +0100260 * @param failOnError Do you want to throw exception if salt-call fails
Jakub Josef79ecec32017-02-17 14:36:28 +0100261 */
Jakub Josef5ade54c2017-03-10 16:14:01 +0100262def checkResult(result, failOnError = true) {
263 def common = new com.mirantis.mk.Common()
Jakub Josef52f69f72017-03-14 15:18:08 +0100264 if(result['return']){
265 for (int i=0;i<result['return'].size();i++) {
266 def entry = result['return'][i]
267 if (!entry) {
268 if (failOnError) {
269 throw new Exception("Salt API returned empty response: ${result}")
270 } else {
271 common.errorMsg("Salt API returned empty response: ${result}")
Jakub Josefa532efc2017-03-13 14:51:40 +0100272 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100273 }
274 for (int j=0;j<entry.size();j++) {
Jakub Josef26546bd2017-03-14 18:38:00 +0100275 def nodeKey = entry.keySet()[j]
276 def node=entry[nodeKey]
277 for (int k=0;k<node.size();k++) {
Jakub Josefece32af2017-03-14 19:20:08 +0100278 def resource;
279 def resKey;
280 if(node instanceof Map){
281 resKey = node.keySet()[k]
282 }else if(node instanceof List){
283 resKey = k
284 }
285 resource = node[resKey]
Jakub Josef9873dae2017-03-14 19:23:19 +0100286 common.errorMsg("Checking resource: ${resource}")
Jakub Josef871bf152017-03-14 20:13:41 +0100287 if(resource instanceof String || !resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){
Jakub Josef52f69f72017-03-14 15:18:08 +0100288 if (failOnError) {
Jakub Josef9873dae2017-03-14 19:23:19 +0100289 throw new Exception("Salt state on node ${nodeKey} failed: ${resource}. State output: ${node}")
Jakub Josef52f69f72017-03-14 15:18:08 +0100290 } else {
Jakub Josef9873dae2017-03-14 19:23:19 +0100291 common.errorMsg("Salt state on node ${nodeKey} failed: ${resource}. State output: ${node}")
Jakub Josef52f69f72017-03-14 15:18:08 +0100292 }
Jakub Josef5ade54c2017-03-10 16:14:01 +0100293 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100294 }
295 }
296 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100297 }else{
298 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100299 }
300}
301
302/**
303 * Print Salt state run results in human-friendly form
304 *
305 * @param result Parsed response of Salt API
306 * @param onlyChanges If true (default), print only changed resources
307 * parsing
308 */
309def printSaltStateResult(result, onlyChanges = true) {
Tomáš Kukrál6eb45f82017-03-08 18:26:16 +0100310 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100311 def out = [:]
Jakub Josef52f69f72017-03-14 15:18:08 +0100312 if(result['return']){
313 for (int i=0; i<result['return'].size(); i++) {
Jakub Joseff17c5342017-03-14 18:06:50 +0100314 def entry = result['return'][i]
Jakub Josef52f69f72017-03-14 15:18:08 +0100315 for (int j=0; j<entry.size(); j++) {
Jakub Josefb22c65a2017-03-14 15:42:52 +0100316 common.errorMsg("Entry is: ${entry}")
Jakub Josefce90b102017-03-14 16:22:55 +0100317 def nodeKey = entry.keySet()[j]
318 def node=entry[nodeKey]
319 out[nodeKey] = [:]
Jakub Josef8a715bf2017-03-14 21:39:01 +0100320 if(node instanceof Iterable){
321 for (int k=0; k<node.size(); k++) {
322 def resource;
323 def resKey;
324 if(node instanceof Map){
325 resKey = node.keySet()[k]
326 }else if(node instanceof List){
327 resKey=k
328 }
329 resource = node[resKey]
330 if (resource instanceof String) {
331 //ORIGINAL??out[node.key] = node.value
332 out[nodeKey][resKey] = resource
333 } else if (resource.result.toString().toBoolean() == false || resource.changes || onlyChanges == false) {
334 out[nodeKey][resKey] = resource.value
335 }
Jakub Josef4eb2e6a2017-03-14 18:53:35 +0100336 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100337 } else {
338 out[nodeKey] = node.toString();
Jakub Josef79ecec32017-02-17 14:36:28 +0100339 }
340 }
341 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100342
Jakub Josef52f69f72017-03-14 15:18:08 +0100343 for (int i=0; i<out.size(); i++) {
Jakub Josefce90b102017-03-14 16:22:55 +0100344 def nodeKey = out.keySet()[i]
345 def node=out[nodeKey]
346 if (node) {
347 println "Node ${nodeKey} changes:"
348 print new groovy.json.JsonBuilder(node).toPrettyString().replace('\\n', System.getProperty('line.separator'))
Jakub Josef52f69f72017-03-14 15:18:08 +0100349 } else {
Jakub Josefce90b102017-03-14 16:22:55 +0100350 println "No changes for node ${nodeKey}"
Jakub Josef52f69f72017-03-14 15:18:08 +0100351 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100352 }
Jakub Josef52f69f72017-03-14 15:18:08 +0100353 }else{
354 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100355 }
356}
357
358/**
359 * Print Salt state run results in human-friendly form
360 *
361 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100362 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100363def printSaltCommandResult(result) {
Jakub Josef871bf152017-03-14 20:13:41 +0100364 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100365 def out = [:]
Jakub Josef52f69f72017-03-14 15:18:08 +0100366 if(result['return']){
367 for (int i=0; i<result['return'].size(); i++) {
Jakub Joseff17c5342017-03-14 18:06:50 +0100368 def entry = result['return'][i]
Jakub Josef52f69f72017-03-14 15:18:08 +0100369 for (int j=0; j<entry.size(); j++) {
Jakub Josefce90b102017-03-14 16:22:55 +0100370 common.errorMsg("Entry is: ${entry}")
371 def nodeKey = entry.keySet()[j]
372 def node=entry[nodeKey]
373 out[nodeKey] = [:]
Jakub Josef8a715bf2017-03-14 21:39:01 +0100374 if(node instanceof Iterable){
375 for (int k=0; k<node.size(); k++) {
376 def resource;
377 def resKey;
378 if(node instanceof Map){
379 resKey = node.keySet()[k]
380 }else if(node instanceof List){
381 resKey=k
382 }
383 resource = node[resKey]
384 //ORIGINAL??out[node.key] = node.value
385 out[nodeKey][resKey] = resource
Jakub Josef871bf152017-03-14 20:13:41 +0100386 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100387 } else {
388 out[nodeKey] = node.toString();
Jakub Josef52f69f72017-03-14 15:18:08 +0100389 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100390 }
391 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100392
Jakub Josef8a715bf2017-03-14 21:39:01 +0100393 for (int i=0; i<out.size(); i++) {
394 def nodeKey = out.keySet()[i]
395 def node = out[nodeKey]
396 if (node) {
397 common.infoMsg("Node ${nodeKey} changes:")
398 common.infoMsg(new groovy.json.JsonBuilder(node).toPrettyString())
399 } else {
400 common.infoMsg("No changes for node ${nodeKey}")
401 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100402 }
Jakub Josef8a715bf2017-03-14 21:39:01 +0100403 }else{
Jakub Josef52f69f72017-03-14 15:18:08 +0100404 common.errorMsg("Salt result hasn't return attribute! Result: ${result}")
405 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100406}