Skip to content

Commit

Permalink
Pull upstream
Browse files Browse the repository at this point in the history
  • Loading branch information
buchanan committed Dec 29, 2015
2 parents 50b24e1 + 148a7d8 commit b257d79
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 15 deletions.
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ daemons as though they were running Salt locally. The long-term goal is to add
additional CLI scripts maintain the same interface as Salt's own CLI scripts
(``salt``, ``salt-run``, ``salt-key``, etc).

It does not require any additional dependencies and runs on Python 2.5+ and
Python 3. (Python 3 support is new, please file an issue if you encounter
trouble.)

.. __: https://github.com/saltstack/salt-api

Installation
Expand Down
37 changes: 28 additions & 9 deletions pepper/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@
'''
from __future__ import print_function

import json
import logging
import optparse
import os
import textwrap
import getpass
import time
try:
# Python 3
from configparser import ConfigParser
except ImportError:
# Python 2
import ConfigParser

import pepper

Expand All @@ -31,15 +36,15 @@ def emit(self, record): pass


class PepperCli(object):
def __init__(self, default_timeout_in_seconds=60*60, seconds_to_wait=3):
def __init__(self, default_timeout_in_seconds=60 * 60, seconds_to_wait=3):
self.seconds_to_wait = seconds_to_wait
self.parser = self.get_parser()
self.parser.option_groups.extend([self.add_globalopts(),
self.add_tgtopts(),
self.add_authopts()])
self.add_tgtopts(),
self.add_authopts()])
self.parser.defaults.update({'timeout': default_timeout_in_seconds,
'fail_if_minions_dont_respond': False,
'expr_form': 'glob'})
'fail_if_minions_dont_respond': False,
'expr_form': 'glob'})

def get_parser(self):
return optparse.OptionParser(
Expand All @@ -66,6 +71,13 @@ def parse(self):
action='store_true', help=textwrap.dedent('''\
Output the HTTP request/response headers on stderr'''))

self.parser.add_option('--ignore-ssl-errors', action='store_true',
dest='ignore_ssl_certificate_errors',
default=False,
help=textwrap.dedent('''\
Ignore any SSL certificate that may be encountered. Note that it is
recommended to resolve certificate errors for production.'''))

self.options, self.args = self.parser.parse_args()

def add_globalopts(self):
Expand All @@ -75,7 +87,7 @@ def add_globalopts(self):
optgroup = optparse.OptionGroup(self.parser, "Pepper ``salt`` Options",
"Mimic the ``salt`` CLI")

optgroup.add_option('-t', '--timeout', dest='timeout', type ='int',
optgroup.add_option('-t', '--timeout', dest='timeout', type='int',
help=textwrap.dedent('''\
Specify wait time (in seconds) before returning control to the
shell'''))
Expand Down Expand Up @@ -189,7 +201,10 @@ def get_login_details(self):
'SALTAPI_EAUTH': 'auto',
}

config = configparser.RawConfigParser()
try:
config = ConfigParser(interpolation=None)
except TypeError as e:
config = ConfigParser.RawConfigParser()
config.read(self.options.config)

# read file
Expand Down Expand Up @@ -272,7 +287,7 @@ def parse_cmd(self):
elif client.startswith('runner'):
low['fun'] = args.pop(0)
for arg in args:
key, value = arg.split('=')
key, value = arg.split('=', 1)
low[key] = value
else:
if len(args) < 1:
Expand Down Expand Up @@ -329,7 +344,11 @@ def run(self):
load = self.parse_cmd()
creds = iter(self.parse_login())

<<<<<<< HEAD
api = pepper.Pepper(next(creds), debug_http=self.options.debug_http)
=======
api = pepper.Pepper(next(creds), debug_http=self.options.debug_http, ignore_ssl_errors=self.options.ignore_ssl_certificate_errors)
>>>>>>> 148a7d86dc7d746590d6c61b71da1cb1726c03bf
auth = api.login(*list(creds))

if self.options.fail_if_minions_dont_respond:
Expand Down
20 changes: 15 additions & 5 deletions pepper/libpepper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import functools
import json
import logging
import ssl
import os
try:
import ssl
Expand Down Expand Up @@ -58,7 +59,7 @@ class Pepper(object):
u'ms-4': True}]}
'''
def __init__(self, api_url='https://localhost:8000', debug_http=False):
def __init__(self, api_url='https://localhost:8000', debug_http=False, ignore_ssl_errors=False):
'''
Initialize the class with the URL of the API
Expand All @@ -67,6 +68,8 @@ def __init__(self, api_url='https://localhost:8000', debug_http=False):
:param debug_http: Add a flag to urllib2 to output the HTTP exchange
:param ignore_ssl_errors: Add a flag to urllib2 to ignore invalid SSL certificates
:raises PepperException: if the api_url is misformed
'''
Expand All @@ -77,6 +80,7 @@ def __init__(self, api_url='https://localhost:8000', debug_http=False):

self.api_url = api_url
self.debug_http = int(debug_http)
self._ssl_verify = not ignore_ssl_errors
self.auth = {}

def req(self, path, data=None):
Expand Down Expand Up @@ -121,7 +125,13 @@ def req(self, path, data=None):

# Send request
try:
f = urlopen(req)
if not (self._ssl_verify):
con = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
#con.check_hostname = False
#con.verify_mode = ssl.CERT_NONE
f = urlopen(req, context=con)
else:
f = urlopen(req)
ret = json.loads(f.read().decode('utf-8'))
except (HTTPError, URLError) as exc:
logger.debug('Error with request', exc_info=True)
Expand Down Expand Up @@ -162,11 +172,11 @@ def req_requests(self, path, data=None):
}
if self.auth and 'token' in self.auth and self.auth['token']:
headers.setdefault('X-Auth-Token', self.auth['token'])
# TODO make an option
self._ssl_verify = False
# Optionally toggle SSL verification
self._ssl_verify = self.ignore_ssl_errors
params = {'url': self._construct_url(path),
'headers': headers,
'verify': self._ssl_verify,
'verify': self._ssl_verify == True,
'auth': auth,
'data': json.dumps(data),
}
Expand Down
10 changes: 9 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,24 @@ def read_version_tag():
else:
return out.strip() or None

else:
return read_version_from_json_file()

return None

def read_version_from_json_file():
with open(os.path.join(os.path.dirname(__file__), "pepper", "version.json")) as f:
return json.load(f)['version']

def parse_version_tag(tag):
'''
Parse the output from Git describe
Returns a tuple of the version number, number of commits (if any), and the
Git SHA (if available).
'''
tag = tag.decode('UTF-8')
if isinstance(tag, bytes):
tag = tag.decode()
if not tag or '-g' not in tag:
return tag, None, None

Expand Down

0 comments on commit b257d79

Please sign in to comment.