blob: 536188712dd17765ae7b81204aa9f6f71a18c77f [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") {
15 def common = new com.mirantis.mk.Common();
16 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")
51 * @param batch
52 * @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
66 if (batch) {
67 data['batch'] = batch
68 }
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) {
91 def run_states
92 if (state instanceof String) {
93 run_states = state
94 } else {
95 run_states = state.join(',')
96 }
97
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +010098 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.sls', null, [run_states])
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +010099
Jakub Josef79ecec32017-02-17 14:36:28 +0100100 try {
101 checkResult(out)
102 } finally {
103 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100104 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100105 }
106 }
107 return out
108}
109
110def cmdRun(master, target, cmd) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100111 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100112 return out
113}
114
115def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100116 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100117}
118
119def enforceHighstate(master, target, output = false) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100120 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
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 generateNodeKey(master, target, host, keysize = 4096) {
132 args = [host]
133 kwargs = ['keysize': keysize]
134 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', args, kwargs)
135}
136
137def generateNodeMetadata(master, target, host, classes, parameters) {
138 args = [host, '_generated']
139 kwargs = ['classes': classes, 'parameters': parameters]
140 return runSaltCommand(master, 'local', target, 'reclass.node_create', args, kwargs)
141}
142
143def orchestrateSystem(master, target, orchestrate) {
144 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
145}
146
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100147def runSaltProcessStep(master, tgt, fun, arg = [], batch = null, output = true) {
148 def out
149
Jakub Josef79ecec32017-02-17 14:36:28 +0100150 if (batch) {
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100151 out = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
152 } else {
153 out = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
Jakub Josef79ecec32017-02-17 14:36:28 +0100154 }
Tomáš Kukráladb4ecd2017-03-02 10:06:36 +0100155
156 try {
157 checkResult(out)
158 } finally {
159 if (output == true) {
160 printSaltCommandResult(out)
161 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100162 }
Jakub Josef79ecec32017-02-17 14:36:28 +0100163}
164
165/**
166 * Check result for errors and throw exception if any found
167 *
168 * @param result Parsed response of Salt API
169 */
170def checkResult(result) {
171 for (entry in result['return']) {
172 if (!entry) {
173 throw new Exception("Salt API returned empty response: ${result}")
174 }
175 for (node in entry) {
176 for (resource in node.value) {
177 if (resource instanceof String || resource.value.result.toString().toBoolean() != true) {
178 throw new Exception("Salt state on node ${node.key} failed: ${node.value}")
179 }
180 }
181 }
182 }
183}
184
185/**
186 * Print Salt state run results in human-friendly form
187 *
188 * @param result Parsed response of Salt API
189 * @param onlyChanges If true (default), print only changed resources
190 * parsing
191 */
192def printSaltStateResult(result, onlyChanges = true) {
193 def out = [:]
194 for (entry in result['return']) {
195 for (node in entry) {
196 out[node.key] = [:]
197 for (resource in node.value) {
198 if (resource instanceof String) {
199 out[node.key] = node.value
200 } else if (resource.value.result.toString().toBoolean() == false || resource.value.changes || onlyChanges == false) {
201 out[node.key][resource.key] = resource.value
202 }
203 }
204 }
205 }
206
207 for (node in out) {
208 if (node.value) {
209 println "Node ${node.key} changes:"
210 print new groovy.json.JsonBuilder(node.value).toPrettyString()
211 } else {
212 println "No changes for node ${node.key}"
213 }
214 }
215}
216
217/**
218 * Print Salt state run results in human-friendly form
219 *
220 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100221 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100222def printSaltCommandResult(result) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100223 def out = [:]
224 for (entry in result['return']) {
225 for (node in entry) {
226 out[node.key] = [:]
227 for (resource in node.value) {
228 out[node.key] = node.value
229 }
230 }
231 }
232
233 for (node in out) {
234 if (node.value) {
235 println "Node ${node.key} changes:"
236 print new groovy.json.JsonBuilder(node.value).toPrettyString()
237 } else {
238 println "No changes for node ${node.key}"
239 }
240 }
241}