| 1 |
''' |
| 2 |
A Python library for working with Salt's REST API |
| 3 |
|
| 4 |
(Specifically the rest_cherrypy netapi module.) |
| 5 |
|
| 6 |
''' |
| 7 |
import json |
| 8 |
import logging |
| 9 |
import ssl |
| 10 |
try: |
| 11 |
ssl._create_default_https_context = ssl._create_stdlib_context |
| 12 |
except: |
| 13 |
pass |
| 14 |
|
| 15 |
try: |
| 16 |
from urllib.request import HTTPHandler, Request, urlopen, \ |
| 17 |
install_opener, build_opener |
| 18 |
from urllib.error import HTTPError, URLError |
| 19 |
import urllib.parse as urlparse |
| 20 |
except ImportError: |
| 21 |
from urllib2 import HTTPHandler, Request, urlopen, install_opener, build_opener, \ |
| 22 |
HTTPError, URLError |
| 23 |
import urlparse |
| 24 |
|
| 25 |
logger = logging.getLogger('pepper') |
| 26 |
|
| 27 |
|
| 28 |
class PepperException(Exception): |
| 29 |
pass |
| 30 |
|
| 31 |
|
| 32 |
class Pepper(object): |
| 33 |
''' |
| 34 |
A thin wrapper for making HTTP calls to the salt-api rest_cherrpy REST |
| 35 |
interface |
| 36 |
|
| 37 |
>>> api = Pepper('https://localhost:8000') |
| 38 |
>>> api.login('saltdev', 'saltdev', 'pam') |
| 39 |
{"return": [ |
| 40 |
{ |
| 41 |
"eauth": "pam", |
| 42 |
"expire": 1370434219.714091, |
| 43 |
"perms": [ |
| 44 |
"test.*" |
| 45 |
], |
| 46 |
"start": 1370391019.71409, |
| 47 |
"token": "c02a6f4397b5496ba06b70ae5fd1f2ab75de9237", |
| 48 |
"user": "saltdev" |
| 49 |
} |
| 50 |
] |
| 51 |
} |
| 52 |
>>> api.low([{'client': 'local', 'tgt': '*', 'fun': 'test.ping'}]) |
| 53 |
{u'return': [{u'ms-0': True, |
| 54 |
u'ms-1': True, |
| 55 |
u'ms-2': True, |
| 56 |
u'ms-3': True, |
| 57 |
u'ms-4': True}]} |
| 58 |
|
| 59 |
''' |
| 60 |
def __init__(self, |
| 61 |
api_url='https://localhost:8000', |
| 62 |
debug_http=False, |
| 63 |
ignore_ssl_errors=False): |
| 64 |
''' |
| 65 |
Initialize the class with the URL of the API |
| 66 |
|
| 67 |
:param api_url: Host or IP address of the salt-api URL; |
| 68 |
include the port number |
| 69 |
|
| 70 |
:param debug_http: Add a flag to urllib2 to output the HTTP exchange |
| 71 |
|
| 72 |
:param ignore_ssl_errors: Add a flag to urllib2 to ignore invalid SSL certificates |
| 73 |
|
| 74 |
:raises PepperException: if the api_url is misformed |
| 75 |
|
| 76 |
''' |
| 77 |
split = urlparse.urlsplit(api_url) |
| 78 |
if split.scheme not in ['http', 'https']: |
| 79 |
raise PepperException("salt-api URL missing HTTP(s) protocol: {0}" |
| 80 |
.format(api_url)) |
| 81 |
|
| 82 |
self.api_url = api_url |
| 83 |
self.debug_http = int(debug_http) |
| 84 |
self._ssl_verify = not ignore_ssl_errors |
| 85 |
self.auth = {} |
| 86 |
|
| 87 |
def req_stream(self, path): |
| 88 |
''' |
| 89 |
A thin wrapper to get a response from saltstack api. |
| 90 |
The body of the response will not be downloaded immediately. |
| 91 |
Make sure to close the connection after use. |
| 92 |
api = Pepper('http://ipaddress/api/') |
| 93 |
print(api.login('salt','salt','pam')) |
| 94 |
response = api.req_stream('/events') |
| 95 |
|
| 96 |
:param path: The path to the salt api resource |
| 97 |
|
| 98 |
:return: :class:`Response <Response>` object |
| 99 |
|
| 100 |
:rtype: requests.Response |
| 101 |
''' |
| 102 |
import requests |
| 103 |
|
| 104 |
headers = { |
| 105 |
'Accept': 'application/json', |
| 106 |
'Content-Type': 'application/json', |
| 107 |
'X-Requested-With': 'XMLHttpRequest', |
| 108 |
} |
| 109 |
if self.auth and 'token' in self.auth and self.auth['token']: |
| 110 |
headers.setdefault('X-Auth-Token', self.auth['token']) |
| 111 |
else: |
| 112 |
raise PepperException('Authentication required') |
| 113 |
return |
| 114 |
|
| 115 |
|
| 116 |
params = {'url': self._construct_url(path), |
| 117 |
'headers': headers, |
| 118 |
'verify': self._ssl_verify == True, |
| 119 |
'stream': True |
| 120 |
} |
| 121 |
try: |
| 122 |
resp = requests.get(**params) |
| 123 |
|
| 124 |
if resp.status_code == 401: |
| 125 |
raise PepperException(str(resp.status_code) + ':Authentication denied') |
| 126 |
return |
| 127 |
|
| 128 |
if resp.status_code == 500: |
| 129 |
raise PepperException(str(resp.status_code) + ':Server error.') |
| 130 |
return |
| 131 |
|
| 132 |
if resp.status_code == 404: |
| 133 |
raise PepperException(str(resp.status_code) +' :This request returns nothing.') |
| 134 |
return |
| 135 |
except PepperException as e: |
| 136 |
print(e) |
| 137 |
return |
| 138 |
return resp |
| 139 |
|
| 140 |
def req_get(self, path): |
| 141 |
''' |
| 142 |
A thin wrapper from get http method of saltstack api |
| 143 |
api = Pepper('http://ipaddress/api/') |
| 144 |
print(api.login('salt','salt','pam')) |
| 145 |
print(api.req_get('/keys')) |
| 146 |
''' |
| 147 |
import requests |
| 148 |
|
| 149 |
headers = { |
| 150 |
'Accept': 'application/json', |
| 151 |
'Content-Type': 'application/json', |
| 152 |
'X-Requested-With': 'XMLHttpRequest', |
| 153 |
} |
| 154 |
if self.auth and 'token' in self.auth and self.auth['token']: |
| 155 |
headers.setdefault('X-Auth-Token', self.auth['token']) |
| 156 |
else: |
| 157 |
raise PepperException('Authentication required') |
| 158 |
return |
| 159 |
|
| 160 |
|
| 161 |
params = {'url': self._construct_url(path), |
| 162 |
'headers': headers, |
| 163 |
'verify': self._ssl_verify == True, |
| 164 |
} |
| 165 |
try: |
| 166 |
resp = requests.get(**params) |
| 167 |
|
| 168 |
if resp.status_code == 401: |
| 169 |
raise PepperException(str(resp.status_code) + ':Authentication denied') |
| 170 |
return |
| 171 |
|
| 172 |
if resp.status_code == 500: |
| 173 |
raise PepperException(str(resp.status_code) + ':Server error.') |
| 174 |
return |
| 175 |
|
| 176 |
if resp.status_code == 404: |
| 177 |
raise PepperException(str(resp.status_code) +' :This request returns nothing.') |
| 178 |
return |
| 179 |
except PepperException as e: |
| 180 |
print(e) |
| 181 |
return |
| 182 |
return resp.json() |
| 183 |
|
| 184 |
def req(self, path, data=None): |
| 185 |
''' |
| 186 |
A thin wrapper around urllib2 to send requests and return the response |
| 187 |
|
| 188 |
If the current instance contains an authentication token it will be |
| 189 |
attached to the request as a custom header. |
| 190 |
|
| 191 |
:rtype: dictionary |
| 192 |
|
| 193 |
''' |
| 194 |
if ((hasattr(data, 'get') and data.get('eauth') == 'kerberos') |
| 195 |
or self.auth.get('eauth') == 'kerberos'): |
| 196 |
return self.req_requests(path, data) |
| 197 |
|
| 198 |
headers = { |
| 199 |
'Accept': 'application/json', |
| 200 |
'Content-Type': 'application/json', |
| 201 |
'X-Requested-With': 'XMLHttpRequest', |
| 202 |
} |
| 203 |
|
| 204 |
handler = HTTPHandler(debuglevel=self.debug_http) |
| 205 |
opener = build_opener(handler) |
| 206 |
install_opener(opener) |
| 207 |
|
| 208 |
|
| 209 |
if data is not None: |
| 210 |
postdata = json.dumps(data).encode() |
| 211 |
clen = len(postdata) |
| 212 |
else: |
| 213 |
postdata = None |
| 214 |
|
| 215 |
|
| 216 |
url = self._construct_url(path) |
| 217 |
req = Request(url, postdata, headers) |
| 218 |
|
| 219 |
|
| 220 |
if data is not None: |
| 221 |
req.add_header('Content-Length', clen) |
| 222 |
|
| 223 |
|
| 224 |
if self.auth and 'token' in self.auth and self.auth['token']: |
| 225 |
req.add_header('X-Auth-Token', self.auth['token']) |
| 226 |
|
| 227 |
|
| 228 |
try: |
| 229 |
if not (self._ssl_verify): |
| 230 |
con = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 231 |
|
| 232 |
|
| 233 |
f = urlopen(req, context=con) |
| 234 |
else: |
| 235 |
f = urlopen(req) |
| 236 |
ret = json.loads(f.read().decode('utf-8')) |
| 237 |
except (HTTPError, URLError) as exc: |
| 238 |
logger.debug('Error with request', exc_info=True) |
| 239 |
status = getattr(exc, 'code', None) |
| 240 |
|
| 241 |
if status == 401: |
| 242 |
raise PepperException('Authentication denied') |
| 243 |
|
| 244 |
if status == 500: |
| 245 |
raise PepperException('Server error.') |
| 246 |
|
| 247 |
logger.error('Error with request: {0}'.format(exc)) |
| 248 |
raise |
| 249 |
except AttributeError: |
| 250 |
logger.debug('Error converting response from JSON', exc_info=True) |
| 251 |
raise PepperException('Unable to parse the server response.') |
| 252 |
|
| 253 |
return ret |
| 254 |
|
| 255 |
def req_requests(self, path, data=None): |
| 256 |
''' |
| 257 |
A thin wrapper around request and request_kerberos to send |
| 258 |
requests and return the response |
| 259 |
|
| 260 |
If the current instance contains an authentication token it will be |
| 261 |
attached to the request as a custom header. |
| 262 |
|
| 263 |
:rtype: dictionary |
| 264 |
|
| 265 |
''' |
| 266 |
import requests |
| 267 |
from requests_kerberos import HTTPKerberosAuth, OPTIONAL |
| 268 |
auth = HTTPKerberosAuth(mutual_authentication=OPTIONAL) |
| 269 |
headers = { |
| 270 |
'Accept': 'application/json', |
| 271 |
'Content-Type': 'application/json', |
| 272 |
'X-Requested-With': 'XMLHttpRequest', |
| 273 |
} |
| 274 |
if self.auth and 'token' in self.auth and self.auth['token']: |
| 275 |
headers.setdefault('X-Auth-Token', self.auth['token']) |
| 276 |
|
| 277 |
params = {'url': self._construct_url(path), |
| 278 |
'headers': headers, |
| 279 |
'verify': self._ssl_verify is True, |
| 280 |
'auth': auth, |
| 281 |
'data': json.dumps(data), |
| 282 |
} |
| 283 |
logger.debug('postdata {0}'.format(params)) |
| 284 |
resp = requests.post(**params) |
| 285 |
if resp.status_code == 401: |
| 286 |
|
| 287 |
raise PepperException('Authentication denied') |
| 288 |
if resp.status_code == 500: |
| 289 |
|
| 290 |
raise PepperException('Server error.') |
| 291 |
return resp.json() |
| 292 |
|
| 293 |
def low(self, lowstate, path='/'): |
| 294 |
''' |
| 295 |
Execute a command through salt-api and return the response |
| 296 |
|
| 297 |
:param string path: URL path to be joined with the API hostname |
| 298 |
|
| 299 |
:param list lowstate: a list of lowstate dictionaries |
| 300 |
''' |
| 301 |
return self.req(path, lowstate) |
| 302 |
|
| 303 |
def local(self, tgt, fun, arg=None, kwarg=None, expr_form='glob', |
| 304 |
timeout=None, ret=None): |
| 305 |
''' |
| 306 |
Run a single command using the ``local`` client |
| 307 |
|
| 308 |
Wraps :meth:`low`. |
| 309 |
''' |
| 310 |
low = { |
| 311 |
'client': 'local', |
| 312 |
'tgt': tgt, |
| 313 |
'fun': fun, |
| 314 |
} |
| 315 |
|
| 316 |
if arg: |
| 317 |
low['arg'] = arg |
| 318 |
|
| 319 |
if kwarg: |
| 320 |
low['kwarg'] = kwarg |
| 321 |
|
| 322 |
if expr_form: |
| 323 |
low['expr_form'] = expr_form |
| 324 |
|
| 325 |
if timeout: |
| 326 |
low['timeout'] = timeout |
| 327 |
|
| 328 |
if ret: |
| 329 |
low['ret'] = ret |
| 330 |
|
| 331 |
return self.low([low]) |
| 332 |
|
| 333 |
def local_async(self, tgt, fun, arg=None, kwarg=None, expr_form='glob', |
| 334 |
timeout=None, ret=None): |
| 335 |
''' |
| 336 |
Run a single command using the ``local_async`` client |
| 337 |
|
| 338 |
Wraps :meth:`low`. |
| 339 |
''' |
| 340 |
low = { |
| 341 |
'client': 'local_async', |
| 342 |
'tgt': tgt, |
| 343 |
'fun': fun, |
| 344 |
} |
| 345 |
|
| 346 |
if arg: |
| 347 |
low['arg'] = arg |
| 348 |
|
| 349 |
if kwarg: |
| 350 |
low['kwarg'] = kwarg |
| 351 |
|
| 352 |
if expr_form: |
| 353 |
low['expr_form'] = expr_form |
| 354 |
|
| 355 |
if timeout: |
| 356 |
low['timeout'] = timeout |
| 357 |
|
| 358 |
if ret: |
| 359 |
low['ret'] = ret |
| 360 |
|
| 361 |
return self.low([low]) |
| 362 |
|
| 363 |
def local_batch(self, tgt, fun, arg=None, kwarg=None, expr_form='glob', |
| 364 |
batch='50%', ret=None): |
| 365 |
''' |
| 366 |
Run a single command using the ``local_batch`` client |
| 367 |
|
| 368 |
Wraps :meth:`low`. |
| 369 |
''' |
| 370 |
low = { |
| 371 |
'client': 'local_batch', |
| 372 |
'tgt': tgt, |
| 373 |
'fun': fun, |
| 374 |
} |
| 375 |
|
| 376 |
if arg: |
| 377 |
low['arg'] = arg |
| 378 |
|
| 379 |
if kwarg: |
| 380 |
low['kwarg'] = kwarg |
| 381 |
|
| 382 |
if expr_form: |
| 383 |
low['expr_form'] = expr_form |
| 384 |
|
| 385 |
if batch: |
| 386 |
low['batch'] = batch |
| 387 |
|
| 388 |
if ret: |
| 389 |
low['ret'] = ret |
| 390 |
|
| 391 |
return self.low([low]) |
| 392 |
|
| 393 |
def lookup_jid(self, jid): |
| 394 |
''' |
| 395 |
Get job results |
| 396 |
|
| 397 |
Wraps :meth:`runner`. |
| 398 |
''' |
| 399 |
|
| 400 |
return self.runner('jobs.lookup_jid', jid='{0}'.format(jid)) |
| 401 |
|
| 402 |
def runner(self, fun, arg=None, **kwargs): |
| 403 |
''' |
| 404 |
Run a single command using the ``runner`` client |
| 405 |
|
| 406 |
Usage:: |
| 407 |
runner('jobs.lookup_jid', jid=12345) |
| 408 |
''' |
| 409 |
low = { |
| 410 |
'client': 'runner', |
| 411 |
'fun': fun, |
| 412 |
} |
| 413 |
if arg: |
| 414 |
low['arg'] = arg |
| 415 |
|
| 416 |
low.update(kwargs) |
| 417 |
|
| 418 |
return self.low([low]) |
| 419 |
|
| 420 |
def wheel(self, fun, arg=None, kwarg=None, **kwargs): |
| 421 |
''' |
| 422 |
Run a single command using the ``wheel`` client |
| 423 |
|
| 424 |
Usage:: |
| 425 |
wheel('key.accept', match='myminion') |
| 426 |
''' |
| 427 |
low = { |
| 428 |
'client': 'wheel', |
| 429 |
'fun': fun, |
| 430 |
} |
| 431 |
|
| 432 |
if arg: |
| 433 |
low['arg'] = arg |
| 434 |
if kwarg: |
| 435 |
low['kwarg'] = kwarg |
| 436 |
|
| 437 |
low.update(kwargs) |
| 438 |
|
| 439 |
return self.low([low]) |
| 440 |
|
| 441 |
def _send_auth(self, path, **kwargs): |
| 442 |
return self.req(path, kwargs) |
| 443 |
|
| 444 |
def login(self, username=None, password=None, eauth=None, **kwargs): |
| 445 |
''' |
| 446 |
Authenticate with salt-api and return the user permissions and |
| 447 |
authentication token or an empty dict |
| 448 |
|
| 449 |
''' |
| 450 |
local = locals() |
| 451 |
kwargs.update( |
| 452 |
dict( |
| 453 |
(key, local[key]) for key in ( |
| 454 |
'username', |
| 455 |
'password', |
| 456 |
'eauth' |
| 457 |
) if local.get(key, None) is not None |
| 458 |
) |
| 459 |
) |
| 460 |
self.auth = self._send_auth('/login', **kwargs).get('return', [{}])[0] |
| 461 |
return self.auth |
| 462 |
|
| 463 |
def token(self, **kwargs): |
| 464 |
''' |
| 465 |
Get an eauth token from Salt for use with the /run URL |
| 466 |
|
| 467 |
''' |
| 468 |
self.auth = self._send_auth('/token', **kwargs)[0] |
| 469 |
return self.auth |
| 470 |
|
| 471 |
def _construct_url(self, path): |
| 472 |
''' |
| 473 |
Construct the url to salt-api for the given path |
| 474 |
|
| 475 |
Args: |
| 476 |
path: the path to the salt-api resource |
| 477 |
|
| 478 |
>>> api = Pepper('https://localhost:8000/salt-api/') |
| 479 |
>>> api._construct_url('/login') |
| 480 |
'https://localhost:8000/salt-api/login' |
| 481 |
''' |
| 482 |
|
| 483 |
relative_path = path.lstrip('/') |
| 484 |
return urlparse.urljoin(self.api_url, relative_path) |