-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.py
278 lines (243 loc) · 9.53 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""Contains various data processing, parsing, or conversion utilities"""
import os
import json
import logging
import requests
import contextlib
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from requests.compat import urljoin
from requests.utils import prepend_scheme_if_needed
log = logging.getLogger(__name__)
class WebRequestError(ValueError):
pass
class WebRequest(object):
"""Utilities for making HTTP requests"""
@staticmethod
def request_get(webapp,
route,
data_dict=None,
scheme='',
header_dict={}):
"""
:param webapp: web app address. If the address contains
schema information, then the schema argument should be None.
Port, if any, is assumed to already be appended to webapp.
:param route: web application route
:param data_dict: dict of url parameters if any
:param scheme: web address scheme. If the address contains
schema information, then this argument is ignored.
:param header_dict: dict of header for request. Default: None.
:return: the HTTP response object
:raises WebRequestError if HTTP status is not 200
"""
webapp_url = prepend_scheme_if_needed(webapp, scheme)
url = urljoin(webapp_url, route)
req = requests.get(url, params=data_dict, headers=header_dict)
log.debug("HTTP get " + str(req.url))
if req.status_code != 200:
raise WebRequestError("Status code: " + str(req.status_code) +
", msg: " + req.text)
return req
def __init__(self, webapp):
self.webapp = webapp
def get(self, route, data_dict=None, scheme=None):
"""
:param route: web application route
:param data_dict: dict of url parameters if any
:param scheme: web address scheme. If the address contains
schema information, then this argument must be None.
:return: the response contents
:raises WebRequestError if HTTP status is not 200
"""
return WebRequest.request_get(self.webapp, route, data_dict, scheme)
class XmlParserError(Exception):
pass
class XmlParser(object):
"""
Utilities for parsing XML data
"""
@staticmethod
def parse_file(file_path):
"""
:param file_path: absolute path to an XML file
:return: a parsed XML object
:raises XmlParserError if file not found or
if XML cannot be parsed.
"""
try:
return minidom.parse(file_path)
except IOError as e:
raise XmlParserError(e)
except ExpatError as e:
raise XmlParserError(e)
@staticmethod
def parse_string(data):
"""
:param data: XML data as str
:return: a parsed XML object
:raises XmlParserError if XML cannot be parsed.
"""
try:
return minidom.parseString(data)
except TypeError as e:
raise XmlParserError(e)
except ExpatError as e:
raise XmlParserError(e)
@staticmethod
def map_element_data(xml_parsed, tag_name):
"""
:param xml_parsed: a parsed XML object
:param tag_name: (str) an XML tag name
:return: the data in the first child for all
elements matching a given tag name
"""
return map(lambda e: e.childNodes[0].data,
xml_parsed.getElementsByTagName(tag_name))
@staticmethod
def get_element_data(xml_parsed, tag_name):
"""
:param xml_parsed: a parsed XML object
:param tag_name: (str) an XML tag name
:return: the data in the first child for the first
element matching a given tag name
"""
return xml_parsed.getElementsByTagName(tag_name)[0].firstChild.data
class InvalidSize(Exception):
ERROR_STR = "Size must be specified as bytes (b), " \
"kibibytes (k), mebibytes (m), gibibytes (g), " \
"tebibytes (t), or pebibytes(p). " \
"E.g. 50b, 100kb, or 250mb."
class Util(object):
"""
Utilities here may be available in other packages (such as 'humanfriendly'
and 'humanize') but these are tailored for this package, and also avoid the
non-essential requirements.
"""
@staticmethod
def ratio(a, b):
"""
:param a: a number
:param b: a number
:return: the ratio of two numbers. If denominator is
equal to 0, then return INFINITY * numerator.
"""
if b == 0:
return float('inf') * a
return a / b
@staticmethod
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""
TODO: use Python 3's implementation once we've moved over
:param a: a number
:param b: a number
:param rel_tol: relative tolerance (default: 1e-09)
:param abs_tol: absolute tolerance (default: 0.0)
:return: true iff the absolute difference between the given
two numbers is within prescribed tolerance. False otherwise.
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
@staticmethod
def format_size(num_bytes, units=""):
"""
This function formats sizes in bytes, kibibytes (k), mebibytes (m),
gibibytes (g), tebibytes (t), or pebibytes(p). The format itself:
a. contains only integral values,
b. preserves, where possible, four significant figures
to account for rounding errors, and
c. converts to a byte string format that Spark finds
readable. See Apache Spark's
src/main/java/org/apache/spark/network/util/JavaUtils.java#L276
Note that, in case of float values, the function doesn't round to avoid
going out of some arbitrary min-max bounds.
The choice of units in ('b', 'k', 'm', 'g', 't', 'p') instead of
('b', 'kb', 'mb', 'gb', 'tb', 'pb') was constrained by by JVM's format
for heap size arguments (Xms and Xmx).
Some examples:
> format_size(0)
'0b'
> format_size(5)
'5b'
> format_size(1024)
'1kb'
> format_size(10240)
'10kb'
> format_size(1024 ** 3 * 4)
'4gb'
> format_size(int(1024 ** 3 * 4.12))
'4218mb'
:param num_bytes: a :class:`int` representing the number of bytes
:param units: units to express the number bytes in. Must be a value
in the set ('b', 'k', 'm', 'g', 't', 'p'), and defaults
to an empty string allowing the function to choose an appropriate
representation. The given unit may be ignored if it results in
'significant' rounding error.
:return: a human-readable, :class:`str` representation of the
input number of bytes
"""
if not isinstance(num_bytes, int):
raise InvalidSize("Input bytes must be integral")
num = num_bytes
for x in ['b', 'k', 'm', 'g', 't']:
if x == units or num < 1024 or (num != int(num) and num <= 9999):
return "%d%s" % (num, x)
num /= 1024.0
return "%d%s" % (num, 'p')
@staticmethod
def parse_size(mem_str):
"""
TODO implementing this would help remove dependency on
the 'humanfriendly' package.
:param mem_str: a `str` expressing a memory size.
Size must be specified as bytes (b), kibibytes (k),
mebibytes (m), gibibytes (g), tebibytes (t), or pebibytes(p).
E.g. 50b, 100kb, or 250mb.
:return: the number of bytes represented as an int
"""
raise NotImplementedError
class TestUtil(object):
"""
Note: the JAR used here is a slim, unshaded file, and
so should not be used for full functionality.
"""
JAR_NAME = "sort-0.1-all.jar"
@staticmethod
@contextlib.contextmanager
def modified_environ(*remove, **update):
"""
Temporarily updates the ``os.environ`` dictionary in-place.
The ``os.environ`` dictionary is updated in-place so that
the modification is sure to work in all situations.
This function is cribbed from:
https://github.com/laurent-laporte-pro/stackoverflow-q2059482
:param remove: Environment variables to remove.
:param update: Dictionary of environment variables and values
to add/update.
"""
env = os.environ
update = update or {}
remove = remove or []
# List of environment variables being updated or removed.
stomped = (set(update.keys()) | set(remove)) & set(env.keys())
# Environment variables and values to restore on exit.
update_after = {k: env[k] for k in stomped}
# Environment variables and values to remove on exit.
remove_after = frozenset(k for k in update if k not in env)
try:
env.update(update)
[env.pop(k, None) for k in remove]
yield
finally:
env.update(update_after)
[env.pop(k) for k in remove_after]
@staticmethod
def yarn_api_helper(
yarn_dir, mocker, json_file, proto, addr, port, route):
headers = {"content-type": "application/json"}
info_resp_path = os.path.join(yarn_dir, json_file)
with open(info_resp_path) as json_file:
json_data = json.load(json_file)
base_url = proto + "://" + addr + ":" + port
req_url = urljoin(base_url, route)
mocker.get(req_url, json=json_data, headers=headers)
return json_data