blob: 10930a53712d2a3a96099fed88ac4ec9dc795225 [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])
Jakub Josef79ecec32017-02-17 14:36:28 +010099 try {
100 checkResult(out)
101 } finally {
102 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100103 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100104 }
105 }
106 return out
107}
108
109def cmdRun(master, target, cmd) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100110 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', null, [cmd])
Jakub Josef79ecec32017-02-17 14:36:28 +0100111 return out
112}
113
114def syncAll(master, target) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100115 return runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all')
Jakub Josef79ecec32017-02-17 14:36:28 +0100116}
117
118def enforceHighstate(master, target, output = false) {
Filip Pytloun5a7f7fd2017-02-27 18:50:25 +0100119 def out = runSaltCommand(master, 'local', ['expression': target, 'type': 'compound'], 'state.highstate')
Jakub Josef79ecec32017-02-17 14:36:28 +0100120 try {
121 checkResult(out)
122 } finally {
123 if (output == true) {
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100124 printSaltStateResult(out)
Jakub Josef79ecec32017-02-17 14:36:28 +0100125 }
126 }
127 return out
128}
129
130def generateNodeKey(master, target, host, keysize = 4096) {
131 args = [host]
132 kwargs = ['keysize': keysize]
133 return runSaltCommand(master, 'wheel', target, 'key.gen_accept', args, kwargs)
134}
135
136def generateNodeMetadata(master, target, host, classes, parameters) {
137 args = [host, '_generated']
138 kwargs = ['classes': classes, 'parameters': parameters]
139 return runSaltCommand(master, 'local', target, 'reclass.node_create', args, kwargs)
140}
141
142def orchestrateSystem(master, target, orchestrate) {
143 return runSaltCommand(master, 'runner', target, 'state.orchestrate', [orchestrate])
144}
145
146def runSaltProcessStep(master, tgt, fun, arg = [], batch = null) {
147 if (batch) {
148 result = runSaltCommand(master, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg)
149 }
150 else {
151 result = runSaltCommand(master, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg)
152 }
153 echo("${result}")
Jakub Josef79ecec32017-02-17 14:36:28 +0100154}
155
156/**
157 * Check result for errors and throw exception if any found
158 *
159 * @param result Parsed response of Salt API
160 */
161def checkResult(result) {
162 for (entry in result['return']) {
163 if (!entry) {
164 throw new Exception("Salt API returned empty response: ${result}")
165 }
166 for (node in entry) {
167 for (resource in node.value) {
168 if (resource instanceof String || resource.value.result.toString().toBoolean() != true) {
169 throw new Exception("Salt state on node ${node.key} failed: ${node.value}")
170 }
171 }
172 }
173 }
174}
175
176/**
177 * Print Salt state run results in human-friendly form
178 *
179 * @param result Parsed response of Salt API
180 * @param onlyChanges If true (default), print only changed resources
181 * parsing
182 */
183def printSaltStateResult(result, onlyChanges = true) {
184 def out = [:]
185 for (entry in result['return']) {
186 for (node in entry) {
187 out[node.key] = [:]
188 for (resource in node.value) {
189 if (resource instanceof String) {
190 out[node.key] = node.value
191 } else if (resource.value.result.toString().toBoolean() == false || resource.value.changes || onlyChanges == false) {
192 out[node.key][resource.key] = resource.value
193 }
194 }
195 }
196 }
197
198 for (node in out) {
199 if (node.value) {
200 println "Node ${node.key} changes:"
201 print new groovy.json.JsonBuilder(node.value).toPrettyString()
202 } else {
203 println "No changes for node ${node.key}"
204 }
205 }
206}
207
208/**
209 * Print Salt state run results in human-friendly form
210 *
211 * @param result Parsed response of Salt API
Jakub Josef79ecec32017-02-17 14:36:28 +0100212 */
Filip Pytlound2f1bbe2017-02-27 19:03:51 +0100213def printSaltCommandResult(result) {
Jakub Josef79ecec32017-02-17 14:36:28 +0100214 def out = [:]
215 for (entry in result['return']) {
216 for (node in entry) {
217 out[node.key] = [:]
218 for (resource in node.value) {
219 out[node.key] = node.value
220 }
221 }
222 }
223
224 for (node in out) {
225 if (node.value) {
226 println "Node ${node.key} changes:"
227 print new groovy.json.JsonBuilder(node.value).toPrettyString()
228 } else {
229 println "No changes for node ${node.key}"
230 }
231 }
232}