Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1 | package com.mirantis.mk |
| 2 | |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 3 | import com.cloudbees.groovy.cps.NonCPS |
Jakub Josef | b77c081 | 2017-03-27 14:11:01 +0200 | [diff] [blame] | 4 | import java.util.stream.Collectors |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 5 | /** |
| 6 | * Salt functions |
| 7 | * |
| 8 | */ |
| 9 | |
| 10 | /** |
| 11 | * Salt connection and context parameters |
| 12 | * |
| 13 | * @param url Salt API server URL |
| 14 | * @param credentialsID ID of credentials store entry |
| 15 | */ |
| 16 | def connection(url, credentialsId = "salt") { |
Tomáš Kukrál | 6c04bd0 | 2017-03-01 22:18:52 +0100 | [diff] [blame] | 17 | def common = new com.mirantis.mk.Common() |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 18 | params = [ |
| 19 | "url": url, |
| 20 | "credentialsId": credentialsId, |
| 21 | "authToken": null, |
| 22 | "creds": common.getCredentials(credentialsId) |
| 23 | ] |
| 24 | params["authToken"] = saltLogin(params) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 25 | return params |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Login to Salt API, return auth token |
| 30 | * |
| 31 | * @param master Salt connection object |
| 32 | */ |
| 33 | def saltLogin(master) { |
Tomáš Kukrál | 7bec053 | 2017-02-20 15:39:31 +0100 | [diff] [blame] | 34 | def http = new com.mirantis.mk.Http() |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 35 | data = [ |
| 36 | 'username': master.creds.username, |
| 37 | 'password': master.creds.password.toString(), |
| 38 | 'eauth': 'pam' |
| 39 | ] |
Tomáš Kukrál | 7bec053 | 2017-02-20 15:39:31 +0100 | [diff] [blame] | 40 | authToken = http.restGet(master, '/login', data)['return'][0]['token'] |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 41 | return authToken |
| 42 | } |
| 43 | |
| 44 | /** |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 45 | * Run action using Salt API (using plain HTTP request from Jenkins master) or Pepper (from slave shell) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 46 | * |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 47 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) (determines if command will be sent with Pepper of Salt API ) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 48 | * @param client Client type |
| 49 | * @param target Target specification, eg. for compound matches by Pillar |
| 50 | * data: ['expression': 'I@openssh:server', 'type': 'compound']) |
| 51 | * @param function Function to execute (eg. "state.sls") |
Jakub Josef | 2f25cf2 | 2017-03-28 13:34:57 +0200 | [diff] [blame] | 52 | * @param batch Batch param to salt (integer or string with percents) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 53 | * @param args Additional arguments to function |
| 54 | * @param kwargs Additional key-value arguments to function |
Jiri Broulik | 48544be | 2017-06-14 18:33:54 +0200 | [diff] [blame] | 55 | * @param timeout Additional argument salt api timeout |
Vasyl Saienko | e36ab7c | 2017-07-17 14:35:48 +0300 | [diff] [blame] | 56 | * @param read_timeout http session read timeout |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 57 | */ |
| 58 | @NonCPS |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 59 | def runSaltCommand(saltId, client, target, function, batch = null, args = null, kwargs = null, timeout = -1, read_timeout = -1) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 60 | |
| 61 | data = [ |
| 62 | 'tgt': target.expression, |
| 63 | 'fun': function, |
| 64 | 'client': client, |
| 65 | 'expr_form': target.type, |
| 66 | ] |
Richard Felkl | d9476ac | 2018-07-12 19:01:33 +0200 | [diff] [blame] | 67 | |
| 68 | if(batch != null){ |
| 69 | batch = batch.toString() |
| 70 | if( (batch.isInteger() && batch.toInteger() > 0) || (batch.contains("%"))){ |
| 71 | data['client']= "local_batch" |
| 72 | data['batch'] = batch |
| 73 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 74 | } |
| 75 | |
| 76 | if (args) { |
| 77 | data['arg'] = args |
| 78 | } |
| 79 | |
| 80 | if (kwargs) { |
| 81 | data['kwarg'] = kwargs |
| 82 | } |
| 83 | |
Jiri Broulik | 48544be | 2017-06-14 18:33:54 +0200 | [diff] [blame] | 84 | if (timeout != -1) { |
| 85 | data['timeout'] = timeout |
| 86 | } |
| 87 | |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 88 | // Command will be sent using HttpRequest |
| 89 | if (saltId instanceof HashMap && saltId.containsKey("authToken") ) { |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 90 | |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 91 | def headers = [ |
| 92 | 'X-Auth-Token': "${saltId.authToken}" |
| 93 | ] |
| 94 | |
| 95 | def http = new com.mirantis.mk.Http() |
| 96 | return http.sendHttpPostRequest("${saltId.url}/", data, headers, read_timeout) |
| 97 | } else if (saltId instanceof HashMap) { |
| 98 | throw new Exception("Invalid saltId") |
| 99 | } |
| 100 | |
| 101 | // Command will be sent using Pepper |
| 102 | return runPepperCommand(data, saltId) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 103 | } |
| 104 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 105 | /** |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 106 | * Return pillar for given saltId and target |
| 107 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 108 | * @param target Get pillar target |
| 109 | * @param pillar pillar name (optional) |
| 110 | * @return output of salt command |
| 111 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 112 | def getPillar(saltId, target, pillar = null) { |
Tomáš Kukrál | d258970 | 2017-03-10 16:30:46 +0100 | [diff] [blame] | 113 | if (pillar != null) { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 114 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.get', null, [pillar.replace('.', ':')]) |
Tomáš Kukrál | d258970 | 2017-03-10 16:30:46 +0100 | [diff] [blame] | 115 | } else { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 116 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'pillar.data') |
Ales Komarek | a3c7e50 | 2017-03-13 11:20:44 +0100 | [diff] [blame] | 117 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 118 | } |
| 119 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 120 | /** |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 121 | * Return grain for given saltId and target |
| 122 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 123 | * @param target Get grain target |
| 124 | * @param grain grain name (optional) |
| 125 | * @return output of salt command |
| 126 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 127 | def getGrain(saltId, target, grain = null) { |
Ales Komarek | cec24d4 | 2017-03-08 10:25:45 +0100 | [diff] [blame] | 128 | if(grain != null) { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 129 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.item', null, [grain]) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 130 | } else { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 131 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'grains.items') |
Ales Komarek | cec24d4 | 2017-03-08 10:25:45 +0100 | [diff] [blame] | 132 | } |
Ales Komarek | cec24d4 | 2017-03-08 10:25:45 +0100 | [diff] [blame] | 133 | } |
| 134 | |
Oleksii Grudev | 9e1d97a | 2018-06-29 16:04:30 +0300 | [diff] [blame] | 135 | /** |
| 136 | * Return config items for given saltId and target |
| 137 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 138 | * @param target Get grain target |
| 139 | * @param config grain name (optional) |
| 140 | * @return output of salt command |
| 141 | */ |
| 142 | def getConfig(saltId, target, config) { |
| 143 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'config.get', null, [config.replace('.', ':')], '--out=json') |
| 144 | } |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 145 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 146 | /** |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 147 | * Enforces state on given saltId and target |
| 148 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 149 | * @param target State enforcing target |
| 150 | * @param state Salt state |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 151 | * @param excludedStates states which will be excluded from main state (default empty string) |
| 152 | * @param output print output (optional, default true) |
| 153 | * @param failOnError throw exception on salt state result:false (optional, default true) |
| 154 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 155 | * @param optional Optional flag (if true pipeline will continue even if no minions for target found) |
| 156 | * @param read_timeout http session read timeout (optional, default -1 - disabled) |
| 157 | * @param retries Retry count for salt state. (optional, default -1 - no retries) |
| 158 | * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH |
| 159 | * @param saltArgs additional salt args eq. ["runas=aptly"] |
| 160 | * @return output of salt command |
| 161 | */ |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 162 | def enforceStateWithExclude(Map params) { |
| 163 | //Set defaults |
| 164 | defaults = ["excludedStates": "", "output": true, "failOnError": true, "batch": null, "optional": false, |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 165 | "read_timeout": -1, "retries": -1, "retries_wait": 5, "queue": true, "saltArgs": []] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 166 | params = defaults + params |
| 167 | params.saltArgs << "exclude=${params.excludedStates}" |
| 168 | params.remove('excludedStates') |
| 169 | return enforceState(params) |
| 170 | } |
| 171 | |
| 172 | |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 173 | def enforceStateWithExclude(saltId, target, state, excludedStates = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[], retries_wait=5) { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 174 | // Deprecated, convert state to use Map as input parameter |
| 175 | def common = new com.mirantis.mk.Common() |
Martin Polreich | 4928869 | 2018-12-20 15:41:04 +0100 | [diff] [blame] | 176 | common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter") |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 177 | // Convert to Map |
| 178 | params = ['saltId': saltId, 'target': target, 'state': state, 'excludedStates': excludedStates, 'output': output, |
| 179 | 'failOnError': failOnError, 'batch': batch, 'optional': optional, 'read_timeout': read_timeout, |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 180 | 'retries': retries, 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 181 | // Call new method with Map as parameter |
| 182 | return enforceStateWithExclude(params) |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 183 | } |
| 184 | |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 185 | /** |
| 186 | * Allows to test the given target for reachability and if reachable enforces the state |
| 187 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 188 | * @param target State enforcing target |
| 189 | * @param state Salt state |
| 190 | * @param testTargetMatcher Salt compound matcher to be tested (default is empty string). If empty string, param `target` will be used for tests |
| 191 | * @param output print output (optional, default true) |
| 192 | * @param failOnError throw exception on salt state result:false (optional, default true) |
| 193 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 194 | * @param optional Optional flag (if true pipeline will continue even if no minions for target found) |
| 195 | * @param read_timeout http session read timeout (optional, default -1 - disabled) |
| 196 | * @param retries Retry count for salt state. (optional, default -1 - no retries) |
| 197 | * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH |
| 198 | * @param saltArgs additional salt args eq. ["runas=aptly"] |
| 199 | * @return output of salt command |
| 200 | */ |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 201 | def enforceStateWithTest(Map params) { |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 202 | def common = new com.mirantis.mk.Common() |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 203 | //Set defaults |
| 204 | defaults = ["testTargetMatcher": "", "output": true, "failOnError": true, "batch": null, "optional": false, |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 205 | "read_timeout": -1, "retries": -1, "retries_wait": 5, "queue": true, "saltArgs":[]] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 206 | params = defaults + params |
| 207 | if (!params.testTargetMatcher) { |
| 208 | params.testTargetMatcher = params.target |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 209 | } |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 210 | if (testTarget(params.saltId, params.testTargetMatcher)) { |
| 211 | return enforceState(params) |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 212 | } else { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 213 | if (!params.optional) { |
| 214 | common.infoMsg("No Minions matched the target matcher: ${params.testTargetMatcher}, and 'optional' param was set to false. - This may signify missing pillar definition!!") |
Martin Polreich | 92db3e1 | 2018-09-27 15:29:23 +0200 | [diff] [blame] | 215 | // throw new Exception("No Minions matched the target matcher: ${testTargetMatcher}.") TODO: Change the infoMsg to Error once the methods are changed to Use named params and optional param will be set globally |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 216 | } else { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 217 | common.infoMsg("No Minions matched the target matcher: ${params.testTargetMatcher}, but 'optional' param was set to true - Pipeline continues. ") |
Martin Polreich | 75e4064 | 2018-08-13 16:05:08 +0200 | [diff] [blame] | 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 222 | |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 223 | def enforceStateWithTest(saltId, target, state, testTargetMatcher = "", output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs=[], retries_wait=5) { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 224 | // Deprecated, convert state to use Map as input parameter |
| 225 | def common = new com.mirantis.mk.Common() |
Martin Polreich | 4928869 | 2018-12-20 15:41:04 +0100 | [diff] [blame] | 226 | common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter") |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 227 | // Convert to Map |
| 228 | params = ['saltId': saltId, 'target': target, 'state': state, 'testTargetMatcher': testTargetMatcher, 'output': output, |
| 229 | 'failOnError': failOnError, 'batch': batch, 'optional': optional, 'read_timeout': read_timeout, |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 230 | 'retries': retries, 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 231 | // Call new method with Map as parameter |
| 232 | return enforceStateWithTest(params) |
| 233 | } |
| 234 | |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 235 | /* Enforces state on given saltId and target |
| 236 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 237 | * @param target State enforcing target |
| 238 | * @param state Salt state |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 239 | * @param output print output (optional, default true) |
| 240 | * @param failOnError throw exception on salt state result:false (optional, default true) |
Jakub Josef | 2f25cf2 | 2017-03-28 13:34:57 +0200 | [diff] [blame] | 241 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 242 | * @param optional Optional flag (if true pipeline will continue even if no minions for target found) |
Petr Michalec | de0ff32 | 2017-10-04 09:32:14 +0200 | [diff] [blame] | 243 | * @param read_timeout http session read timeout (optional, default -1 - disabled) |
| 244 | * @param retries Retry count for salt state. (optional, default -1 - no retries) |
| 245 | * @param queue salt queue parameter for state.sls calls (optional, default true) - CANNOT BE USED WITH BATCH |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 246 | * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"] |
Vasyl Saienko | 6a39621 | 2018-06-08 09:20:08 +0300 | [diff] [blame] | 247 | * @param minionRestartWaitTimeout specifies timeout that we should wait after minion restart. |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 248 | * @return output of salt command |
| 249 | */ |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 250 | def enforceState(Map params) { |
Tomáš Kukrál | 6c04bd0 | 2017-03-01 22:18:52 +0100 | [diff] [blame] | 251 | def common = new com.mirantis.mk.Common() |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 252 | //Set defaults |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 253 | defaults = ["output": true, "failOnError": true, "batch": null, "optional": false, "read_timeout": -1, |
| 254 | "retries": -1, "retries_wait": 5, "queue": true, "saltArgs": [], "minionRestartWaitTimeout": 10] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 255 | params = defaults + params |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 256 | // add state to salt args |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 257 | if (params.state instanceof String) { |
| 258 | params.saltArgs << params.state |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 259 | } else { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 260 | params.saltArgs << params.state.join(',') |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 261 | } |
| 262 | |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 263 | common.infoMsg("Running state ${params.state} on ${params.target}") |
Vasyl Saienko | e36ab7c | 2017-07-17 14:35:48 +0300 | [diff] [blame] | 264 | def out |
Petr Michalec | de0ff32 | 2017-10-04 09:32:14 +0200 | [diff] [blame] | 265 | def kwargs = [:] |
| 266 | |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 267 | if (params.queue && params.batch == null) { |
Petr Michalec | de0ff32 | 2017-10-04 09:32:14 +0200 | [diff] [blame] | 268 | kwargs["queue"] = true |
| 269 | } |
Vasyl Saienko | e36ab7c | 2017-07-17 14:35:48 +0300 | [diff] [blame] | 270 | |
Victor Ryzhenkin | 7e4d18f | 2019-01-09 17:46:17 +0400 | [diff] [blame] | 271 | if (params.optional == false || testTarget(params.saltId, params.target)){ |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 272 | if (params.retries > 0){ |
Jakub Josef | 962ba91 | 2018-04-04 17:39:19 +0200 | [diff] [blame] | 273 | def retriesCounter = 0 |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 274 | retry(params.retries){ |
Jakub Josef | 962ba91 | 2018-04-04 17:39:19 +0200 | [diff] [blame] | 275 | retriesCounter++ |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 276 | // we have to reverse order in saltArgs because salt state have to be first |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 277 | out = runSaltCommand(params.saltId, 'local', ['expression': params.target, 'type': 'compound'], 'state.sls', params.batch, params.saltArgs.reverse(), kwargs, -1, params.read_timeout) |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 278 | // failOnError should be passed as true because we need to throw exception for retry block handler |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 279 | checkResult(out, true, params.output, true, retriesCounter < params.retries) //disable ask on error for every interation except last one |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 280 | sleep(params['retries_wait']) |
Vasyl Saienko | e36ab7c | 2017-07-17 14:35:48 +0300 | [diff] [blame] | 281 | } |
Petr Michalec | de0ff32 | 2017-10-04 09:32:14 +0200 | [diff] [blame] | 282 | } else { |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 283 | // we have to reverse order in saltArgs because salt state have to be first |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 284 | out = runSaltCommand(params.saltId, 'local', ['expression': params.target, 'type': 'compound'], 'state.sls', params.batch, params.saltArgs.reverse(), kwargs, -1, params.read_timeout) |
| 285 | checkResult(out, params.failOnError, params.output) |
Vasyl Saienko | e36ab7c | 2017-07-17 14:35:48 +0300 | [diff] [blame] | 286 | } |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 287 | waitForMinion(out, params.minionRestartWaitTimeout) |
Martin Polreich | 1c77afa | 2017-07-18 11:27:02 +0200 | [diff] [blame] | 288 | return out |
Martin Polreich | 1c77afa | 2017-07-18 11:27:02 +0200 | [diff] [blame] | 289 | } else { |
| 290 | common.infoMsg("No Minions matched the target given, but 'optional' param was set to true - Pipeline continues. ") |
| 291 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 292 | } |
| 293 | |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 294 | def enforceState(saltId, target, state, output = true, failOnError = true, batch = null, optional = false, read_timeout=-1, retries=-1, queue=true, saltArgs = [], minionRestartWaitTimeout=10, retries_wait=5) { |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 295 | // Deprecated, convert state to use Map as input parameter |
| 296 | def common = new com.mirantis.mk.Common() |
Martin Polreich | 4928869 | 2018-12-20 15:41:04 +0100 | [diff] [blame] | 297 | common.infoMsg("This method will be deprecated. Convert you method call to use Map as input parameter") |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 298 | // Convert to Map |
Martin Polreich | b1a369f | 2019-03-07 11:21:05 +0100 | [diff] [blame] | 299 | params = ['saltId': saltId, 'target': target, 'state': state, 'output': output, 'failOnError': failOnError, |
| 300 | 'batch': batch, 'optional': optional, 'read_timeout': read_timeout, 'retries': retries, |
| 301 | 'retries_wait': retries_wait, 'queue': queue, 'saltArgs': saltArgs, 'minionRestartWaitTimeout': minionRestartWaitTimeout] |
Martin Polreich | c19e66b | 2018-10-22 12:22:03 +0200 | [diff] [blame] | 302 | // Call new method with Map as parameter |
| 303 | return enforceState(params) |
| 304 | } |
| 305 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 306 | /** |
| 307 | * Run command on salt minion (salt cmd.run wrapper) |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 308 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 309 | * @param target Get pillar target |
| 310 | * @param cmd command |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 311 | * @param checkResponse test command success execution (default true) |
Jakub Josef | 2f25cf2 | 2017-03-28 13:34:57 +0200 | [diff] [blame] | 312 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 313 | * @param output do you want to print output |
chnyda | 205a92b | 2018-01-11 17:07:32 +0100 | [diff] [blame] | 314 | * @param saltArgs additional salt args eq. ["runas=aptly"] |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 315 | * @return output of salt command |
| 316 | */ |
chnyda | 205a92b | 2018-01-11 17:07:32 +0100 | [diff] [blame] | 317 | def cmdRun(saltId, target, cmd, checkResponse = true, batch=null, output = true, saltArgs = []) { |
Tomáš Kukrál | 6c04bd0 | 2017-03-01 22:18:52 +0100 | [diff] [blame] | 318 | def common = new com.mirantis.mk.Common() |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 319 | def originalCmd = cmd |
Tomáš Kukrál | dfd4b49 | 2017-03-02 12:08:50 +0100 | [diff] [blame] | 320 | common.infoMsg("Running command ${cmd} on ${target}") |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 321 | if (checkResponse) { |
| 322 | cmd = cmd + " && echo Salt command execution success" |
| 323 | } |
chnyda | 205a92b | 2018-01-11 17:07:32 +0100 | [diff] [blame] | 324 | |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 325 | // add cmd name to salt args list |
chnyda | 205a92b | 2018-01-11 17:07:32 +0100 | [diff] [blame] | 326 | saltArgs << cmd |
| 327 | |
| 328 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.run', batch, saltArgs.reverse()) |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 329 | if (checkResponse) { |
| 330 | // iterate over all affected nodes and check success return code |
Jiri Broulik | 16e9ce7 | 2017-05-17 13:28:31 +0200 | [diff] [blame] | 331 | if (out["return"]){ |
| 332 | for(int i=0;i<out["return"].size();i++){ |
| 333 | def node = out["return"][i]; |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 334 | for(int j=0;j<node.size();j++){ |
| 335 | def nodeKey = node.keySet()[j] |
Martin Polreich | a2effb8 | 2018-08-01 11:35:11 +0200 | [diff] [blame] | 336 | if (node[nodeKey] instanceof String) { |
| 337 | if (!node[nodeKey].contains("Salt command execution success")) { |
| 338 | throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}") |
| 339 | } |
| 340 | } else if (node[nodeKey] instanceof Boolean) { |
| 341 | if (!node[nodeKey]) { |
| 342 | throw new Exception("Execution of cmd ${originalCmd} failed. Server returns: ${node[nodeKey]}") |
| 343 | } |
| 344 | } else { |
| 345 | throw new Exception("Execution of cmd ${originalCmd} failed. Server returns unexpected data type: ${node[nodeKey]}") |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 346 | } |
| 347 | } |
| 348 | } |
Martin Polreich | a2effb8 | 2018-08-01 11:35:11 +0200 | [diff] [blame] | 349 | } else { |
Jakub Josef | 053df39 | 2017-05-03 15:51:05 +0200 | [diff] [blame] | 350 | throw new Exception("Salt Api response doesn't have return param!") |
| 351 | } |
| 352 | } |
Jiri Broulik | 16e9ce7 | 2017-05-17 13:28:31 +0200 | [diff] [blame] | 353 | if (output == true) { |
| 354 | printSaltCommandResult(out) |
| 355 | } |
| 356 | return out |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 357 | } |
| 358 | |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 359 | /** |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 360 | * Checks if salt minion is in a list of salt master's accepted keys |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 361 | * @usage minionPresent(saltId, 'I@salt:master', 'ntw', true, null, true, 200, 3) |
| 362 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 363 | * @param target Get pillar target |
| 364 | * @param minion_name unique identification of a minion in salt-key command output |
| 365 | * @param waitUntilPresent return after the minion becomes present (default true) |
| 366 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 367 | * @param output print salt command (default true) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 368 | * @param maxRetries finite number of iterations to check status of a command (default 200) |
| 369 | * @param answers how many minions should return (optional, default 1) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 370 | * @return output of salt command |
| 371 | */ |
lmercl | 9418927 | 2018-06-01 11:03:46 +0200 | [diff] [blame] | 372 | def minionPresent(saltId, target, minion_name, waitUntilPresent = true, batch=null, output = true, maxRetries = 180, answers = 1) { |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 373 | minion_name = minion_name.replace("*", "") |
| 374 | def common = new com.mirantis.mk.Common() |
Dzmitry Stremkouski | 8a8d56b | 2018-05-01 12:20:04 +0200 | [diff] [blame] | 375 | common.infoMsg("Looking for minion: " + minion_name) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 376 | def cmd = 'salt-key | grep ' + minion_name |
| 377 | if (waitUntilPresent){ |
| 378 | def count = 0 |
| 379 | while(count < maxRetries) { |
Dzmitry Stremkouski | 5425d23 | 2018-06-07 00:46:00 +0200 | [diff] [blame] | 380 | try { |
| 381 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5) |
| 382 | if (output) { |
| 383 | printSaltCommandResult(out) |
| 384 | } |
| 385 | def valueMap = out["return"][0] |
| 386 | def result = valueMap.get(valueMap.keySet()[0]) |
| 387 | def resultsArray = result.tokenize("\n") |
| 388 | def size = resultsArray.size() |
| 389 | if (size >= answers) { |
| 390 | return out |
| 391 | } |
| 392 | count++ |
| 393 | sleep(time: 1000, unit: 'MILLISECONDS') |
| 394 | common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state") |
| 395 | } catch (Exception er) { |
| 396 | common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment') |
| 397 | } |
| 398 | } |
| 399 | } else { |
| 400 | try { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 401 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 402 | if (output) { |
| 403 | printSaltCommandResult(out) |
| 404 | } |
Dzmitry Stremkouski | 5425d23 | 2018-06-07 00:46:00 +0200 | [diff] [blame] | 405 | return out |
| 406 | } catch (Exception er) { |
| 407 | common.infoMsg('[WARNING]: runSaltCommand command read timeout within 5 seconds. You have very slow or broken environment') |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 408 | } |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 409 | } |
| 410 | // otherwise throw exception |
| 411 | common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.") |
| 412 | throw new Exception("${cmd} signals failure of status check!") |
| 413 | } |
| 414 | |
| 415 | /** |
Dzmitry Stremkouski | 8a8d56b | 2018-05-01 12:20:04 +0200 | [diff] [blame] | 416 | * Checks if salt minions are in a list of salt master's accepted keys by matching compound |
| 417 | * @usage minionsPresent(saltId, 'I@salt:master', 'I@salt:minion', true, null, true, 200, 3) |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 418 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 419 | * @param target Performs tests on this target node |
| 420 | * @param target_minions all targeted minions to test (for ex. I@salt:minion) |
| 421 | * @param waitUntilPresent return after the minion becomes present (default true) |
| 422 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 423 | * @param output print salt command (default true) |
| 424 | * @param maxRetries finite number of iterations to check status of a command (default 200) |
| 425 | * @param answers how many minions should return (optional, default 1) |
| 426 | * @return output of salt command |
| 427 | */ |
| 428 | def minionsPresent(saltId, target = 'I@salt:master', target_minions = '', waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) { |
Dzmitry Stremkouski | 8a8d56b | 2018-05-01 12:20:04 +0200 | [diff] [blame] | 429 | def target_hosts = getMinionsSorted(saltId, target_minions) |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 430 | for (t in target_hosts) { |
Dzmitry Stremkouski | 8a8d56b | 2018-05-01 12:20:04 +0200 | [diff] [blame] | 431 | def tgt = stripDomainName(t) |
| 432 | minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers) |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /** |
| 437 | * Checks if salt minions are in a list of salt master's accepted keys by matching a list |
| 438 | * @usage minionsPresentFromList(saltId, 'I@salt:master', ["cfg01.example.com", "bmk01.example.com"], true, null, true, 200, 3) |
| 439 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 440 | * @param target Performs tests on this target node |
| 441 | * @param target_minions list to test (for ex. ["cfg01.example.com", "bmk01.example.com"]) |
| 442 | * @param waitUntilPresent return after the minion becomes present (default true) |
| 443 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 444 | * @param output print salt command (default true) |
| 445 | * @param maxRetries finite number of iterations to check status of a command (default 200) |
| 446 | * @param answers how many minions should return (optional, default 1) |
| 447 | * @return output of salt command |
| 448 | */ |
| 449 | def minionsPresentFromList(saltId, target = 'I@salt:master', target_minions = [], waitUntilPresent = true, batch=null, output = true, maxRetries = 200, answers = 1) { |
| 450 | def common = new com.mirantis.mk.Common() |
| 451 | for (tgt in target_minions) { |
| 452 | common.infoMsg("Checking if minion " + tgt + " is present") |
| 453 | minionPresent(saltId, target, tgt, waitUntilPresent, batch, output, maxRetries, answers) |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 454 | } |
| 455 | } |
| 456 | |
| 457 | /** |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 458 | * You can call this function when salt-master already contains salt keys of the target_nodes |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 459 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 460 | * @param target Should always be salt-master |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 461 | * @param targetNodes unique identification of a minion or group of salt minions |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 462 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 463 | * @param cmdTimeout timeout for the salt command if minions do not return (default 10) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 464 | * @param maxRetries finite number of iterations to check status of a command (default 200) |
| 465 | * @return output of salt command |
| 466 | */ |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 467 | |
| 468 | def minionsReachable(saltId, target, targetNodes, batch=null, cmdTimeout = 10, maxRetries = 200) { |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 469 | def common = new com.mirantis.mk.Common() |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 470 | def cmd = "salt -t${cmdTimeout} -C '${targetNodes}' test.ping" |
| 471 | common.infoMsg("Checking if all ${targetNodes} minions are reachable") |
| 472 | def retriesCount = 0 |
| 473 | while(retriesCount < maxRetries) { |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 474 | Calendar timeout = Calendar.getInstance(); |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 475 | timeout.add(Calendar.SECOND, cmdTimeout); |
| 476 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, cmdTimeout) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 477 | Calendar current = Calendar.getInstance(); |
| 478 | if (current.getTime().before(timeout.getTime())) { |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 479 | common.infoMsg("Successful response received from all targeted nodes.") |
| 480 | printSaltCommandResult(out) |
| 481 | return out |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 482 | } |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 483 | def outYaml = readYaml text: getReturnValues(out) |
| 484 | def successfulNodes = [] |
| 485 | def failedNodes = [] |
| 486 | for (node in outYaml.keySet()) { |
| 487 | if (outYaml[node] == true || outYaml[node].toString().toLowerCase() == 'true') { |
| 488 | successfulNodes.add(node) |
| 489 | } else { |
| 490 | failedNodes.add(node) |
| 491 | } |
| 492 | } |
| 493 | common.infoMsg("Not all of the targeted minions returned yet. Successful response from ${successfulNodes}. Still waiting for ${failedNodes}.") |
| 494 | retriesCount++ |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 495 | sleep(time: 500, unit: 'MILLISECONDS') |
| 496 | } |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 497 | } |
| 498 | |
Martin Polreich | 0c1e278 | 2019-07-01 17:21:12 +0200 | [diff] [blame] | 499 | |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 500 | /** |
Denis Egorenko | d20a418 | 2019-02-27 19:19:12 +0400 | [diff] [blame] | 501 | * You can call this function when need to check that all minions are available, free and ready for command execution |
| 502 | * @param config LinkedHashMap config parameter, which contains next: |
| 503 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 504 | * @param target unique identification of a minion or group of salt minions |
| 505 | * @param target_reachable unique identification of a minion or group of salt minions to check availability |
| 506 | * @param wait timeout between retries to check target minions (default 5) |
| 507 | * @param retries finite number of iterations to check minions (default 10) |
| 508 | * @param timeout timeout for the salt command if minions do not return (default 5) |
| 509 | * @param availability check that minions also are available before checking readiness (default true) |
| 510 | */ |
| 511 | def checkTargetMinionsReady(LinkedHashMap config) { |
| 512 | def common = new com.mirantis.mk.Common() |
| 513 | def saltId = config.get('saltId') |
| 514 | def target = config.get('target') |
| 515 | def target_reachable = config.get('target_reachable', target) |
| 516 | def wait = config.get('wait', 30) |
| 517 | def retries = config.get('retries', 10) |
| 518 | def timeout = config.get('timeout', 5) |
| 519 | def checkAvailability = config.get('availability', true) |
| 520 | common.retry(retries, wait) { |
| 521 | if (checkAvailability) { |
| 522 | minionsReachable(saltId, 'I@salt:master', target_reachable) |
| 523 | } |
| 524 | def running = runSaltProcessStep(saltId, target, 'saltutil.running', [], null, true, timeout) |
| 525 | for (value in running.get("return")[0].values()) { |
| 526 | if (value != []) { |
| 527 | throw new Exception("Not all salt-minions are ready for execution") |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | /** |
Vasyl Saienko | d8dd2c9 | 2019-06-24 23:39:32 +0300 | [diff] [blame] | 534 | * Restart and wait for salt-minions on target nodes. |
| 535 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 536 | * @param target unique identification of a minion or group of salt minions |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 537 | * @param wait timeout for the salt command if minions do not return (default 10) |
| 538 | * @param maxRetries finite number of iterations to check status of a command (default 15) |
| 539 | * @param async Run salt minion restart and do not wait for response |
Vasyl Saienko | d8dd2c9 | 2019-06-24 23:39:32 +0300 | [diff] [blame] | 540 | * @return output of salt command |
| 541 | */ |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 542 | def restartSaltMinion(saltId, target, wait = 10, maxRetries = 15, async = true) { |
Vasyl Saienko | d8dd2c9 | 2019-06-24 23:39:32 +0300 | [diff] [blame] | 543 | def common = new com.mirantis.mk.Common() |
| 544 | common.infoMsg("Restarting salt-minion on ${target} and waiting for they are reachable.") |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 545 | runSaltProcessStep(saltId, target, 'cmd.shell', ['salt-call service.restart salt-minion'], null, true, 60, null, async) |
| 546 | checkTargetMinionsReady(['saltId': saltId, 'target': target, timeout: wait, retries: maxRetries]) |
Vasyl Saienko | d8dd2c9 | 2019-06-24 23:39:32 +0300 | [diff] [blame] | 547 | common.infoMsg("All ${target} minions are alive...") |
| 548 | } |
| 549 | |
| 550 | /** |
| 551 | * Upgrade package and restart salt minion. |
| 552 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 553 | * @param target unique identification of a minion or group of salt minions |
| 554 | * @param the name of pkg_name to upgrade |
| 555 | * @param wait timeout for the salt command if minions do not return (default 5) |
| 556 | * @param maxRetries finite number of iterations to check status of a command (default 10) |
| 557 | * @return output of salt command |
| 558 | */ |
| 559 | def upgradePackageAndRestartSaltMinion(saltId, target, pkg_name, wait = 5, maxRetries = 10) { |
| 560 | def common = new com.mirantis.mk.Common() |
| 561 | def latest_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.latest_version', [pkg_name, 'show_installed=True'])).split('\n')[0] |
| 562 | def current_version = getReturnValues(runSaltProcessStep(saltId, target, 'pkg.version', [pkg_name])).split('\n')[0] |
| 563 | if (current_version && latest_version != current_version) { |
| 564 | common.infoMsg("Upgrading current ${pkg_name}: ${current_version} to ${latest_version}") |
| 565 | runSaltProcessStep(saltId, target, 'pkg.install', [pkg_name], 'only_upgrade=True') |
| 566 | restartSaltMinion(saltId, target, wait, maxRetries) |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /** |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 571 | * Run command on salt minion (salt cmd.run wrapper) |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 572 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 573 | * @param target Get pillar target |
| 574 | * @param cmd name of a service |
| 575 | * @param correct_state string that command must contain if status is in correct state (optional, default 'running') |
Jiri Broulik | cf1f233 | 2017-07-25 11:30:03 +0200 | [diff] [blame] | 576 | * @param find bool value if it is suppose to find some string in the output or the cmd should return empty string (optional, default true) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 577 | * @param waitUntilOk return after the minion becomes present (optional, default true) |
| 578 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 579 | * @param output print salt command (default true) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 580 | * @param maxRetries finite number of iterations to check status of a command (default 200) |
| 581 | * @param answers how many minions should return (optional, default 0) |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 582 | * @return output of salt command |
| 583 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 584 | def commandStatus(saltId, target, cmd, correct_state='running', find = true, waitUntilOk = true, batch=null, output = true, maxRetries = 200, answers = 0) { |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 585 | def common = new com.mirantis.mk.Common() |
| 586 | common.infoMsg("Checking if status of verification command ${cmd} on ${target} is in correct state") |
| 587 | if (waitUntilOk){ |
| 588 | def count = 0 |
| 589 | while(count < maxRetries) { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 590 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 591 | if (output) { |
| 592 | printSaltCommandResult(out) |
| 593 | } |
Jakub Josef | 115a78f | 2017-07-18 15:04:00 +0200 | [diff] [blame] | 594 | def resultMap = out["return"][0] |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 595 | def success = 0 |
| 596 | if (answers == 0){ |
| 597 | answers = resultMap.size() |
| 598 | } |
| 599 | for (int i=0;i<answers;i++) { |
| 600 | result = resultMap.get(resultMap.keySet()[i]) |
| 601 | // if the goal is to find some string in output of the command |
| 602 | if (find) { |
| 603 | if(result == null || result instanceof Boolean || result.isEmpty()) { result='' } |
| 604 | if (result.toLowerCase().contains(correct_state.toLowerCase())) { |
| 605 | success++ |
| 606 | if (success == answers) { |
| 607 | return out |
| 608 | } |
Jiri Broulik | d0c2757 | 2017-07-24 20:01:10 +0200 | [diff] [blame] | 609 | } |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 610 | // else the goal is to not find any string in output of the command |
| 611 | } else { |
| 612 | if(result instanceof String && result.isEmpty()) { |
| 613 | success++ |
| 614 | if (success == answers) { |
| 615 | return out |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 616 | } |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 617 | } |
| 618 | } |
| 619 | } |
| 620 | count++ |
| 621 | sleep(time: 500, unit: 'MILLISECONDS') |
| 622 | common.infoMsg("Waiting for ${cmd} on ${target} to be in correct state") |
| 623 | } |
| 624 | } else { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 625 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'cmd.shell', batch, [cmd], null, 5) |
Jiri Broulik | 71512bc | 2017-08-04 10:00:18 +0200 | [diff] [blame] | 626 | def resultMap = out["return"][0] |
| 627 | if (output) { |
| 628 | printSaltCommandResult(out) |
| 629 | } |
| 630 | for (int i=0;i<resultMap.size();i++) { |
| 631 | result = resultMap.get(resultMap.keySet()[i]) |
| 632 | // if the goal is to find some string in output of the command |
| 633 | if (find) { |
| 634 | if(result == null || result instanceof Boolean || result.isEmpty()) { result='' } |
| 635 | if (result.toLowerCase().contains(correct_state.toLowerCase())) { |
Jiri Broulik | d0c2757 | 2017-07-24 20:01:10 +0200 | [diff] [blame] | 636 | return out |
| 637 | } |
| 638 | |
| 639 | // else the goal is to not find any string in output of the command |
| 640 | } else { |
| 641 | if(result instanceof String && result.isEmpty()) { |
| 642 | return out |
| 643 | } |
| 644 | } |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 645 | } |
| 646 | } |
| 647 | // otherwise throw exception |
Jiri Broulik | d0c2757 | 2017-07-24 20:01:10 +0200 | [diff] [blame] | 648 | common.errorMsg("Status of command ${cmd} on ${target} failed, please check it.") |
Jiri Broulik | 2c69f3d | 2017-07-18 14:23:58 +0200 | [diff] [blame] | 649 | throw new Exception("${cmd} signals failure of status check!") |
| 650 | } |
| 651 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 652 | /** |
| 653 | * Perform complete salt sync between master and target |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 654 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 655 | * @param target Get pillar target |
| 656 | * @return output of salt command |
| 657 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 658 | def syncAll(saltId, target) { |
| 659 | return runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'saltutil.sync_all') |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 660 | } |
| 661 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 662 | /** |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 663 | * Perform complete salt refresh between master and target |
| 664 | * Method will call saltutil.refresh_pillar, saltutil.refresh_grains and saltutil.sync_all |
| 665 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 666 | * @param target Get pillar target |
| 667 | * @return output of salt command |
| 668 | */ |
| 669 | def fullRefresh(saltId, target){ |
| 670 | runSaltProcessStep(saltId, target, 'saltutil.refresh_pillar', [], null, true) |
| 671 | runSaltProcessStep(saltId, target, 'saltutil.refresh_grains', [], null, true) |
| 672 | runSaltProcessStep(saltId, target, 'saltutil.sync_all', [], null, true) |
| 673 | } |
| 674 | |
| 675 | /** |
| 676 | * Enforce highstate on given targets |
| 677 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 678 | * @param target Highstate enforcing target |
| 679 | * @param excludedStates states which will be excluded from main state (default empty string) |
| 680 | * @param output print output (optional, default true) |
| 681 | * @param failOnError throw exception on salt state result:false (optional, default true) |
| 682 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
| 683 | * @param saltArgs additional salt args eq. ["runas=aptly", exclude="opencontrail.database"] |
| 684 | * @return output of salt command |
| 685 | */ |
| 686 | def enforceHighstateWithExclude(saltId, target, excludedStates = "", output = false, failOnError = true, batch = null, saltArgs = []) { |
| 687 | saltArgs << "exclude=${excludedStates}" |
| 688 | return enforceHighstate(saltId, target, output, failOnError, batch, saltArgs) |
| 689 | } |
| 690 | /** |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 691 | * Enforce highstate on given targets |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 692 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 693 | * @param target Highstate enforcing target |
| 694 | * @param output print output (optional, default true) |
| 695 | * @param failOnError throw exception on salt state result:false (optional, default true) |
Jakub Josef | 2f25cf2 | 2017-03-28 13:34:57 +0200 | [diff] [blame] | 696 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 697 | * @return output of salt command |
| 698 | */ |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 699 | def enforceHighstate(saltId, target, output = false, failOnError = true, batch = null, saltArgs = []) { |
Petr Jediný | 30be703 | 2018-05-29 18:22:46 +0200 | [diff] [blame] | 700 | def out = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'state.highstate', batch, saltArgs) |
Alexander Noskov | 657ccfc | 2017-07-14 11:35:52 +0000 | [diff] [blame] | 701 | def common = new com.mirantis.mk.Common() |
| 702 | |
Marek Celoud | 6336611 | 2017-07-25 17:27:24 +0200 | [diff] [blame] | 703 | common.infoMsg("Running state highstate on ${target}") |
Alexander Noskov | 657ccfc | 2017-07-14 11:35:52 +0000 | [diff] [blame] | 704 | |
Jakub Josef | 374beb7 | 2017-04-27 15:45:09 +0200 | [diff] [blame] | 705 | checkResult(out, failOnError, output) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 706 | return out |
| 707 | } |
| 708 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 709 | /** |
Ales Komarek | 5276ebe | 2017-03-16 08:46:34 +0100 | [diff] [blame] | 710 | * Get running minions IDs according to the target |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 711 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Ales Komarek | 5276ebe | 2017-03-16 08:46:34 +0100 | [diff] [blame] | 712 | * @param target Get minions target |
| 713 | * @return list of active minions fitin |
| 714 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 715 | def getMinions(saltId, target) { |
| 716 | def minionsRaw = runSaltCommand(saltId, 'local', ['expression': target, 'type': 'compound'], 'test.ping') |
Ales Komarek | 5276ebe | 2017-03-16 08:46:34 +0100 | [diff] [blame] | 717 | return new ArrayList<String>(minionsRaw['return'][0].keySet()) |
| 718 | } |
| 719 | |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 720 | /** |
| 721 | * Get sorted running minions IDs according to the target |
| 722 | * @param saltId Salt Connection object or pepperEnv |
| 723 | * @param target Get minions target |
| 724 | * @return list of sorted active minions fitin |
| 725 | */ |
| 726 | def getMinionsSorted(saltId, target) { |
| 727 | return getMinions(saltId, target).sort() |
| 728 | } |
| 729 | |
| 730 | /** |
| 731 | * Get first out of running minions IDs according to the target |
| 732 | * @param saltId Salt Connection object or pepperEnv |
| 733 | * @param target Get minions target |
| 734 | * @return first of active minions fitin |
| 735 | */ |
| 736 | def getFirstMinion(saltId, target) { |
| 737 | def minionsSorted = getMinionsSorted(saltId, target) |
Dmitry Ukov | d72cd2a | 2018-09-04 17:31:46 +0400 | [diff] [blame] | 738 | return minionsSorted[0] |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 739 | } |
| 740 | |
| 741 | /** |
| 742 | * Get running salt minions IDs without it's domain name part and its numbering identifications |
| 743 | * @param saltId Salt Connection object or pepperEnv |
| 744 | * @param target Get minions target |
| 745 | * @return list of active minions fitin without it's domain name part name numbering |
| 746 | */ |
| 747 | def getMinionsGeneralName(saltId, target) { |
| 748 | def minionsSorted = getMinionsSorted(saltId, target) |
| 749 | return stripDomainName(minionsSorted[0]).replaceAll('\\d+$', "") |
| 750 | } |
| 751 | |
| 752 | /** |
| 753 | * Get domain name of the env |
| 754 | * @param saltId Salt Connection object or pepperEnv |
| 755 | * @return domain name |
| 756 | */ |
| 757 | def getDomainName(saltId) { |
| 758 | return getReturnValues(getPillar(saltId, 'I@salt:master', '_param:cluster_domain')) |
| 759 | } |
| 760 | |
| 761 | /** |
| 762 | * Remove domain name from Salt minion ID |
| 763 | * @param name String of Salt minion ID |
| 764 | * @return Salt minion ID without its domain name |
| 765 | */ |
| 766 | def stripDomainName(name) { |
| 767 | return name.split("\\.")[0] |
| 768 | } |
| 769 | |
| 770 | /** |
| 771 | * Gets return values of a salt command |
| 772 | * @param output String of Salt minion ID |
| 773 | * @return Return values of a salt command |
| 774 | */ |
| 775 | def getReturnValues(output) { |
| 776 | if(output.containsKey("return") && !output.get("return").isEmpty()) { |
| 777 | return output['return'][0].values()[0] |
| 778 | } |
| 779 | def common = new com.mirantis.mk.Common() |
| 780 | common.errorMsg('output does not contain return key') |
| 781 | return '' |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Get minion ID of one of KVM nodes |
| 786 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 787 | * @return Salt minion ID of one of KVM nodes in env |
| 788 | */ |
| 789 | def getKvmMinionId(saltId) { |
| 790 | return getReturnValues(getGrain(saltId, 'I@salt:control', 'id')).values()[0] |
| 791 | } |
| 792 | |
| 793 | /** |
| 794 | * Get Salt minion ID of KVM node hosting 'name' VM |
| 795 | * @param saltId Salt Connection object or pepperEnv |
| 796 | * @param name Name of the VM (for ex. ctl01) |
| 797 | * @return Salt minion ID of KVM node hosting 'name' VM |
| 798 | */ |
Jiri Broulik | d2a5055 | 2018-04-25 17:17:59 +0200 | [diff] [blame] | 799 | def getNodeProvider(saltId, nodeName) { |
| 800 | def salt = new com.mirantis.mk.Salt() |
| 801 | def common = new com.mirantis.mk.Common() |
| 802 | def kvms = salt.getMinions(saltId, 'I@salt:control') |
| 803 | for (kvm in kvms) { |
| 804 | try { |
| 805 | vms = salt.getReturnValues(salt.runSaltProcessStep(saltId, kvm, 'virt.list_domains', [], null, true)) |
| 806 | if (vms.toString().contains(nodeName)) { |
| 807 | return kvm |
| 808 | } |
| 809 | } catch (Exception er) { |
| 810 | common.infoMsg("${nodeName} not present on ${kvm}") |
| 811 | } |
| 812 | } |
Jiri Broulik | f8f9694 | 2018-02-15 10:03:42 +0100 | [diff] [blame] | 813 | } |
| 814 | |
Ales Komarek | 5276ebe | 2017-03-16 08:46:34 +0100 | [diff] [blame] | 815 | /** |
Tomáš Kukrál | b12ff9f | 2017-07-12 12:32:34 +0200 | [diff] [blame] | 816 | * Test if there are any minions to target |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 817 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Tomáš Kukrál | b12ff9f | 2017-07-12 12:32:34 +0200 | [diff] [blame] | 818 | * @param target Target to test |
vrovachev | 1c4770b | 2017-07-05 13:25:21 +0400 | [diff] [blame] | 819 | * @return bool indicating if target was succesful |
Tomáš Kukrál | b12ff9f | 2017-07-12 12:32:34 +0200 | [diff] [blame] | 820 | */ |
| 821 | |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 822 | def testTarget(saltId, target) { |
| 823 | return getMinions(saltId, target).size() > 0 |
Tomáš Kukrál | b12ff9f | 2017-07-12 12:32:34 +0200 | [diff] [blame] | 824 | } |
| 825 | |
| 826 | /** |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 827 | * Generates node key using key.gen_accept call |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 828 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 829 | * @param target Key generating target |
| 830 | * @param host Key generating host |
| 831 | * @param keysize generated key size (optional, default 4096) |
| 832 | * @return output of salt command |
| 833 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 834 | def generateNodeKey(saltId, target, host, keysize = 4096) { |
| 835 | return runSaltCommand(saltId, 'wheel', target, 'key.gen_accept', [host], ['keysize': keysize]) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 836 | } |
| 837 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 838 | /** |
Jakub Josef | 2f25cf2 | 2017-03-28 13:34:57 +0200 | [diff] [blame] | 839 | * Generates node reclass metadata |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 840 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 841 | * @param target Metadata generating target |
| 842 | * @param host Metadata generating host |
| 843 | * @param classes Reclass classes |
| 844 | * @param parameters Reclass parameters |
| 845 | * @return output of salt command |
| 846 | */ |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 847 | def generateNodeMetadata(saltId, target, host, classes, parameters) { |
| 848 | return runSaltCommand(saltId, 'local', target, 'reclass.node_create', [host, '_generated'], ['classes': classes, 'parameters': parameters]) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 849 | } |
| 850 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 851 | /** |
| 852 | * Run salt orchestrate on given targets |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 853 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 854 | * @param target Orchestration target |
| 855 | * @param orchestrate Salt orchestrate params |
Dzmitry Stremkouski | dd020d9 | 2018-07-22 12:01:07 +0200 | [diff] [blame] | 856 | * @param kwargs Salt orchestrate params |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 857 | * @return output of salt command |
| 858 | */ |
Dzmitry Stremkouski | dd020d9 | 2018-07-22 12:01:07 +0200 | [diff] [blame] | 859 | def orchestrateSystem(saltId, target, orchestrate=[], kwargs = null) { |
Oleksii Grudev | 9e1d97a | 2018-06-29 16:04:30 +0300 | [diff] [blame] | 860 | //Since the runSaltCommand uses "arg" (singular) for "runner" client this won`t work correctly on old salt 2016 |
| 861 | //cause this version of salt used "args" (plural) for "runner" client, see following link for reference: |
| 862 | //https://github.com/saltstack/salt/pull/32938 |
Oleksii Grudev | 0c09838 | 2018-08-08 16:16:38 +0300 | [diff] [blame] | 863 | def common = new com.mirantis.mk.Common() |
| 864 | def result = runSaltCommand(saltId, 'runner', target, 'state.orchestrate', true, orchestrate, kwargs, 7200, 7200) |
| 865 | if(result != null){ |
| 866 | if(result['return']){ |
| 867 | def retcode = result['return'][0].get('retcode') |
| 868 | if (retcode != 0) { |
| 869 | throw new Exception("Orchestration state failed while running: "+orchestrate) |
| 870 | }else{ |
| 871 | common.infoMsg("Orchestrate state "+orchestrate+" succeeded") |
| 872 | } |
| 873 | }else{ |
| 874 | common.errorMsg("Salt result has no return attribute! Result: ${result}") |
| 875 | } |
| 876 | }else{ |
| 877 | common.errorMsg("Cannot check salt result, given result is null") |
| 878 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 879 | } |
| 880 | |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 881 | /** |
Dzmitry Stremkouski | b544070 | 2018-07-22 13:00:05 +0200 | [diff] [blame] | 882 | * Run salt pre or post orchestrate tasks |
| 883 | * |
| 884 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 885 | * @param pillar_tree Reclass pillar that has orchestrate pillar for desired stage |
| 886 | * @param extra_tgt Extra targets for compound |
| 887 | * |
| 888 | * @return output of salt command |
| 889 | */ |
| 890 | def orchestratePrePost(saltId, pillar_tree, extra_tgt = '') { |
| 891 | |
| 892 | def common = new com.mirantis.mk.Common() |
| 893 | def salt = new com.mirantis.mk.Salt() |
| 894 | def compound = 'I@' + pillar_tree + " " + extra_tgt |
| 895 | |
| 896 | common.infoMsg("Refreshing pillars") |
| 897 | runSaltProcessStep(saltId, '*', 'saltutil.refresh_pillar', [], null, true) |
| 898 | |
| 899 | common.infoMsg("Looking for orchestrate pillars") |
| 900 | if (salt.testTarget(saltId, compound)) { |
| 901 | for ( node in salt.getMinionsSorted(saltId, compound) ) { |
| 902 | def pillar = salt.getPillar(saltId, node, pillar_tree) |
| 903 | if ( !pillar['return'].isEmpty() ) { |
| 904 | for ( orch_id in pillar['return'][0].values() ) { |
| 905 | def orchestrator = orch_id.values()['orchestrator'] |
| 906 | def orch_enabled = orch_id.values()['enabled'] |
| 907 | if ( orch_enabled ) { |
| 908 | common.infoMsg("Orchestrating: ${orchestrator}") |
| 909 | salt.printSaltCommandResult(salt.orchestrateSystem(saltId, ['expression': node], [orchestrator])) |
| 910 | } |
| 911 | } |
| 912 | } |
| 913 | } |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | /** |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 918 | * Run salt process step |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 919 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 920 | * @param tgt Salt process step target |
| 921 | * @param fun Salt process step function |
| 922 | * @param arg process step arguments (optional, default []) |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 923 | * @param batch salt batch parameter integer or string with percents (optional, default null - disable batch). Can't be used with async |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 924 | * @param output print output (optional, default true) |
Jiri Broulik | 48544be | 2017-06-14 18:33:54 +0200 | [diff] [blame] | 925 | * @param timeout Additional argument salt api timeout |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 926 | * @param async Run the salt command but don't wait for a reply. Can't be used with batch |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 927 | * @return output of salt command |
| 928 | */ |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 929 | def runSaltProcessStep(saltId, tgt, fun, arg = [], batch = null, output = true, timeout = -1, kwargs = null, async = false) { |
Tomáš Kukrál | 6c04bd0 | 2017-03-01 22:18:52 +0100 | [diff] [blame] | 930 | def common = new com.mirantis.mk.Common() |
Jiri Broulik | 48544be | 2017-06-14 18:33:54 +0200 | [diff] [blame] | 931 | def salt = new com.mirantis.mk.Salt() |
Tomáš Kukrál | adb4ecd | 2017-03-02 10:06:36 +0100 | [diff] [blame] | 932 | def out |
| 933 | |
Marek Celoud | 6336611 | 2017-07-25 17:27:24 +0200 | [diff] [blame] | 934 | common.infoMsg("Running step ${fun} ${arg} on ${tgt}") |
Tomáš Kukrál | 6c04bd0 | 2017-03-01 22:18:52 +0100 | [diff] [blame] | 935 | |
Filip Pytloun | f0435c0 | 2017-03-02 17:48:54 +0100 | [diff] [blame] | 936 | if (batch == true) { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 937 | out = runSaltCommand(saltId, 'local_batch', ['expression': tgt, 'type': 'compound'], fun, String.valueOf(batch), arg, kwargs, timeout) |
Ivan Berezovskiy | 3870245 | 2019-08-01 15:52:44 +0400 | [diff] [blame] | 938 | } else if (async == true) { |
| 939 | out = runSaltCommand(saltId, 'local_async', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout) |
Tomáš Kukrál | adb4ecd | 2017-03-02 10:06:36 +0100 | [diff] [blame] | 940 | } else { |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 941 | out = runSaltCommand(saltId, 'local', ['expression': tgt, 'type': 'compound'], fun, batch, arg, kwargs, timeout) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 942 | } |
Tomáš Kukrál | adb4ecd | 2017-03-02 10:06:36 +0100 | [diff] [blame] | 943 | |
Tomáš Kukrál | f5dda64 | 2017-03-02 14:22:59 +0100 | [diff] [blame] | 944 | if (output == true) { |
Jiri Broulik | 48544be | 2017-06-14 18:33:54 +0200 | [diff] [blame] | 945 | salt.printSaltCommandResult(out) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 946 | } |
Jiri Broulik | ae19c26 | 2017-05-16 19:06:52 +0200 | [diff] [blame] | 947 | return out |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 948 | } |
| 949 | |
| 950 | /** |
| 951 | * Check result for errors and throw exception if any found |
| 952 | * |
| 953 | * @param result Parsed response of Salt API |
Jakub Josef | 8021c00 | 2017-03-27 15:41:28 +0200 | [diff] [blame] | 954 | * @param failOnError Do you want to throw exception if salt-call fails (optional, default true) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 955 | * @param printResults Do you want to print salt results (optional, default true) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 956 | * @param printOnlyChanges If true (default), print only changed resources |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 957 | * @param disableAskOnError Flag for disabling ASK_ON_ERROR feature (optional, default false) |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 958 | */ |
Jakub Josef | 432e9d9 | 2018-02-06 18:28:37 +0100 | [diff] [blame] | 959 | def checkResult(result, failOnError = true, printResults = true, printOnlyChanges = true, disableAskOnError = false) { |
Jakub Josef | 5ade54c | 2017-03-10 16:14:01 +0100 | [diff] [blame] | 960 | def common = new com.mirantis.mk.Common() |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 961 | if(result != null){ |
| 962 | if(result['return']){ |
| 963 | for (int i=0;i<result['return'].size();i++) { |
| 964 | def entry = result['return'][i] |
| 965 | if (!entry) { |
| 966 | if (failOnError) { |
| 967 | throw new Exception("Salt API returned empty response: ${result}") |
| 968 | } else { |
| 969 | common.errorMsg("Salt API returned empty response: ${result}") |
Jakub Josef | ece32af | 2017-03-14 19:20:08 +0100 | [diff] [blame] | 970 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 971 | } |
| 972 | for (int j=0;j<entry.size();j++) { |
| 973 | def nodeKey = entry.keySet()[j] |
| 974 | def node=entry[nodeKey] |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 975 | def outputResources = [] |
Jakub Josef | 4714594 | 2018-04-04 17:30:38 +0200 | [diff] [blame] | 976 | def errorResources = [] |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 977 | common.infoMsg("Node ${nodeKey} changes:") |
| 978 | if(node instanceof Map || node instanceof List){ |
| 979 | for (int k=0;k<node.size();k++) { |
| 980 | def resource; |
| 981 | def resKey; |
| 982 | if(node instanceof Map){ |
| 983 | resKey = node.keySet()[k] |
Victor Ryzhenkin | 4a45d73 | 2019-01-09 15:28:21 +0400 | [diff] [blame] | 984 | if (resKey == "retcode") { |
Richard Felkl | d9476ac | 2018-07-12 19:01:33 +0200 | [diff] [blame] | 985 | continue |
Victor Ryzhenkin | 4a45d73 | 2019-01-09 15:28:21 +0400 | [diff] [blame] | 986 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 987 | }else if(node instanceof List){ |
| 988 | resKey = k |
| 989 | } |
| 990 | resource = node[resKey] |
Jakub Josef | c4c4020 | 2017-04-28 12:04:24 +0200 | [diff] [blame] | 991 | // print |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 992 | if(printResults){ |
| 993 | if(resource instanceof Map && resource.keySet().contains("result")){ |
| 994 | //clean unnesaccary fields |
| 995 | if(resource.keySet().contains("__run_num__")){ |
| 996 | resource.remove("__run_num__") |
| 997 | } |
| 998 | if(resource.keySet().contains("__id__")){ |
| 999 | resource.remove("__id__") |
| 1000 | } |
| 1001 | if(resource.keySet().contains("pchanges")){ |
| 1002 | resource.remove("pchanges") |
| 1003 | } |
| 1004 | if(!resource["result"] || (resource["result"] instanceof String && resource["result"] != "true")){ |
| 1005 | if(resource["result"] != null){ |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 1006 | outputResources.add(String.format("Resource: %s\n\u001B[31m%s\u001B[0m", resKey, common.prettify(resource))) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1007 | }else{ |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 1008 | outputResources.add(String.format("Resource: %s\n\u001B[33m%s\u001B[0m", resKey, common.prettify(resource))) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1009 | } |
| 1010 | }else{ |
| 1011 | if(!printOnlyChanges || resource.changes.size() > 0){ |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 1012 | outputResources.add(String.format("Resource: %s\n\u001B[32m%s\u001B[0m", resKey, common.prettify(resource))) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1013 | } |
| 1014 | } |
| 1015 | }else{ |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 1016 | outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", resKey, common.prettify(resource))) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1017 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1018 | } |
Jakub Josef | c4c4020 | 2017-04-28 12:04:24 +0200 | [diff] [blame] | 1019 | common.debugMsg("checkResult: checking resource: ${resource}") |
| 1020 | if(resource instanceof String || (resource["result"] != null && !resource["result"]) || (resource["result"] instanceof String && resource["result"] == "false")){ |
Jakub Josef | 4714594 | 2018-04-04 17:30:38 +0200 | [diff] [blame] | 1021 | errorResources.add(resource) |
Jakub Josef | c4c4020 | 2017-04-28 12:04:24 +0200 | [diff] [blame] | 1022 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1023 | } |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1024 | }else if(node!=null && node!=""){ |
Jakub Josef | 62f6c84 | 2017-08-04 16:36:35 +0200 | [diff] [blame] | 1025 | outputResources.add(String.format("Resource: %s\n\u001B[36m%s\u001B[0m", nodeKey, common.prettify(node))) |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1026 | } |
| 1027 | if(printResults && !outputResources.isEmpty()){ |
Jakub Josef | 4714594 | 2018-04-04 17:30:38 +0200 | [diff] [blame] | 1028 | println outputResources.stream().collect(Collectors.joining("\n")) |
| 1029 | } |
| 1030 | if(!errorResources.isEmpty()){ |
| 1031 | for(resource in errorResources){ |
| 1032 | def prettyResource = common.prettify(resource) |
| 1033 | if (!disableAskOnError && env["ASK_ON_ERROR"] && env["ASK_ON_ERROR"] == "true") { |
| 1034 | timeout(time:1, unit:'HOURS') { |
| 1035 | input message: "False result on ${nodeKey} found, resource ${prettyResource}. \nDo you want to continue?" |
| 1036 | } |
| 1037 | } else { |
| 1038 | def errorMsg = "Salt state on node ${nodeKey} failed. Resource: ${prettyResource}" |
| 1039 | if (failOnError) { |
| 1040 | throw new Exception(errorMsg) |
| 1041 | } else { |
| 1042 | common.errorMsg(errorMsg) |
| 1043 | } |
| 1044 | } |
| 1045 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1046 | } |
| 1047 | } |
Jakub Josef | 52f69f7 | 2017-03-14 15:18:08 +0100 | [diff] [blame] | 1048 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1049 | }else{ |
| 1050 | common.errorMsg("Salt result hasn't return attribute! Result: ${result}") |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1051 | } |
Jakub Josef | 52f69f7 | 2017-03-14 15:18:08 +0100 | [diff] [blame] | 1052 | }else{ |
Jakub Josef | a87941c | 2017-04-20 17:14:58 +0200 | [diff] [blame] | 1053 | common.errorMsg("Cannot check salt result, given result is null") |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | /** |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1058 | * Parse salt API output to check minion restart and wait some time to be sure minion is up. |
| 1059 | * See https://mirantis.jira.com/browse/PROD-16258 for more details |
| 1060 | * TODO: change sleep to more tricky procedure. |
| 1061 | * |
| 1062 | * @param result Parsed response of Salt API |
| 1063 | */ |
Vasyl Saienko | 6a39621 | 2018-06-08 09:20:08 +0300 | [diff] [blame] | 1064 | def waitForMinion(result, minionRestartWaitTimeout=10) { |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1065 | def common = new com.mirantis.mk.Common() |
Oleg Iurchenko | 3eedc78 | 2017-12-12 11:49:29 +0200 | [diff] [blame] | 1066 | //In order to prevent multiple sleeps use bool variable to catch restart for any minion. |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1067 | def isMinionRestarted = false |
Oleg Iurchenko | 3eedc78 | 2017-12-12 11:49:29 +0200 | [diff] [blame] | 1068 | if(result != null){ |
| 1069 | if(result['return']){ |
| 1070 | for (int i=0;i<result['return'].size();i++) { |
| 1071 | def entry = result['return'][i] |
| 1072 | // exit in case of empty response. |
| 1073 | if (!entry) { |
| 1074 | return |
| 1075 | } |
| 1076 | // Loop for nodes |
| 1077 | for (int j=0;j<entry.size();j++) { |
| 1078 | def nodeKey = entry.keySet()[j] |
| 1079 | def node=entry[nodeKey] |
| 1080 | if(node instanceof Map || node instanceof List){ |
| 1081 | // Loop for node resources |
| 1082 | for (int k=0;k<node.size();k++) { |
| 1083 | def resource; |
| 1084 | def resKey; |
| 1085 | if(node instanceof Map){ |
| 1086 | resKey = node.keySet()[k] |
| 1087 | }else if(node instanceof List){ |
| 1088 | resKey = k |
| 1089 | } |
| 1090 | resource = node[resKey] |
Jakub Josef | fb9996d | 2018-04-10 14:05:31 +0200 | [diff] [blame] | 1091 | // try to find if salt_minion service was restarted |
| 1092 | if(resKey instanceof String && resKey.contains("salt_minion_service_restart") && resource instanceof Map && resource.keySet().contains("result")){ |
Oleg Iurchenko | 3eedc78 | 2017-12-12 11:49:29 +0200 | [diff] [blame] | 1093 | if((resource["result"] instanceof Boolean && resource["result"]) || (resource["result"] instanceof String && resource["result"] == "true")){ |
| 1094 | if(resource.changes.size() > 0){ |
| 1095 | isMinionRestarted=true |
| 1096 | } |
| 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | } |
| 1101 | } |
| 1102 | } |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1103 | } |
| 1104 | } |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1105 | if (isMinionRestarted){ |
Vasyl Saienko | 6a39621 | 2018-06-08 09:20:08 +0300 | [diff] [blame] | 1106 | common.infoMsg("Salt minion service restart detected. Sleep ${minionRestartWaitTimeout} seconds to wait minion restart") |
| 1107 | sleep(minionRestartWaitTimeout) |
Oleg Iurchenko | 7eb2150 | 2017-11-28 18:53:43 +0200 | [diff] [blame] | 1108 | } |
| 1109 | } |
| 1110 | |
| 1111 | /** |
Jakub Josef | 7852fe1 | 2017-03-15 16:02:41 +0100 | [diff] [blame] | 1112 | * Print salt command run results in human-friendly form |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1113 | * |
| 1114 | * @param result Parsed response of Salt API |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1115 | */ |
Filip Pytloun | d2f1bbe | 2017-02-27 19:03:51 +0100 | [diff] [blame] | 1116 | def printSaltCommandResult(result) { |
Jakub Josef | 871bf15 | 2017-03-14 20:13:41 +0100 | [diff] [blame] | 1117 | def common = new com.mirantis.mk.Common() |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1118 | if(result != null){ |
| 1119 | if(result['return']){ |
| 1120 | for (int i=0; i<result['return'].size(); i++) { |
| 1121 | def entry = result['return'][i] |
| 1122 | for (int j=0; j<entry.size(); j++) { |
| 1123 | common.debugMsg("printSaltCommandResult: printing salt command entry: ${entry}") |
| 1124 | def nodeKey = entry.keySet()[j] |
| 1125 | def node=entry[nodeKey] |
Jakub Josef | bceaa32 | 2017-06-13 18:28:27 +0200 | [diff] [blame] | 1126 | common.infoMsg(String.format("Node %s changes:\n%s",nodeKey, common.prettify(node))) |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1127 | } |
Jakub Josef | 8a715bf | 2017-03-14 21:39:01 +0100 | [diff] [blame] | 1128 | } |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1129 | }else{ |
| 1130 | common.errorMsg("Salt result hasn't return attribute! Result: ${result}") |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1131 | } |
Jakub Josef | 8a715bf | 2017-03-14 21:39:01 +0100 | [diff] [blame] | 1132 | }else{ |
Jakub Josef | d9afd0e | 2017-03-15 19:19:23 +0100 | [diff] [blame] | 1133 | common.errorMsg("Cannot print salt command result, given result is null") |
Jakub Josef | 52f69f7 | 2017-03-14 15:18:08 +0100 | [diff] [blame] | 1134 | } |
Jakub Josef | 79ecec3 | 2017-02-17 14:36:28 +0100 | [diff] [blame] | 1135 | } |
Tomáš Kukrál | b12eedd | 2017-04-21 10:45:13 +0200 | [diff] [blame] | 1136 | |
| 1137 | |
| 1138 | /** |
| 1139 | * Return content of file target |
| 1140 | * |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 1141 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Tomáš Kukrál | b12eedd | 2017-04-21 10:45:13 +0200 | [diff] [blame] | 1142 | * @param target Compound target (should target only one host) |
| 1143 | * @param file File path to read (/etc/hosts for example) |
| 1144 | */ |
| 1145 | |
Pavlo Shchelokovskyy | 9710007 | 2018-10-04 11:53:44 +0300 | [diff] [blame] | 1146 | def getFileContent(saltId, target, file, checkResponse = true, batch=null, output = true, saltArgs = []) { |
| 1147 | result = cmdRun(saltId, target, "cat ${file}", checkResponse, batch, output, saltArgs) |
Tomáš Kukrál | f1a692a | 2017-08-11 13:29:28 +0200 | [diff] [blame] | 1148 | return result['return'][0].values()[0].replaceAll('Salt command execution success','') |
Tomáš Kukrál | b12eedd | 2017-04-21 10:45:13 +0200 | [diff] [blame] | 1149 | } |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1150 | |
| 1151 | /** |
| 1152 | * Set override parameters in Salt cluster metadata |
| 1153 | * |
chnyda | a0dbb25 | 2017-10-05 10:46:09 +0200 | [diff] [blame] | 1154 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1155 | * @param salt_overrides YAML formatted string containing key: value, one per line |
Matthew Mosesohn | e564684 | 2017-07-19 16:54:57 +0300 | [diff] [blame] | 1156 | * @param reclass_dir Directory where Reclass git repo is located |
Dzmitry Stremkouski | b544070 | 2018-07-22 13:00:05 +0200 | [diff] [blame] | 1157 | * @param extra_tgt Extra targets for compound |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1158 | */ |
| 1159 | |
Oleh Hryhorov | 5f96e09 | 2018-06-22 18:37:08 +0300 | [diff] [blame] | 1160 | def setSaltOverrides(saltId, salt_overrides, reclass_dir="/srv/salt/reclass", extra_tgt = '') { |
Tomáš Kukrál | f178f05 | 2017-07-11 11:31:00 +0200 | [diff] [blame] | 1161 | def common = new com.mirantis.mk.Common() |
Mykyta Karpin | 1c165e2 | 2017-08-22 18:27:01 +0300 | [diff] [blame] | 1162 | def salt_overrides_map = readYaml text: salt_overrides |
Tomáš Kukrál | 243cf84 | 2017-07-11 13:11:56 +0200 | [diff] [blame] | 1163 | for (entry in common.entries(salt_overrides_map)) { |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1164 | def key = entry[0] |
| 1165 | def value = entry[1] |
| 1166 | |
| 1167 | common.debugMsg("Set salt override ${key}=${value}") |
Victor Ryzhenkin | b742f4b | 2019-01-10 15:12:55 +0400 | [diff] [blame] | 1168 | runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'reclass.cluster_meta_set', ["name=${key}", "value=${value}"], false) |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1169 | } |
Oleh Hryhorov | 5f96e09 | 2018-06-22 18:37:08 +0300 | [diff] [blame] | 1170 | runSaltProcessStep(saltId, "I@salt:master ${extra_tgt}", 'cmd.run', ["git -C ${reclass_dir} update-index --skip-worktree classes/cluster/overrides.yml"]) |
Matthew Mosesohn | 9e88085 | 2017-07-04 21:17:53 +0300 | [diff] [blame] | 1171 | } |
Oleg Grigorov | bec4558 | 2017-09-12 20:29:24 +0300 | [diff] [blame] | 1172 | |
| 1173 | /** |
| 1174 | * Execute salt commands via salt-api with |
| 1175 | * CLI client salt-pepper |
| 1176 | * |
| 1177 | * @param data Salt command map |
| 1178 | * @param venv Path to virtualenv with |
| 1179 | */ |
| 1180 | |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1181 | def runPepperCommand(data, venv) { |
Jakub Josef | 03d4d5a | 2017-12-20 16:35:09 +0100 | [diff] [blame] | 1182 | def common = new com.mirantis.mk.Common() |
Oleg Grigorov | bec4558 | 2017-09-12 20:29:24 +0300 | [diff] [blame] | 1183 | def python = new com.mirantis.mk.Python() |
| 1184 | def dataStr = new groovy.json.JsonBuilder(data).toString() |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1185 | // TODO(alexz): parametrize? |
| 1186 | int retry = 10 |
chnyda | 4901a04 | 2017-11-16 12:14:56 +0100 | [diff] [blame] | 1187 | |
Jakub Josef | a2491ad | 2018-01-15 16:26:27 +0100 | [diff] [blame] | 1188 | def pepperCmdFile = "${venv}/pepper-cmd.json" |
| 1189 | writeFile file: pepperCmdFile, text: dataStr |
| 1190 | def pepperCmd = "pepper -c ${venv}/pepperrc --make-token -x ${venv}/.peppercache --json-file ${pepperCmdFile}" |
Oleg Grigorov | bec4558 | 2017-09-12 20:29:24 +0300 | [diff] [blame] | 1191 | |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1192 | int tries = 0 |
| 1193 | def FullOutput = ['status': 1] |
Jakub Josef | 37cd497 | 2018-02-01 16:25:25 +0100 | [diff] [blame] | 1194 | def outputObj |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1195 | while (tries++ < retry) { |
| 1196 | try { |
| 1197 | if (venv) { |
| 1198 | FullOutput = python.runVirtualenvCommand(venv, pepperCmd, true, true) |
| 1199 | } else { |
| 1200 | FullOutput = common.shCmdStatus(pepperCmd) |
| 1201 | } |
| 1202 | if (FullOutput['status'] != 0) { |
| 1203 | error() |
| 1204 | } |
| 1205 | break |
| 1206 | } catch (e) { |
| 1207 | // Check , if we get failed pepper HTTP call, and retry |
| 1208 | common.errorMsg("Command: ${pepperCmd} failed to execute with error:\n${FullOutput['stderr']}") |
| 1209 | if (FullOutput['stderr'].contains('Error with request: HTTP Error 50') || FullOutput['stderr'].contains('Pepper error: Server error')) { |
| 1210 | common.errorMsg("Pepper HTTP Error detected. Most probably, " + |
| 1211 | "master SaltReqTimeoutError in master zmq thread issue...lets retry ${tries}/${retry}") |
| 1212 | sleep(5) |
| 1213 | continue |
| 1214 | } |
| 1215 | } |
| 1216 | } |
| 1217 | // Try to parse json output. No sense to check exit code, since we always expect json answer only. |
Jakub Josef | 37cd497 | 2018-02-01 16:25:25 +0100 | [diff] [blame] | 1218 | try { |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1219 | outputObj = new groovy.json.JsonSlurperClassic().parseText(FullOutput['stdout']) |
| 1220 | } catch (Exception jsonE) { |
| 1221 | common.errorMsg('Parsing Salt API JSON response failed! Response: ' + FullOutput) |
| 1222 | throw jsonE |
Jakub Josef | 37cd497 | 2018-02-01 16:25:25 +0100 | [diff] [blame] | 1223 | } |
| 1224 | return outputObj |
Oleg Grigorov | bec4558 | 2017-09-12 20:29:24 +0300 | [diff] [blame] | 1225 | } |
Martin Polreich | ddfe51c | 2019-01-21 14:31:00 +0100 | [diff] [blame] | 1226 | |
azvyagintsev | b8b7f92 | 2019-06-13 13:39:04 +0300 | [diff] [blame] | 1227 | |
Martin Polreich | ddfe51c | 2019-01-21 14:31:00 +0100 | [diff] [blame] | 1228 | /** |
| 1229 | * Check time settings on defined nodes, compares them |
| 1230 | * and evaluates the results |
| 1231 | * |
| 1232 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 1233 | * @param target Targeted nodes to be checked |
| 1234 | * @param diff Maximum time difference (in seconds) to be accepted during time sync check |
| 1235 | * @return bool Return true if time difference is <= diff and returns false if time difference is > diff |
| 1236 | */ |
| 1237 | |
| 1238 | def checkClusterTimeSync(saltId, target) { |
| 1239 | def common = new com.mirantis.mk.Common() |
| 1240 | def salt = new com.mirantis.mk.Salt() |
| 1241 | |
| 1242 | times = [] |
| 1243 | try { |
| 1244 | diff = salt.getReturnValues(salt.getPillar(saltId, 'I@salt:master', 'linux:system:time_diff')) |
| 1245 | if (diff != null && diff != "" && diff.isInteger()) { |
| 1246 | diff = diff.toInteger() |
| 1247 | } else { |
| 1248 | diff = 5 |
| 1249 | } |
| 1250 | out = salt.runSaltProcessStep(saltId, target, 'status.time', '%s') |
| 1251 | outParsed = out['return'][0] |
| 1252 | def outKeySet = outParsed.keySet() |
| 1253 | for (key in outKeySet) { |
| 1254 | def time = outParsed[key].readLines().get(0) |
| 1255 | common.infoMsg(time) |
| 1256 | if (time.isInteger()) { |
| 1257 | times.add(time.toInteger()) |
| 1258 | } |
| 1259 | } |
| 1260 | if ((times.max() - times.min()) <= diff) { |
| 1261 | return true |
| 1262 | } else { |
| 1263 | return false |
| 1264 | } |
| 1265 | } catch(Exception e) { |
| 1266 | common.errorMsg("Could not check cluster time sync.") |
| 1267 | return false |
| 1268 | } |
| 1269 | } |
Martin Polreich | ad8e95b | 2019-03-29 12:10:00 +0100 | [diff] [blame] | 1270 | |
| 1271 | /** |
| 1272 | * Finds out IP address of the given node or a list of nodes |
| 1273 | * |
| 1274 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 1275 | * @param nodes Targeted node hostnames to be checked (String or List of strings) |
| 1276 | * @param useGrains If the, the value will be taken from grains. If false, it will be taken from 'hostname' command. |
| 1277 | * @return Map Return result Map in format ['nodeName1': 'ipAdress1', 'nodeName2': 'ipAdress2', ...] |
| 1278 | */ |
| 1279 | |
| 1280 | def getIPAddressesForNodenames(saltId, nodes = [], useGrains = true) { |
| 1281 | result = [:] |
| 1282 | |
| 1283 | if (nodes instanceof String) { |
| 1284 | nodes = [nodes] |
| 1285 | } |
| 1286 | |
| 1287 | if (useGrains) { |
| 1288 | for (String node in nodes) { |
| 1289 | ip = getReturnValues(getGrain(saltId, node, "fqdn_ip4"))["fqdn_ip4"][0] |
| 1290 | result[node] = ip |
| 1291 | } |
| 1292 | } else { |
| 1293 | for (String node in nodes) { |
| 1294 | ip = getReturnValues(cmdRun(saltId, node, "hostname -i")).readLines()[0] |
| 1295 | result[node] = ip |
| 1296 | } |
| 1297 | } |
| 1298 | return result |
| 1299 | } |
| 1300 | |
| 1301 | /** |
| 1302 | * Checks if required package is installed and returns averaged IO stats for selected disks. |
| 1303 | * Allows getting averaged values of specific parameter for all disks or a specified disk. |
| 1304 | * Interval between checks and its number is parametrized and configurable. |
| 1305 | * |
| 1306 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 1307 | * @param target Node to be targeted (Should only match 1 node) |
| 1308 | * @param parameterName Name of parameter from 'iostat' output (default = '' -- returns all variables) |
| 1309 | * @param interval Interval between checks (default = 1) |
| 1310 | * @param count Number of checks (default = 5) |
| 1311 | * @param disks Disks to be checked (default = '' -- returns all disks) |
| 1312 | * @param output Print Salt command return (default = true) |
| 1313 | * @return Map Map containing desired values in format ['disk':'value'] |
| 1314 | */ |
| 1315 | |
| 1316 | def getIostatValues(Map params) { |
| 1317 | def common = new com.mirantis.mk.Common() |
| 1318 | def ret = [:] |
| 1319 | if (isPackageInstalled(['saltId': params.saltId, 'target': params.target, 'packageName': 'sysstat', 'output': false])) { |
| 1320 | def arg = [params.get('interval', 1), params.get('count', 5), params.get('disks', '')] |
| 1321 | def res = getReturnValues(runSaltProcessStep(params.saltId, params.target, 'disk.iostat', arg, null, params.output)) |
| 1322 | if (res instanceof Map) { |
| 1323 | for (int i = 0; i < res.size(); i++) { |
| 1324 | def key = res.keySet()[i] |
| 1325 | if (params.containsKey('parameterName')) { |
| 1326 | if (res[key].containsKey(params.parameterName)){ |
| 1327 | ret[key] = res[key][params.parameterName] |
| 1328 | } else { |
| 1329 | common.errorMsg("Parameter '${params.parameterName}' not found for disk '${key}'. Valid parameter for this disk are: '${res[key].keySet()}'") |
| 1330 | } |
| 1331 | } else { |
| 1332 | return res // If no parameterName is defined, return all of them. |
| 1333 | } |
| 1334 | } |
| 1335 | } |
| 1336 | } else { |
| 1337 | common.errorMsg("Package 'sysstat' seems not to be installed on at least one of tageted nodes: ${params.target}. Please fix this to be able to check 'iostat' values. Find more in the docs TODO:<Add docs link>") |
| 1338 | } |
| 1339 | return ret |
| 1340 | } |
| 1341 | |
| 1342 | /** |
| 1343 | * Checks if defined package is installed on all nodes defined by target parameter. |
| 1344 | * |
| 1345 | * @param saltId Salt Connection object or pepperEnv (the command will be sent using the selected method) |
| 1346 | * @param target Node or nodes to be targeted |
| 1347 | * @param packageName Name of package to be checked |
| 1348 | * @param output Print Salt command return (default = true) |
| 1349 | * @return boolean True if package is installed on all defined nodes. False if not found on at least one of defined nodes. |
| 1350 | */ |
| 1351 | |
| 1352 | def isPackageInstalled(Map params) { |
| 1353 | def output = params.get('output', true) |
Ivan Berezovskiy | 81a0b8c | 2019-08-06 18:50:39 +0400 | [diff] [blame^] | 1354 | def res = runSaltProcessStep(params.saltId, params.target, "pkg.list_pkgs", [], null, output)['return'][0] |
Ivan Berezovskiy | 1480c7e | 2019-07-26 16:44:22 +0400 | [diff] [blame] | 1355 | if (res) { |
| 1356 | for (int i = 0; i < res.size(); i++) { |
| 1357 | def key = res.keySet()[i] |
Ivan Berezovskiy | 81a0b8c | 2019-08-06 18:50:39 +0400 | [diff] [blame^] | 1358 | if (!(res[key] instanceof Map && res[key].get(params.packageName, false))) { |
Ivan Berezovskiy | 1480c7e | 2019-07-26 16:44:22 +0400 | [diff] [blame] | 1359 | return false |
| 1360 | } |
Martin Polreich | ad8e95b | 2019-03-29 12:10:00 +0100 | [diff] [blame] | 1361 | } |
Ivan Berezovskiy | 1480c7e | 2019-07-26 16:44:22 +0400 | [diff] [blame] | 1362 | return true |
| 1363 | } else { |
| 1364 | return false |
Martin Polreich | ad8e95b | 2019-03-29 12:10:00 +0100 | [diff] [blame] | 1365 | } |
Martin Polreich | ad8e95b | 2019-03-29 12:10:00 +0100 | [diff] [blame] | 1366 | } |