blob: 297acb686aba47fc1ad2560fc8cf413069bf6dce [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
85def pillarGet(master, target, pillar) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +010086 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')])
Jakub Josef79ecec32017-02-17 14:36:28 +010087 return out
88}
89
90def enforceState(master, target, state, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010091 def common = new com.mirantis.mk.Common()
Jakub Josef79ecec32017-02-17 14:36:28 +010092 def run_states
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +010093
Jakub Josef79ecec32017-02-17 14:36:28 +010094 if (state instanceof String) {
95 run_states = state
96 } else {
97 run_states = state.join(',')
98 }
99
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100100 common.infoMsg("Enforcing state ${run_states} on ${target}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100101
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100102 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', null, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100103
Jakub Josef79ecec32017-02-17 14:36:28 +0100104 try {
105 checkResult(out)
106 } finally {
107 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100108 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100109 }
110 }
111 return out
112}
113
114def cmdRun(master, target, cmd) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100115 def common = new com.mirantis.mk.Common()
116
Tomáš Kukráldfd4b492017-03-02 12:08:50 +0100117 common.infoMsg("Running command ${cmd} 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'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100120 return out
121}
122
123def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100124 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100125}
126
127def enforceHighstate(master, target, output = false) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100128 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
Jakub Josef79ecec32017-02-17 14:36:28 +0100129 try {
130 checkResult(out)
131 } finally {
132 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100133 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100134 }
135 }
136 return out
137}
138
139def generateNodeKey(master, target, host, keysize = 4096) {
140 args = [host]
141 kwargs = ['keysize': keysize]
142 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', args, kwargs)
143}
144
145def generateNodeMetadata(master, target, host, classes, parameters) {
146 args = [host, '_generated']
147 kwargs = ['classes': classes, 'parameters': parameters]
148 return runSaltCommand(master, 'local', target, 'reclass.node_create', args, kwargs)
149}
150
151def orchestrateSystem(master, target, orchestrate) {
152 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
153}
154
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100155def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = false) {
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100156 def common = new com.mirantis.mk.Common()
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100157 def out
158
Tomáš Kukrál3281ba12017-03-02 22:21:44 +0100159 arg_string = arg.join(',')
160 common.infoMsg("Running step ${fun} on ${tgt} with args ${arg_string}")
Tomáš Kukrál6c04bd02017-03-01 22:18:52 +0100161
Filip Pytlounf0435c02017-03-02 17:48:54 +0100162 if (batch == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100163 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
164 } else {
165 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100166 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100167
Tomáš Kukrálf5dda642017-03-02 14:22:59 +0100168 if (output == true) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100169 printSaltCommandResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100170 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100171}
172
173/**
174 * Check result for errors and throw exception if any found
175 *
176 * @param result Parsed response of Salt API
177 */
178def checkResult(result) {
179 for (entry in result['return']) {
180 if (!entry) {
181 throw new Exception("Salt API returned empty response: ${result}")
182 }
183 for (node in entry) {
184 for (resource in node.value) {
Tomáš Kukrál76db9e82017-03-02 12:15:46 +0100185 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 +0100186 throw new Exception("Salt state on node ${node.key} failed: ${node.value}")
187 }
188 }
189 }
190 }
191}
192
193/**
194 * Print Salt state run results in human-friendly form
195 *
196 * @param result Parsed response of Salt API
197 * @param onlyChanges If true (default), print only changed resources
198 * parsing
199 */
200def printSaltStateResult(result, onlyChanges = true) {
201 def out = [:]
202 for (entry in result['return']) {
203 for (node in entry) {
204 out[node.key] = [:]
205 for (resource in node.value) {
206 if (resource instanceof String) {
207 out[node.key] = node.value
208 } else if (resource.value.result.toString().toBoolean() == false || resource.value.changes || onlyChanges == false) {
209 out[node.key][resource.key] = resource.value
210 }
211 }
212 }
213 }
214
215 for (node in out) {
216 if (node.value) {
217 println "Node ${node.key} changes:"
218 print new groovy.json.JsonBuilder(node.value).toPrettyString()
219 } else {
220 println "No changes for node ${node.key}"
221 }
222 }
223}
224
225/**
226 * Print Salt state run results in human-friendly form
227 *
228 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100229 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100230def printSaltCommandResult(result) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100231 def out = [:]
232 for (entry in result['return']) {
233 for (node in entry) {
234 out[node.key] = [:]
235 for (resource in node.value) {
236 out[node.key] = node.value
237 }
238 }
239 }
240
241 for (node in out) {
242 if (node.value) {
243 println "Node ${node.key} changes:"
244 print new groovy.json.JsonBuilder(node.value).toPrettyString()
245 } else {
246 println "No changes for node ${node.key}"
247 }
248 }
249}