desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
':param string consumer_key: Key provided by Yahoo.
:param string consumer_secret: Secret corresponding to the key
provided by Yahoo.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception.
:param dict proxies: If specified, routes this geocoder"s requests
through the specified proxy. E.g., {"https": "192.0.2.0"}. For
more information, see documentation on
:class:`urllib2.ProxyHandler`.
.. versionadded:: 0.96'
| def __init__(self, consumer_key, consumer_secret, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| if requests_missing:
raise ImportError('requests-oauthlib is needed for YahooPlaceFinder. Install with `pip install geopy -e ".[placefinder]"`.')
super(YahooPlaceFinder, self).__init__(timeout=timeout, proxies=proxies, user_agent=user_agent)
self.consumer_key = (unicode(consumer_key) if (not py3k) else str(consumer_key))
self.consumer_secret = (unicode(consumer_secret) if (not py3k) else str(consumer_secret))
self.auth = OAuth1(client_key=self.consumer_key, client_secret=self.consumer_secret, signature_method='HMAC-SHA1', signature_type='AUTH_HEADER')
self.api = 'https://yboss.yahooapis.com/geo/placefinder'
|
'Returns only the results that meet the minimum quality threshold
and are located in expected countries.'
| @staticmethod
def _filtered_results(results, min_quality, valid_country_codes):
| if min_quality:
results = [loc for loc in results if (int(loc.raw['quality']) > min_quality)]
if valid_country_codes:
results = [loc for loc in results if (loc.raw['countrycode'] in valid_country_codes)]
return results
|
'Returns the parsed result of a PlaceFinder API call.'
| def _parse_response(self, content):
| try:
placefinder = content['bossresponse']['placefinder']
if ((not len(placefinder)) or (not len(placefinder.get('results', [])))):
return None
results = [Location(self.humanize(place), (float(place['latitude']), float(place['longitude'])), raw=place) for place in placefinder['results']]
except (KeyError, ValueError):
raise GeocoderParseError('Error parsing PlaceFinder result')
return results
|
'Returns a human readable representation of a raw PlaceFinder location'
| @staticmethod
def humanize(location):
| return ', '.join([location[line] for line in ['line1', 'line2', 'line3', 'line4'] if location[line]])
|
'Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int min_quality:
:param bool reverse:
:param valid_country_codes:
:type valid_country_codes: list or tuple
:param bool with_timezone: Include the timezone in the response\'s
`raw` dictionary (as `timezone`).'
| def geocode(self, query, exactly_one=True, timeout=None, min_quality=0, reverse=False, valid_country_codes=None, with_timezone=False):
| params = {'location': query, 'flags': 'J'}
if (reverse is True):
params['gflags'] = 'R'
if (exactly_one is True):
params['count'] = '1'
if (with_timezone is True):
params['flags'] += 'T'
response = self._call_geocoder(self.api, timeout=timeout, requester=get, params=params, auth=self.auth)
results = self._parse_response(response)
if (results is None):
return None
results = self._filtered_results(results, min_quality, valid_country_codes)
if exactly_one:
return results[0]
else:
return results
|
'Returns a reverse geocoded location using Yahoo"s PlaceFinder API.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param bool exactly_one: Return one result or a list of results, if
available.'
| def reverse(self, query, exactly_one=True, timeout=None):
| query = self._coerce_point_to_string(query)
if isinstance(query, string_compare):
query = query.replace(' ', '')
return self.geocode(query, exactly_one=exactly_one, timeout=timeout, reverse=True)
|
'Initialize a customized Baidu geocoder using the v2 API.
.. versionadded:: 1.0.0
:param string api_key: The API key required by Baidu Map to perform
geocoding requests. API keys are managed through the Baidu APIs
console (http://lbsyun.baidu.com/apiconsole/key).
:param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme.
Default is http and only http support.
:param dict proxies: If specified, routes this geocoder\'s requests
through the specified proxy. E.g., {"https": "192.0.2.0"}. For
more information, see documentation on
:class:`urllib2.ProxyHandler`.'
| def __init__(self, api_key, scheme='http', timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| super(Baidu, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent)
self.api_key = api_key
self.scheme = scheme
self.doc = {}
self.api = 'http://api.map.baidu.com/geocoder/v2/'
|
'Format the components dict to something Baidu understands.'
| @staticmethod
def _format_components_param(components):
| return '|'.join((':'.join(item) for item in components.items()))
|
'Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder\'s initialization.'
| def geocode(self, query, exactly_one=True, timeout=None):
| params = {'ak': self.api_key, 'output': 'json', 'address': (self.format_string % query)}
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.geocode: %s', self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one)
|
'Given a point, find an address.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder\'s initialization.'
| def reverse(self, query, timeout=None):
| params = {'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query)}
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.reverse: %s', self.__class__.__name__, url)
return self._parse_reverse_json(self._call_geocoder(url, timeout=timeout))
|
'Parses a location from a single-result reverse API call.'
| @staticmethod
def _parse_reverse_json(page):
| place = page.get('result')
location = place.get('formatted_address').encode('utf-8')
latitude = place['location']['lat']
longitude = place['location']['lng']
return Location(location, (latitude, longitude), place)
|
'Returns location, (latitude, longitude) from JSON feed.'
| def _parse_json(self, page, exactly_one=True):
| place = page.get('result', None)
if (not place):
self._check_status(page.get('status'))
return None
def parse_place(place):
'\n Get the location, lat, lng from a single JSON place.\n '
location = place.get('level')
latitude = place['location']['lat']
longitude = place['location']['lng']
return Location(location, (latitude, longitude), place)
if exactly_one:
return parse_place(place)
else:
return [parse_place(item) for item in place]
|
'Validates error statuses.'
| @staticmethod
def _check_status(status):
| if (status == '0'):
return
if (status == '1'):
raise GeocoderQueryError('Internal server error.')
elif (status == '2'):
raise GeocoderQueryError('Invalid request.')
elif (status == '3'):
raise GeocoderAuthenticationFailure('Authentication failure.')
elif (status == '4'):
raise GeocoderQuotaExceeded('Quota validate failure.')
elif (status == '5'):
raise GeocoderQueryError('AK Illegal or Not Exist.')
elif (status == '101'):
raise GeocoderQueryError('Your request was denied.')
elif (status == '102'):
raise GeocoderQueryError('IP/SN/SCODE/REFERER Illegal:')
elif (status == '2xx'):
raise GeocoderQueryError('Has No Privilleges.')
elif (status == '3xx'):
raise GeocoderQuotaExceeded('Quota Error.')
else:
raise GeocoderQueryError('Unknown error')
|
'Initialize a customized Open Cage Data geocoder.
:param string api_key: The API key required by Open Cage Data
to perform geocoding requests. You can get your key here:
https://developer.opencagedata.com/
:param string domain: Currently it is \'api.opencagedata.com\', can
be changed for testing purposes.
:param string scheme: Use \'https\' or \'http\' as the API URL\'s scheme.
Default is https. Note that SSL connections\' certificates are not
verified.
:param dict proxies: If specified, routes this geocoder\'s requests
through the specified proxy. E.g., {"https": "192.0.2.0"}. For
more information, see documentation on
:class:`urllib2.ProxyHandler`.'
| def __init__(self, api_key, domain='api.opencagedata.com', scheme=DEFAULT_SCHEME, timeout=DEFAULT_TIMEOUT, proxies=None, user_agent=None):
| super(OpenCage, self).__init__(scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent)
self.api_key = api_key
self.domain = domain.strip('/')
self.scheme = scheme
self.api = ('%s://%s/geocode/v1/json' % (self.scheme, self.domain))
|
'Geocode a location query.
:param string query: The query string to be geocoded; this must
be URL encoded.
:param string language: an IETF format language code (such as `es`
for Spanish or pt-BR for Brazilian Portuguese); if this is
omitted a code of `en` (English) will be assumed by the remote
service.
:param string bounds: Provides the geocoder with a hint to the region
that the query resides in. This value will help the geocoder
but will not restrict the possible results to the supplied
region. The bounds parameter should be specified as 4
coordinate points forming the south-west and north-east
corners of a bounding box. For example,
`bounds=-0.563160,51.280430,0.278970,51.683979`.
:param string country: Provides the geocoder with a hint to the
country that the query resides in. This value will help the
geocoder but will not restrict the possible results to the
supplied country. The country code is a 3 character code as
defined by the ISO 3166-1 Alpha 3 standard.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder\'s initialization.'
| def geocode(self, query, bounds=None, country=None, language=None, exactly_one=True, timeout=None):
| params = {'key': self.api_key, 'q': (self.format_string % query)}
if bounds:
params['bounds'] = bounds
if language:
params['language'] = language
if country:
params['country'] = country
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.geocode: %s', self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
|
'Given a point, find an address.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param string language: The language in which to return results.
:param boolean exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder\'s initialization.'
| def reverse(self, query, language=None, exactly_one=False, timeout=None):
| params = {'key': self.api_key, 'q': self._coerce_point_to_string(query)}
if language:
params['language'] = language
url = '?'.join((self.api, urlencode(params)))
logger.debug('%s.reverse: %s', self.__class__.__name__, url)
return self._parse_json(self._call_geocoder(url, timeout=timeout), exactly_one)
|
'Returns location, (latitude, longitude) from json feed.'
| def _parse_json(self, page, exactly_one=True):
| places = page.get('results', [])
if (not len(places)):
self._check_status(page.get('status'))
return None
def parse_place(place):
'Get the location, lat, lng from a single json place.'
location = place.get('formatted')
latitude = place['geometry']['lat']
longitude = place['geometry']['lng']
return Location(location, (latitude, longitude), place)
if exactly_one:
return parse_place(places[0])
else:
return [parse_place(place) for place in places]
|
'Validates error statuses.'
| @staticmethod
def _check_status(status):
| status_code = status['code']
if (status_code == 429):
raise GeocoderQuotaExceeded('The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time.')
if (status_code == 200):
return
if (status_code == 403):
raise GeocoderQueryError('Your request was denied.')
else:
raise GeocoderQueryError('Unknown error.')
|
'Location as a formatted string returned by the geocoder or constructed
by geopy, depending on the service.
:rtype: unicode'
| @property
def address(self):
| return self._address
|
'Location\'s latitude.
:rtype: float or None'
| @property
def latitude(self):
| return self._point[0]
|
'Location\'s longitude.
:rtype: float or None'
| @property
def longitude(self):
| return self._point[1]
|
'Location\'s altitude.
:rtype: float or None'
| @property
def altitude(self):
| return self._point[2]
|
':class:`geopy.point.Point` instance representing the location\'s
latitude, longitude, and altitude.
:rtype: :class:`geopy.point.Point` or None'
| @property
def point(self):
| return (self._point if (self._point != (None, None, None)) else None)
|
'Location\'s raw, unparsed geocoder response. For details on this,
consult the service\'s documentation.
:rtype: dict or None'
| @property
def raw(self):
| return self._raw
|
'Backwards compatibility with geopy<0.98 tuples.'
| def __getitem__(self, index):
| return self._tuple[index]
|
'Abstract method for measure'
| def measure(self, a, b):
| raise NotImplementedError()
|
'TODO docs.'
| def destination(self, point, bearing, distance=None):
| point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if (distance is None):
distance = self
if isinstance(distance, Distance):
distance = distance.kilometers
d_div_r = (float(distance) / self.RADIUS)
lat2 = asin(((sin(lat1) * cos(d_div_r)) + ((cos(lat1) * sin(d_div_r)) * cos(bearing))))
lng2 = (lng1 + atan2(((sin(bearing) * sin(d_div_r)) * cos(lat1)), (cos(d_div_r) - (sin(lat1) * sin(lat2)))))
return Point(units.degrees(radians=lat2), units.degrees(radians=lng2))
|
'Change the ellipsoid used in the calculation.'
| def set_ellipsoid(self, ellipsoid):
| if (not isinstance(ellipsoid, (list, tuple))):
try:
self.ELLIPSOID = ELLIPSOIDS[ellipsoid]
self.ellipsoid_key = ellipsoid
except KeyError:
raise Exception('Invalid ellipsoid. See geopy.distance.ELIPSOIDS')
else:
self.ELLIPSOID = ellipsoid
self.ellipsoid_key = None
return
|
'TODO docs.'
| def destination(self, point, bearing, distance=None):
| point = Point(point)
lat1 = units.radians(degrees=point.latitude)
lng1 = units.radians(degrees=point.longitude)
bearing = units.radians(degrees=bearing)
if (distance is None):
distance = self
if isinstance(distance, Distance):
distance = distance.kilometers
ellipsoid = self.ELLIPSOID
if isinstance(ellipsoid, string_compare):
ellipsoid = ELLIPSOIDS[ellipsoid]
(major, minor, f) = ellipsoid
tan_reduced1 = ((1 - f) * tan(lat1))
cos_reduced1 = (1 / sqrt((1 + (tan_reduced1 ** 2))))
sin_reduced1 = (tan_reduced1 * cos_reduced1)
(sin_bearing, cos_bearing) = (sin(bearing), cos(bearing))
sigma1 = atan2(tan_reduced1, cos_bearing)
sin_alpha = (cos_reduced1 * sin_bearing)
cos_sq_alpha = (1 - (sin_alpha ** 2))
u_sq = ((cos_sq_alpha * ((major ** 2) - (minor ** 2))) / (minor ** 2))
A = (1 + ((u_sq / 16384.0) * (4096 + (u_sq * ((-768) + (u_sq * (320 - (175 * u_sq))))))))
B = ((u_sq / 1024.0) * (256 + (u_sq * ((-128) + (u_sq * (74 - (47 * u_sq)))))))
sigma = (distance / (minor * A))
sigma_prime = (2 * pi)
while (abs((sigma - sigma_prime)) > 1e-11):
cos2_sigma_m = cos(((2 * sigma1) + sigma))
(sin_sigma, cos_sigma) = (sin(sigma), cos(sigma))
delta_sigma = ((B * sin_sigma) * (cos2_sigma_m + ((B / 4.0) * ((cos_sigma * ((-1) + (2 * cos2_sigma_m))) - ((((B / 6.0) * cos2_sigma_m) * ((-3) + (4 * (sin_sigma ** 2)))) * ((-3) + (4 * (cos2_sigma_m ** 2))))))))
sigma_prime = sigma
sigma = ((distance / (minor * A)) + delta_sigma)
(sin_sigma, cos_sigma) = (sin(sigma), cos(sigma))
lat2 = atan2(((sin_reduced1 * cos_sigma) + ((cos_reduced1 * sin_sigma) * cos_bearing)), ((1 - f) * sqrt(((sin_alpha ** 2) + (((sin_reduced1 * sin_sigma) - ((cos_reduced1 * cos_sigma) * cos_bearing)) ** 2)))))
lambda_lng = atan2((sin_sigma * sin_bearing), ((cos_reduced1 * cos_sigma) - ((sin_reduced1 * sin_sigma) * cos_bearing)))
C = (((f / 16.0) * cos_sq_alpha) * (4 + (f * (4 - (3 * cos_sq_alpha)))))
delta_lng = (lambda_lng - ((((1 - C) * f) * sin_alpha) * (sigma + ((C * sin_sigma) * (cos2_sigma_m + ((C * cos_sigma) * ((-1) + (2 * (cos2_sigma_m ** 2)))))))))
lng2 = (lng1 + delta_lng)
return Point(units.degrees(radians=lat2), units.degrees(radians=lng2))
|
':param float latitude: Latitude of point.
:param float longitude: Longitude of point.
:param float altitude: Altitude of point.'
| def __new__(cls, latitude=None, longitude=None, altitude=None):
| single_arg = ((longitude is None) and (altitude is None))
if (single_arg and (not isinstance(latitude, util.NUMBER_TYPES))):
arg = latitude
if (arg is None):
pass
elif isinstance(arg, Point):
return cls.from_point(arg)
elif isinstance(arg, string_compare):
return cls.from_string(arg)
else:
try:
seq = iter(arg)
except TypeError:
raise TypeError(('Failed to create Point instance from %r.' % (arg,)))
else:
return cls.from_sequence(seq)
latitude = float((latitude or 0.0))
if (abs(latitude) > 90):
latitude = (((latitude + 90) % 180) - 90)
longitude = float((longitude or 0.0))
if (abs(longitude) > 180):
longitude = (((longitude + 180) % 360) - 180)
altitude = float((altitude or 0.0))
self = super(Point, cls).__new__(cls)
self.latitude = latitude
self.longitude = longitude
self.altitude = altitude
self._items = [self.latitude, self.longitude, self.altitude]
return self
|
'Format decimal degrees (DD) to degrees minutes seconds (DMS)'
| def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'):
| latitude = ('%s %s' % (format_degrees(abs(self.latitude), symbols={'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char}), (((self.latitude >= 0) and 'N') or 'S')))
longitude = ('%s %s' % (format_degrees(abs(self.longitude), symbols={'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char}), (((self.longitude >= 0) and 'E') or 'W')))
coordinates = [latitude, longitude]
if (altitude is None):
altitude = bool(self.altitude)
if altitude:
if (not isinstance(altitude, string_compare)):
altitude = 'km'
coordinates.append(self.format_altitude(altitude))
return ', '.join(coordinates)
|
'Format decimal degrees with altitude'
| def format_decimal(self, altitude=None):
| coordinates = [str(self.latitude), str(self.longitude)]
if (altitude is None):
altitude = bool(self.altitude)
if (altitude is True):
if (not isinstance(altitude, string_compare)):
altitude = 'km'
coordinates.append(self.format_altitude(altitude))
return ', '.join(coordinates)
|
'Foamt altitude with unit'
| def format_altitude(self, unit='km'):
| return format_distance(self.altitude, unit=unit)
|
'Parse degrees minutes seconds including direction (N, S, E, W)'
| @classmethod
def parse_degrees(cls, degrees, arcminutes, arcseconds, direction=None):
| degrees = float(degrees)
negative = (degrees < 0)
arcminutes = float(arcminutes)
arcseconds = float(arcseconds)
if (arcminutes or arcseconds):
more = units.degrees(arcminutes=arcminutes, arcseconds=arcseconds)
if negative:
degrees -= more
else:
degrees += more
if (direction in [None, 'N', 'E']):
return degrees
elif (direction in ['S', 'W']):
return (- degrees)
else:
raise ValueError('Invalid direction! Should be one of [NSEW].')
|
'Parse altitude managing units conversion'
| @classmethod
def parse_altitude(cls, distance, unit):
| if (distance is not None):
distance = float(distance)
CONVERTERS = {'km': (lambda d: d), 'm': (lambda d: units.kilometers(meters=d)), 'mi': (lambda d: units.kilometers(miles=d)), 'ft': (lambda d: units.kilometers(feet=d)), 'nm': (lambda d: units.kilometers(nautical=d)), 'nmi': (lambda d: units.kilometers(nautical=d))}
try:
return CONVERTERS[unit](distance)
except KeyError:
raise NotImplementedError(('Bad distance unit specified, valid are: %r' % CONVERTERS.keys()))
else:
return distance
|
'Create and return a ``Point`` instance from a string containing
latitude and longitude, and optionally, altitude.
Latitude and longitude must be in degrees and may be in decimal form
or indicate arcminutes and arcseconds (labeled with Unicode prime and
double prime, ASCII quote and double quote or \'m\' and \'s\'). The degree
symbol is optional and may be included after the decimal places (in
decimal form) and before the arcminutes and arcseconds otherwise.
Coordinates given from south and west (indicated by S and W suffixes)
will be converted to north and east by switching their signs. If no
(or partial) cardinal directions are given, north and east are the
assumed directions. Latitude and longitude must be separated by at
least whitespace, a comma, or a semicolon (each with optional
surrounding whitespace).
Altitude, if supplied, must be a decimal number with given units.
The following unit abbrevations (case-insensitive) are supported:
- ``km`` (kilometers)
- ``m`` (meters)
- ``mi`` (miles)
- ``ft`` (feet)
- ``nm``, ``nmi`` (nautical miles)
Some example strings the will work include:
- 41.5;-81.0
- 41.5,-81.0
- 41.5 -81.0
- 41.5 N -81.0 W
- -41.5 S;81.0 E
- 23 26m 22s N 23 27m 30s E
- 23 26\' 22" N 23 27\' 30" E
- UT: N 39°20\' 0\'\' / W 74°35\' 0\'\''
| @classmethod
def from_string(cls, string):
| match = re.match(cls.POINT_PATTERN, re.sub("''", '"', string))
if match:
latitude_direction = None
if match.group('latitude_direction_front'):
latitude_direction = match.group('latitude_direction_front')
elif match.group('latitude_direction_back'):
latitude_direction = match.group('latitude_direction_back')
longitude_direction = None
if match.group('longitude_direction_front'):
longitude_direction = match.group('longitude_direction_front')
elif match.group('longitude_direction_back'):
longitude_direction = match.group('longitude_direction_back')
latitude = cls.parse_degrees((match.group('latitude_degrees') or 0.0), (match.group('latitude_arcminutes') or 0.0), (match.group('latitude_arcseconds') or 0.0), latitude_direction)
longitude = cls.parse_degrees((match.group('longitude_degrees') or 0.0), (match.group('longitude_arcminutes') or 0.0), (match.group('longitude_arcseconds') or 0.0), longitude_direction)
altitude = cls.parse_altitude(match.group('altitude_distance'), match.group('altitude_units'))
return cls(latitude, longitude, altitude)
else:
raise ValueError('Failed to create Point instance from string: unknown format.')
|
'Create and return a new ``Point`` instance from any iterable with 0 to
3 elements. The elements, if present, must be latitude, longitude,
and altitude, respectively.'
| @classmethod
def from_sequence(cls, seq):
| args = tuple(islice(seq, 4))
return cls(*args)
|
'Create and return a new ``Point`` instance from another ``Point``
instance.'
| @classmethod
def from_point(cls, point):
| return cls(point.latitude, point.longitude, point.altitude)
|
'Init the Parser'
| def __init__(self):
| self.main_parser = argparse.ArgumentParser()
self.add_args()
|
'Add new arguments'
| def add_args(self):
| self.main_parser.add_argument('-i', type=str, default='eth0', dest='iface', required=False, help='the interface to dump themaster runs on(default:eth0)')
self.main_parser.add_argument('-n', type=int, default=5, dest='ival', required=False, help='interval for printing stats (default:5)')
self.main_parser.add_argument('-I', type=bool, default=False, const=True, nargs='?', dest='only_ip', required=False, help='print unique IPs making new connections with SYN set')
|
'parses and returns the given arguments in a namespace object'
| def parse_args(self):
| return self.main_parser.parse_args()
|
'main loop for the packet-parser'
| def run(self):
| cap = pcapy.open_live(self.iface, 65536, 1, 0)
count = 0
l_time = None
while 1:
packet_data = {'ip': {}, 'tcp': {}}
(header, packet) = cap.next()
(eth_length, eth_protocol) = self.parse_ether(packet)
if (eth_protocol == 8):
(version_ihl, version, ihl, iph_length, ttl, protocol, s_addr, d_addr) = self.parse_ip(packet, eth_length)
packet_data['ip']['s_addr'] = s_addr
packet_data['ip']['d_addr'] = d_addr
if (protocol == 6):
(source_port, dest_port, flags, data) = self.parse_tcp(packet, iph_length, eth_length)
packet_data['tcp']['d_port'] = dest_port
packet_data['tcp']['s_port'] = source_port
packet_data['tcp']['flags'] = flags
packet_data['tcp']['data'] = data
(yield packet_data)
|
'parse ethernet_header and return size and protocol'
| def parse_ether(self, packet):
| eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH', eth_header)
eth_protocol = socket.ntohs(eth[2])
return (eth_length, eth_protocol)
|
'parse ip_header and return all ip data fields'
| def parse_ip(self, packet, eth_length):
| ip_header = packet[eth_length:(20 + eth_length)]
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = (version_ihl >> 4)
ihl = (version_ihl & 15)
iph_length = (ihl * 4)
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8])
d_addr = socket.inet_ntoa(iph[9])
return [version_ihl, version, ihl, iph_length, ttl, protocol, s_addr, d_addr]
|
'parse tcp_data and return source_port,
dest_port and actual packet data'
| def parse_tcp(self, packet, iph_length, eth_length):
| p_len = (iph_length + eth_length)
tcp_header = packet[p_len:(p_len + 20)]
tcph = unpack('!H HLLBBHHH', tcp_header)
source_port = tcph[0]
dest_port = tcph[1]
sequence = tcph[2]
acknowledgement = tcph[3]
doff_reserved = tcph[4]
tcph_length = (doff_reserved >> 4)
tcp_flags = tcph[5]
h_size = ((eth_length + iph_length) + (tcph_length * 4))
data_size = (len(packet) - h_size)
data = packet[h_size:]
return (source_port, dest_port, tcp_flags, data)
|
'Read the table of tcp connections & remove header'
| def proc_tcp(self):
| with open('/proc/net/tcp', 'r') as tcp_f:
content = tcp_f.readlines()
content.pop(0)
return content
|
'convert hex to dezimal'
| def hex2dec(self, hex_s):
| return str(int(hex_s, 16))
|
'convert into readable ip'
| def ip(self, hex_s):
| ip = [self.hex2dec(hex_s[6:8]), self.hex2dec(hex_s[4:6]), self.hex2dec(hex_s[2:4]), self.hex2dec(hex_s[0:2])]
return '.'.join(ip)
|
'create new list without empty entries'
| def remove_empty(self, array):
| return [x for x in array if (x != '')]
|
'hex_ip:hex_port to str_ip:str_port'
| def convert_ip_port(self, array):
| (host, port) = array.split(':')
return (self.ip(host), self.hex2dec(port))
|
'main loop for netstat'
| def run(self):
| while 1:
ips = {'ips/4505': {}, 'ips/4506': {}}
content = self.proc_tcp()
for line in content:
line_array = self.remove_empty(line.split(' '))
(l_host, l_port) = self.convert_ip_port(line_array[1])
(r_host, r_port) = self.convert_ip_port(line_array[2])
if (l_port == '4505'):
if (r_host not in ips['ips/4505']):
ips['ips/4505'][r_host] = 0
ips['ips/4505'][r_host] += 1
if (l_port == '4506'):
if (r_host not in ips['ips/4506']):
ips['ips/4506'][r_host] = 0
ips['ips/4506'][r_host] += 1
(yield (len(ips['ips/4505']), len(ips['ips/4506'])))
time.sleep(0.5)
|
'Test cli function'
| def test_cli(self):
| cmd_iter = self.client.cmd_cli('minion', 'test.ping')
for ret in cmd_iter:
self.assertTrue(ret['minion'])
cmd_iter = self.client.cmd_cli('minion', 'test.sleep', [6])
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert (num_ret > 0)
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'footest')
with salt.utils.files.fopen(key_file, 'a'):
pass
try:
cmd_iter = self.client.cmd_cli('footest', 'test.ping')
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert (num_ret == 0)
finally:
os.unlink(key_file)
|
'test cmd_iter'
| def test_iter(self):
| cmd_iter = self.client.cmd_iter('minion', 'test.ping')
for ret in cmd_iter:
self.assertTrue(ret['minion'])
|
'test cmd_iter_no_block'
| def test_iter_no_block(self):
| cmd_iter = self.client.cmd_iter_no_block('minion', 'test.ping')
for ret in cmd_iter:
if (ret is None):
continue
self.assertTrue(ret['minion'])
|
'test cmd_batch'
| def test_batch(self):
| cmd_batch = self.client.cmd_batch('minion', 'test.ping')
for ret in cmd_batch:
self.assertTrue(ret['minion'])
|
'test cmd_batch with raw option'
| def test_batch_raw(self):
| cmd_batch = self.client.cmd_batch('minion', 'test.ping', raw=True)
for ret in cmd_batch:
self.assertTrue(ret['data']['success'])
|
'test cmd_iter'
| def test_full_returns(self):
| ret = self.client.cmd_full_return('minion', 'test.ping')
self.assertIn('minion', ret)
self.assertEqual({'ret': True, 'success': True}, ret['minion'])
|
'Test return/messaging on a disconnected minion'
| def test_disconnected_return(self):
| test_ret = {'ret': 'Minion did not return. [No response]', 'out': 'no_return'}
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.files.fopen(key_file, 'a'):
pass
try:
cmd_iter = self.client.cmd_cli('disconnected', 'test.ping', show_timeout=True)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertEqual(ret['disconnected']['ret'], test_ret['ret'])
self.assertEqual(ret['disconnected']['out'], test_ret['out'])
self.assertEqual(num_ret, 1)
finally:
os.unlink(key_file)
|
'Test cli function'
| def test_cli(self):
| cmd_iter = self.client.cmd_cli('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'test cmd_iter'
| def test_iter(self):
| cmd_iter = self.client.cmd_iter('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'test cmd_iter_no_block'
| def test_iter_no_block(self):
| cmd_iter = self.client.cmd_iter_no_block('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
for ret in cmd_iter:
if (ret is None):
continue
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'test cmd_iter'
| def test_full_returns(self):
| ret = self.client.cmd_full_return('minion', 'test.arg', ['foo', 'bar', 'baz'], kwarg={'qux': 'quux'})
data = ret['minion']['ret']
self.assertEqual(data['args'], ['foo', 'bar', 'baz'])
self.assertEqual(data['kwargs']['qux'], 'quux')
|
'Test that kwargs end up on the client as the same type'
| def test_kwarg_type(self):
| terrible_yaml_string = 'foo: ""\n# \''
ret = self.client.cmd_full_return('minion', 'test.arg_type', ['a', 1], kwarg={'outer': {'a': terrible_yaml_string}, 'inner': 'value'})
data = ret['minion']['ret']
self.assertIn('str', data['args'][0])
self.assertIn('int', data['args'][1])
self.assertIn('dict', data['kwargs']['outer'])
self.assertIn('str', data['kwargs']['inner'])
|
'Configure an eauth user to test with'
| def setUp(self):
| self.runner = salt.runner.RunnerClient(self.get_config('client_config'))
|
'Test executing master_call with lowdata
The choice of using error.error for this is arbitrary and should be
changed to some mocked function that is more testing friendly.'
| def test_eauth(self):
| low = {'client': 'runner', 'fun': 'error.error'}
low.update(self.eauth_creds)
self.runner.master_call(**low)
|
'Test executing master_call with lowdata
The choice of using error.error for this is arbitrary and should be
changed to some mocked function that is more testing friendly.'
| def test_token(self):
| import salt.auth
auth = salt.auth.LoadAuth(self.get_config('client_config'))
token = auth.mk_token(self.eauth_creds)
self.runner.master_call(**{'client': 'runner', 'fun': 'error.error', 'token': token['token']})
|
'test.ping'
| def test_ping(self):
| self.assertTrue(self.run_function('test.ping'))
|
'test.fib'
| def test_fib(self):
| self.assertEqual(self.run_function('test.fib', ['20'])[0], 6765)
|
'Test the calculations'
| def test_count_runtimes(self):
| results = librato_return._calculate_runtimes(MOCK_RET_OBJ['return'])
self.assertEqual(results['num_failed_states'], 1)
self.assertEqual(results['num_passed_states'], 1)
self.assertEqual(results['runtime'], 7.29)
|
'Tests executing a simple batch command to help catch regressions'
| def test_batch_run(self):
| ret = "Executing run on ['sub_minion']"
cmd = self.run_salt("'*' test.echo 'batch testing' -b 50%")
self.assertIn(ret, cmd)
|
'Tests executing a simple batch command using a number division instead of
a percentage with full batch CLI call.'
| def test_batch_run_number(self):
| ret = "Executing run on ['minion', 'sub_minion']"
cmd = self.run_salt("'*' test.ping --batch-size 2")
self.assertIn(ret, cmd)
|
'Tests executing a batch command using a percentage divisor as well as grains
targeting.'
| def test_batch_run_grains_targeting(self):
| os_grain = ''
sub_min_ret = "Executing run on ['sub_minion']"
min_ret = "Executing run on ['minion']"
for item in self.run_salt('minion grains.get os'):
if (item != 'minion'):
os_grain = item
os_grain = os_grain.strip()
cmd = self.run_salt("-G 'os:{0}' -b 25% test.ping".format(os_grain))
self.assertIn(sub_min_ret, cmd)
self.assertIn(min_ret, cmd)
|
'Test that a failed state returns a non-zero exit code in batch mode'
| def test_batch_exit_code(self):
| cmd = self.run_salt(' "*" state.single test.fail_without_changes name=test_me -b 25%', with_retcode=True)
self.assertEqual(cmd[(-1)], 2)
|
'Test regular module work using SSHCase environment'
| def test_ssh_regular_module(self):
| expected = 'hello'
cmd = self.run_function('test.echo', arg=['hello'])
self.assertEqual(expected, cmd)
|
'Test custom module work using SSHCase environment'
| def test_ssh_custom_module(self):
| expected = 'hello'[::(-1)]
cmd = self.run_function('test.recho', arg=['hello'])
self.assertEqual(expected, cmd)
|
'Test sls with custom module work using SSHCase environment'
| def test_ssh_sls_with_custom_module(self):
| expected = {'module_|-regular-module_|-test.echo_|-run': 'hello', 'module_|-custom-module_|-test.recho_|-run': 'olleh'}
cmd = self.run_function('state.sls', arg=['custom_module'])
for key in cmd:
if ((not isinstance(cmd, dict)) or (not isinstance(cmd[key], dict))):
raise AssertionError('{0} is not a proper state return'.format(cmd))
elif (not cmd[key]['result']):
raise AssertionError(cmd[key]['comment'])
cmd_ret = cmd[key]['changes'].get('ret', None)
self.assertEqual(cmd_ret, expected[key])
|
'Tests running "salt -G \'os:<system-os>\' test.ping and minions both return True'
| def test_grains_targeting_os_running(self):
| test_ret = ['sub_minion:', ' True', 'minion:', ' True']
os_grain = ''
for item in self.run_salt('minion grains.get os'):
if (item != 'minion:'):
os_grain = item.strip()
ret = self.run_salt("-G 'os:{0}' test.ping".format(os_grain))
self.assertEqual(sorted(ret), sorted(test_ret))
|
'Tests return of each running test minion targeting with minion id grain'
| def test_grains_targeting_minion_id_running(self):
| minion = self.run_salt("-G 'id:minion' test.ping")
self.assertEqual(sorted(minion), sorted(['minion:', ' True']))
sub_minion = self.run_salt("-G 'id:sub_minion' test.ping")
self.assertEqual(sorted(sub_minion), sorted(['sub_minion:', ' True']))
|
'Tests return of minion using grains targeting on a disconnected minion.'
| def test_grains_targeting_disconnected(self):
| test_ret = 'Minion did not return. [No response]'
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'disconnected')
with salt.utils.files.fopen(key_file, 'a'):
pass
import logging
log = logging.getLogger(__name__)
try:
ret = ''
for item in self.run_salt("-t 1 -G 'id:disconnected' test.ping", timeout=40):
if (item != 'disconnected:'):
ret = item.strip()
self.assertEqual(ret, test_ret)
finally:
os.unlink(key_file)
|
'Test salt-ssh grains id work for localhost.'
| def test_grains_id(self):
| cmd = self.run_function('grains.get', ['id'])
self.assertEqual(cmd, 'localhost')
|
'Start a master and minion'
| def __enter__(self):
| salt_log_setup.setup_multiprocessing_logging_listener(self.master_opts)
self._enter_mockbin()
if (self.parser.options.transport == 'zeromq'):
self.start_zeromq_daemons()
elif (self.parser.options.transport == 'raet'):
self.start_raet_daemons()
elif (self.parser.options.transport == 'tcp'):
self.start_tcp_daemons()
self.minion_targets = set(['minion', 'sub_minion'])
self.pre_setup_minions()
self.setup_minions()
if getattr(self.parser.options, 'ssh', False):
self.prep_ssh()
if self.parser.options.sysinfo:
try:
print_header('~~~~~~~ Versions Report ', inline=True, width=getattr(self.parser.options, 'output_columns', PNUM))
except TypeError:
print_header('~~~~~~~ Versions Report ', inline=True)
print('\n'.join(salt.version.versions_report()))
try:
print_header('~~~~~~~ Minion Grains Information ', inline=True, width=getattr(self.parser.options, 'output_columns', PNUM))
except TypeError:
print_header('~~~~~~~ Minion Grains Information ', inline=True)
grains = self.client.cmd('minion', 'grains.items')
minion_opts = self.minion_opts.copy()
minion_opts['color'] = (self.parser.options.no_colors is False)
salt.output.display_output(grains, 'grains', minion_opts)
try:
print_header('=', sep='=', inline=True, width=getattr(self.parser.options, 'output_columns', PNUM))
except TypeError:
print_header('', sep='=', inline=True)
try:
return self
finally:
self.post_setup_minions()
|
'Fire up the daemons used for zeromq tests'
| def start_zeromq_daemons(self):
| self.log_server = ThreadedSocketServer(('localhost', SALT_LOG_PORT), SocketServerRequestHandler)
self.log_server_process = threading.Thread(target=self.log_server.serve_forever)
self.log_server_process.daemon = True
self.log_server_process.start()
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting salt-master ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.master_process = start_daemon(daemon_name='salt-master', daemon_id=self.master_opts['id'], daemon_log_prefix='salt-master/{}'.format(self.master_opts['id']), daemon_cli_script_name='master', daemon_config=self.master_opts, daemon_config_dir=RUNTIME_VARS.TMP_CONF_DIR, daemon_class=SaltMaster, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting salt-master ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting salt-master ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting salt-minion ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.minion_process = start_daemon(daemon_name='salt-minion', daemon_id=self.master_opts['id'], daemon_log_prefix='salt-minion/{}'.format(self.minion_opts['id']), daemon_cli_script_name='minion', daemon_config=self.minion_opts, daemon_config_dir=RUNTIME_VARS.TMP_CONF_DIR, daemon_class=SaltMinion, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting salt-minion ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting salt-minion ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting sub salt-minion ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.sub_minion_process = start_daemon(daemon_name='sub salt-minion', daemon_id=self.master_opts['id'], daemon_log_prefix='sub-salt-minion/{}'.format(self.sub_minion_opts['id']), daemon_cli_script_name='minion', daemon_config=self.sub_minion_opts, daemon_config_dir=RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, daemon_class=SaltMinion, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting sub salt-minion ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting sub salt-minion ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting syndic salt-master ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.smaster_process = start_daemon(daemon_name='salt-smaster', daemon_id=self.syndic_master_opts['id'], daemon_log_prefix='salt-smaster/{}'.format(self.syndic_master_opts['id']), daemon_cli_script_name='master', daemon_config=self.syndic_master_opts, daemon_config_dir=RUNTIME_VARS.TMP_SYNDIC_MASTER_CONF_DIR, daemon_class=SaltMaster, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting syndic salt-master ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting syndic salt-master ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting salt-syndic ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.syndic_process = start_daemon(daemon_name='salt-syndic', daemon_id=self.syndic_opts['id'], daemon_log_prefix='salt-syndic/{}'.format(self.syndic_opts['id']), daemon_cli_script_name='syndic', daemon_config=self.syndic_opts, daemon_config_dir=RUNTIME_VARS.TMP_SYNDIC_MINION_CONF_DIR, daemon_class=SaltSyndic, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting salt-syndic ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting salt-syndic ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
if self.parser.options.proxy:
try:
sys.stdout.write(' * {LIGHT_YELLOW}Starting salt-proxy ... {ENDC}'.format(**self.colors))
sys.stdout.flush()
self.proxy_process = start_daemon(daemon_name='salt-proxy', daemon_id=self.master_opts['id'], daemon_log_prefix='salt-proxy/{}'.format(self.proxy_opts['id']), daemon_cli_script_name='proxy', daemon_config=self.proxy_opts, daemon_config_dir=RUNTIME_VARS.TMP_CONF_DIR, daemon_class=SaltProxy, bin_dir_path=SCRIPT_DIR, fail_hard=True, start_timeout=30)
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_GREEN}Starting salt-proxy ... STARTED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
except (RuntimeWarning, RuntimeError):
sys.stdout.write('\r{0}\r'.format((' ' * getattr(self.parser.options, 'output_columns', PNUM))))
sys.stdout.write(' * {LIGHT_RED}Starting salt-proxy ... FAILED!\n{ENDC}'.format(**self.colors))
sys.stdout.flush()
|
'Fire up the raet daemons!'
| def start_raet_daemons(self):
| import salt.daemons.flo
self.master_process = self.start_daemon(salt.daemons.flo.IofloMaster, self.master_opts, 'start')
self.minion_process = self.start_daemon(salt.daemons.flo.IofloMinion, self.minion_opts, 'tune_in')
self.sub_minion_process = self.start_daemon(salt.daemons.flo.IofloMinion, self.sub_minion_opts, 'tune_in')
time.sleep(5)
|
'Generate keys and start an ssh daemon on an alternate port'
| def prep_ssh(self):
| sys.stdout.write(' * {LIGHT_GREEN}Starting {0} ... {ENDC}'.format('SSH server', **self.colors))
keygen = salt.utils.path.which('ssh-keygen')
sshd = salt.utils.path.which('sshd')
if (not (keygen and sshd)):
print('WARNING: Could not initialize SSH subsystem. Tests for salt-ssh may break!')
return
if (not os.path.exists(RUNTIME_VARS.TMP_CONF_DIR)):
os.makedirs(RUNTIME_VARS.TMP_CONF_DIR)
pub_key_test_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test.pub')
priv_key_test_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test')
if os.path.exists(pub_key_test_file):
os.remove(pub_key_test_file)
if os.path.exists(priv_key_test_file):
os.remove(priv_key_test_file)
keygen_process = subprocess.Popen([keygen, '-t', 'ecdsa', '-b', '521', '-C', '"$(whoami)@$(hostname)-$(date -I)"', '-f', 'key_test', '-P', ''], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=RUNTIME_VARS.TMP_CONF_DIR)
(_, keygen_err) = keygen_process.communicate()
if keygen_err:
print('ssh-keygen had errors: {0}'.format(salt.utils.stringutils.to_str(keygen_err)))
sshd_config_path = os.path.join(FILES, 'conf/_ssh/sshd_config')
shutil.copy(sshd_config_path, RUNTIME_VARS.TMP_CONF_DIR)
auth_key_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test.pub')
server_key_dir = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'server')
if (not os.path.exists(server_key_dir)):
os.makedirs(server_key_dir)
server_dsa_priv_key_file = os.path.join(server_key_dir, 'ssh_host_dsa_key')
server_dsa_pub_key_file = os.path.join(server_key_dir, 'ssh_host_dsa_key.pub')
server_ecdsa_priv_key_file = os.path.join(server_key_dir, 'ssh_host_ecdsa_key')
server_ecdsa_pub_key_file = os.path.join(server_key_dir, 'ssh_host_ecdsa_key.pub')
server_ed25519_priv_key_file = os.path.join(server_key_dir, 'ssh_host_ed25519_key')
server_ed25519_pub_key_file = os.path.join(server_key_dir, 'ssh_host.ed25519_key.pub')
for server_key_file in (server_dsa_priv_key_file, server_dsa_pub_key_file, server_ecdsa_priv_key_file, server_ecdsa_pub_key_file, server_ed25519_priv_key_file, server_ed25519_pub_key_file):
if os.path.exists(server_key_file):
os.remove(server_key_file)
keygen_process_dsa = subprocess.Popen([keygen, '-t', 'dsa', '-b', '1024', '-C', '"$(whoami)@$(hostname)-$(date -I)"', '-f', 'ssh_host_dsa_key', '-P', ''], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=server_key_dir)
(_, keygen_dsa_err) = keygen_process_dsa.communicate()
if keygen_dsa_err:
print('ssh-keygen had errors: {0}'.format(salt.utils.stringutils.to_str(keygen_dsa_err)))
keygen_process_ecdsa = subprocess.Popen([keygen, '-t', 'ecdsa', '-b', '521', '-C', '"$(whoami)@$(hostname)-$(date -I)"', '-f', 'ssh_host_ecdsa_key', '-P', ''], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=server_key_dir)
(_, keygen_escda_err) = keygen_process_ecdsa.communicate()
if keygen_escda_err:
print('ssh-keygen had errors: {0}'.format(salt.utils.stringutils.to_str(keygen_escda_err)))
keygen_process_ed25519 = subprocess.Popen([keygen, '-t', 'ed25519', '-b', '521', '-C', '"$(whoami)@$(hostname)-$(date -I)"', '-f', 'ssh_host_ed25519_key', '-P', ''], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=server_key_dir)
(_, keygen_ed25519_err) = keygen_process_ed25519.communicate()
if keygen_ed25519_err:
print('ssh-keygen had errors: {0}'.format(salt.utils.stringutils.to_str(keygen_ed25519_err)))
with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'sshd_config'), 'a') as ssh_config:
ssh_config.write('AuthorizedKeysFile {0}\n'.format(auth_key_file))
if (not keygen_dsa_err):
ssh_config.write('HostKey {0}\n'.format(server_dsa_priv_key_file))
if (not keygen_escda_err):
ssh_config.write('HostKey {0}\n'.format(server_ecdsa_priv_key_file))
if (not keygen_ed25519_err):
ssh_config.write('HostKey {0}\n'.format(server_ed25519_priv_key_file))
self.sshd_pidfile = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'sshd.pid')
self.sshd_process = subprocess.Popen([sshd, '-f', 'sshd_config', '-oPidFile={0}'.format(self.sshd_pidfile)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, cwd=RUNTIME_VARS.TMP_CONF_DIR)
(_, sshd_err) = self.sshd_process.communicate()
if sshd_err:
print('sshd had errors on startup: {0}'.format(salt.utils.stringutils.to_str(sshd_err)))
else:
os.environ['SSH_DAEMON_RUNNING'] = 'True'
roster_path = os.path.join(FILES, 'conf/_ssh/roster')
shutil.copy(roster_path, RUNTIME_VARS.TMP_CONF_DIR)
with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'roster'), 'a') as roster:
roster.write(' user: {0}\n'.format(RUNTIME_VARS.RUNNING_TESTS_USER))
roster.write(' priv: {0}/{1}'.format(RUNTIME_VARS.TMP_CONF_DIR, 'key_test'))
sys.stdout.write(' {LIGHT_GREEN}STARTED!\n{ENDC}'.format(**self.colors))
|
'Return a configuration for a master/minion/syndic.
Currently these roles are:
* master
* minion
* syndic
* syndic_master
* sub_minion
* proxy'
| @classmethod
def config(cls, role):
| return RUNTIME_VARS.RUNTIME_CONFIGS[role]
|
'Return a local client which will be used for example to ping and sync
the test minions.
This client is defined as a class attribute because its creation needs
to be deferred to a latter stage. If created it on `__enter__` like it
previously was, it would not receive the master events.'
| @property
def client(self):
| if ('runtime_client' not in RUNTIME_VARS.RUNTIME_CONFIGS):
RUNTIME_VARS.RUNTIME_CONFIGS['runtime_client'] = salt.client.get_local_client(mopts=self.master_opts)
return RUNTIME_VARS.RUNTIME_CONFIGS['runtime_client']
|
'Kill the minion and master processes'
| def __exit__(self, type, value, traceback):
| self.sub_minion_process.terminate()
self.minion_process.terminate()
if hasattr(self, 'proxy_process'):
self.proxy_process.terminate()
self.master_process.terminate()
try:
self.syndic_process.terminate()
except AttributeError:
pass
try:
self.smaster_process.terminate()
except AttributeError:
pass
self.log_server.server_close()
self.log_server.shutdown()
self._exit_mockbin()
self._exit_ssh()
self.log_server_process.join()
salt_log_setup.shutdown_multiprocessing_logging()
salt_log_setup.shutdown_multiprocessing_logging_listener(daemonizing=True)
|
'Clean out the tmp files'
| @classmethod
def clean(cls):
| def remove_readonly(func, path, excinfo):
os.chmod(path, stat.S_IRWXU)
func(path)
for dirname in (TMP, RUNTIME_VARS.TMP_STATE_TREE, RUNTIME_VARS.TMP_PRODENV_STATE_TREE):
if os.path.isdir(dirname):
shutil.rmtree(dirname, onerror=remove_readonly)
|
'Tests the return of json-formatted data'
| def test_output_json(self):
| ret = self.run_call('test.ping --out=json')
self.assertIn('{', ret)
self.assertIn('"local": true', ''.join(ret))
self.assertIn('}', ''.join(ret))
|
'Tests the return of nested-formatted data'
| def test_output_nested(self):
| expected = ['local:', ' True']
ret = self.run_call('test.ping --out=nested')
self.assertEqual(ret, expected)
|
'Tests the return of an out=quiet query'
| def test_output_quiet(self):
| expected = []
ret = self.run_call('test.ping --out=quiet')
self.assertEqual(ret, expected)
|
'Tests the return of pprint-formatted data'
| def test_output_pprint(self):
| expected = ["{'local': True}"]
ret = self.run_call('test.ping --out=pprint')
self.assertEqual(ret, expected)
|
'Tests the return of raw-formatted data'
| def test_output_raw(self):
| expected = ["{'local': True}"]
ret = self.run_call('test.ping --out=raw')
self.assertEqual(ret, expected)
|
'Tests the return of txt-formatted data'
| def test_output_txt(self):
| expected = ['local: True']
ret = self.run_call('test.ping --out=txt')
self.assertEqual(ret, expected)
|
'Tests the return of yaml-formatted data'
| def test_output_yaml(self):
| expected = ['local: true']
ret = self.run_call('test.ping --out=yaml')
self.assertEqual(ret, expected)
|
'Tests outputter reliability with utf8'
| def test_output_unicodebad(self):
| opts = salt.config.minion_config(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'minion'))
opts['output_file'] = os.path.join(RUNTIME_VARS.TMP, 'outputtest')
data = {'foo': {'result': False, 'aaa': 'azerzaer\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9', 'comment': u'\xe9\xe9\xe9\xe9\xe0\xe0\xe0\xe0'}}
try:
display_output(data, opts=opts)
except Exception:
trace = traceback.format_exc()
sentinel = object()
old_max_diff = getattr(self, 'maxDiff', sentinel)
try:
self.maxDiff = None
self.assertEqual(trace, '')
finally:
if (old_max_diff is sentinel):
delattr(self, 'maxDiff')
else:
self.maxDiff = old_max_diff
|
'Ensure correct exit status when the master is configured to run as an unknown user.'
| def test_exit_status_unknown_user(self):
| master = testprogram.TestDaemonSaltMaster(name='unknown_user', configs={'master': {'map': {'user': 'some_unknown_user_xyz'}}}, parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, 'EX_NOUSER', message='unknown user not on system', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr))
finally:
master.shutdown()
|
'Ensure correct exit status when an unknown argument is passed to salt-master.'
| def test_exit_status_unknown_argument(self):
| master = testprogram.TestDaemonSaltMaster(name='unknown_argument', parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d', '--unknown-argument'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, 'EX_USAGE', message='unknown argument', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr))
finally:
master.shutdown()
|
'Ensure correct exit status when salt-master starts correctly.'
| def test_exit_status_correct_usage(self):
| master = testprogram.TestDaemonSaltMaster(name='correct_usage', parent_dir=self._test_dir)
master.setup()
(stdout, stderr, status) = master.run(args=['-d'], catch_stderr=True, with_retcode=True)
try:
self.assert_exit_status(status, 'EX_OK', message='correct usage', stdout=stdout, stderr=tests.integration.utils.decode_byte_list(stderr))
finally:
master.shutdown(wait_for_orphans=3)
|
'test that pam auth mechanism works with a valid user'
| def test_pam_auth_valid_user(self):
| (password, hashed_pwd) = gen_password()
set_pw_cmd = "shadow.set_password {0} '{1}'".format(self.userA, (password if salt.utils.platform.is_darwin() else hashed_pwd))
self.run_call(set_pw_cmd)
cmd = '-a pam "*" test.ping --username {0} --password {1}'.format(self.userA, password)
resp = self.run_salt(cmd)
self.assertTrue(('minion:' in resp))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.