blob: d17bbc171a27661c7da7cd02910d83edf8d1e058 [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) {
86 if(pillar != null) {
87 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
88 }
89 else {
90 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.data')
91 }
Jakub Josef79ecec32017-02-17 14:36:28 +010092 return out
93}
94
Ales Komarekcec24d42017-03-08 10:25:45 +010095
96def getGrain(master, target, grain = null) {
97 if(grain != null) {
98 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.item', null, [grain])
99 }
100 else {
101 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'grain.items')
102 }
103 return out
104}
105
106
Tomáš Kukrálaa8091c2017-03-08 15:46:52 +0100107def enforceState(master, target, state, output = true) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100108 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100109 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100110
Jakub Josef79ecec32017-02-17 14:36:28 +0100111 if (state instanceof String) {
112 run_states = state
113 } else {
114 run_states = state.join(',')
115 }
116
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100117 common.infoMsg("Enforcing state ${run_states} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100118
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100119 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', null, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100120
Jakub Josef79ecec32017-02-17 14:36:28 +0100121 try {
122 checkResult(out)
123 } finally {
124 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100125 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100126 }
127 }
128 return out
129}
130
131def cmdRun(master, target, cmd) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100132 def common = new com.mirantis.mk.Common()
133
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100134 common.infoMsg("Running command ${cmd} 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'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100137 return out
138}
139
140def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100141 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100142}
143
144def enforceHighstate(master, target, output = false) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100145 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
Jakub Josef79ecec32017-02-17 14:36:28 +0100146 try {
147 checkResult(out)
148 } finally {
149 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100150 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100151 }
152 }
153 return out
154}
155
156def generateNodeKey(master, target, host, keysize = 4096) {
157 args = [host]
158 kwargs = ['keysize': keysize]
159 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', args, kwargs)
160}
161
162def generateNodeMetadata(master, target, host, classes, parameters) {
163 args = [host, '_generated']
164 kwargs = ['classes': classes, 'parameters': parameters]
165 return runSaltCommand(master, 'local', target, 'reclass.node_create', args, kwargs)
166}
167
168def orchestrateSystem(master, target, orchestrate) {
169 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
170}
171
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100172def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100173 def common = new com.mirantis.mk.Common()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100174 def out
175
Tomas Kukrale90bb342017-03-02 21:30:35 +0000176 common.infoMsg("Running step ${fun} on ${tgt}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100177
Filip Pytlounf0435c02017-03-02 17:48:54 +0100178 if (batch == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100179 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
180 } else {
181 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100182 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100183
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100184 if (output == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100185 printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100186 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100187}
188
189/**
190 * Check result for errors and throw exception if any found
191 *
192 * @param result Parsed response of Salt API
193 */
194def checkResult(result) {
195 for (entry in result['return']) {
196 if (!entry) {
197 throw new Exception("Salt API returned empty response: ${result}")
198 }
199 for (node in entry) {
200 for (resource in node.value) {
Tomáš Kukrál76db9e82017-03-02 12:15:46 +0100201 if (resource instanceof String || (resource instanceof Boolean && resource == false) || (resource instanceof HashMap && resource.value.result.toString().toBoolean() != true)) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100202 throw new Exception("Salt state on node ${node.key} failed: ${node.value}")
203 }
204 }
205 }
206 }
207}
208
209/**
210 * Print Salt state run results in human-friendly form
211 *
212 * @param result Parsed response of Salt API
213 * @param onlyChanges If true (default), print only changed resources
214 * parsing
215 */
216def printSaltStateResult(result, onlyChanges = true) {
Tomáš Kukrál6eb45f82017-03-08 18:26:16 +0100217 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +0100218 def out = [:]
219 for (entry in result['return']) {
220 for (node in entry) {
221 out[node.key] = [:]
222 for (resource in node.value) {
223 if (resource instanceof String) {
224 out[node.key] = node.value
225 } else if (resource.value.result.toString().toBoolean() == false || resource.value.changes || onlyChanges == false) {
226 out[node.key][resource.key] = resource.value
Tomáš Kukrál6eb45f82017-03-08 18:26:16 +0100227
Tomáš Kukrál9a195612017-03-09 09:40:53 +0100228 //if (resource.value.result.toString().toBoolean() == false && resource.key instanceof String && node.key instanceof String) {
229 // common.warningMsg("Resource ${resource.key} failed on node ${node.key}!")
230 //}
Jakub Josef79ecec32017-02-17 14:36:28 +0100231 }
232 }
233 }
234 }
235
236 for (node in out) {
237 if (node.value) {
238 println "Node ${node.key} changes:"
Tomáš Kukrál2a9b7122017-03-04 00:17:18 +0100239 print new groovy.json.JsonBuilder(node.value).toPrettyString().replace('\\n', System.getProperty('line.separator'))
Jakub Josef79ecec32017-02-17 14:36:28 +0100240 } else {
241 println "No changes for node ${node.key}"
242 }
243 }
244}
245
246/**
247 * Print Salt state run results in human-friendly form
248 *
249 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100250 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100251def printSaltCommandResult(result) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100252 def out = [:]
253 for (entry in result['return']) {
254 for (node in entry) {
255 out[node.key] = [:]
256 for (resource in node.value) {
257 out[node.key] = node.value
258 }
259 }
260 }
261
262 for (node in out) {
263 if (node.value) {
264 println "Node ${node.key} changes:"
265 print new groovy.json.JsonBuilder(node.value).toPrettyString()
266 } else {
267 println "No changes for node ${node.key}"
268 }
269 }
270}