blob: c2171b3dc9a620b85b92cbc7fcb470834b74e6d3 [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
Ales Komarekcec24d42017-03-08 10:25:45 +010085def getPillar(master, target, pillar = null) {
Tomáš Kukráld2589702017-03-10 16:30:46 +010086 def out
87
88 if (pillar != null) {
89 out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
90 } else {
91 out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
Ales Komarekcec24d42017-03-08 10:25:45 +010092 }
Tomáš Kukráld2589702017-03-10 16:30:46 +010093
Jakub Josef79ecec32017-02-17 14:36:28 +010094 return out
95}
96
Ales Komarekcec24d42017-03-08 10:25:45 +010097
98def getGrain(master, target, grain = null) {
99 if(grain != null) {
100 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.item', null, [grain])
101 }
102 else {
103 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.items')
104 }
105 return out
106}
107
108
Tomáš Kukrálaa8091c2017-03-08 15:46:52 +0100109def enforceState(master, target, state, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100110 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100111 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100112
Jakub Josef79ecec32017-02-17 14:36:28 +0100113 if (state instanceof String) {
114 run_states = state
115 } else {
116 run_states = state.join(',')
117 }
118
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100119 common.infoMsg("Enforcing state ${run_states} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100120
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100121 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', null, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100122
Jakub Josef79ecec32017-02-17 14:36:28 +0100123 try {
124 checkResult(out)
125 } finally {
126 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100127 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100128 }
129 }
130 return out
131}
132
133def cmdRun(master, target, cmd) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100134 def common = new com.mirantis.mk.Common()
135
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100136 common.infoMsg("Running command ${cmd} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100137
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100138 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100139 return out
140}
141
142def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100143 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100144}
145
146def enforceHighstate(master, target, output = false) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100147 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
Jakub Josef79ecec32017-02-17 14:36:28 +0100148 try {
149 checkResult(out)
150 } finally {
151 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100152 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100153 }
154 }
155 return out
156}
157
158def generateNodeKey(master, target, host, keysize = 4096) {
159 args = [host]
160 kwargs = ['keysize': keysize]
161 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', args, kwargs)
162}
163
164def generateNodeMetadata(master, target, host, classes, parameters) {
165 args = [host, '_generated']
166 kwargs = ['classes': classes, 'parameters': parameters]
167 return runSaltCommand(master, 'local', target, 'reclass.node_create', args, kwargs)
168}
169
170def orchestrateSystem(master, target, orchestrate) {
171 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
172}
173
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100174def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100175 def common = new com.mirantis.mk.Common()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100176 def out
177
Tomas Kukrale90bb342017-03-02 21:30:35 +0000178 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100179
Filip Pytlounf0435c02017-03-02 17:48:54 +0100180 if (batch == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100181 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
182 } else {
183 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100184 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100185
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100186 if (output == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100187 printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100188 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100189}
190
191/**
192 * Check result for errors and throw exception if any found
193 *
194 * @param result Parsed response of Salt API
195 */
196def checkResult(result) {
197 for (entry in result['return']) {
198 if (!entry) {
199 throw new Exception("Salt API returned empty response: ${result}")
200 }
201 for (node in entry) {
202 for (resource in node.value) {
Filip Pytloun5d061ea2017-03-09 22:04:42 +0100203 if (resource instanceof String || (resource instanceof Boolean && resource == false) || resource.value.result.toString().toBoolean() != true) {
Filip Pytloun2e3f3be2017-03-10 14:33:19 +0100204 throw new Exception("Salt state on node ${node.key} failed: ${node.value}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100205 }
206 }
207 }
208 }
209}
210
211/**
212 * Print Salt state run results in human-friendly form
213 *
214 * @param result Parsed response of Salt API
215 * @param onlyChanges If true (default), print only changed resources
216 * parsing
217 */
218def printSaltStateResult(result, onlyChanges = true) {
Tomáš Kukrál6eb45f82017-03-08 18:26:16 +0100219 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100220 def out = [:]
221 for (entry in result['return']) {
222 for (node in entry) {
223 out[node.key] = [:]
224 for (resource in node.value) {
225 if (resource instanceof String) {
226 out[node.key] = node.value
227 } else if (resource.value.result.toString().toBoolean() == false || resource.value.changes || onlyChanges == false) {
228 out[node.key][resource.key] = resource.value
Tomáš Kukrál6eb45f82017-03-08 18:26:16 +0100229
Tomáš Kukrál9a195612017-03-09 09:40:53 +0100230 //if (resource.value.result.toString().toBoolean() == false && resource.key instanceof String && node.key instanceof String) {
231 // common.warningMsg("Resource ${resource.key} failed on node ${node.key}!")
232 //}
Jakub Josef79ecec32017-02-17 14:36:28 +0100233 }
234 }
235 }
236 }
237
238 for (node in out) {
239 if (node.value) {
240 println "Node ${node.key} changes:"
Tomáš Kukrál2a9b7122017-03-04 00:17:18 +0100241 print new groovy.json.JsonBuilder(node.value).toPrettyString().replace('\\n', System.getProperty('line.separator'))
Jakub Josef79ecec32017-02-17 14:36:28 +0100242 } else {
243 println "No changes for node ${node.key}"
244 }
245 }
246}
247
248/**
249 * Print Salt state run results in human-friendly form
250 *
251 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100252 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100253def printSaltCommandResult(result) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100254 def out = [:]
255 for (entry in result['return']) {
256 for (node in entry) {
257 out[node.key] = [:]
258 for (resource in node.value) {
259 out[node.key] = node.value
260 }
261 }
262 }
263
264 for (node in out) {
265 if (node.value) {
266 println "Node ${node.key} changes:"
267 print new groovy.json.JsonBuilder(node.value).toPrettyString()
268 } else {
269 println "No changes for node ${node.key}"
270 }
271 }
272}