- Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathnetwork_request.py
416 lines (333 loc) · 12.4 KB
/
network_request.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wrapper script which makes a network request.
Basic Usage: network_request.py post
--url <url>
--header <header> (optional, support multiple)
--body <body> (optional)
--timeout <secs> (optional)
--verbose (optional)
"""
importargparse
importinspect
importlogging
importsocket
importsys
# pylint: disable=g-import-not-at-top
# pylint: disable=g-importing-member
try:
fromsix.moves.http_clientimportHTTPSConnection
fromsix.moves.http_clientimportHTTPConnection
fromsix.moves.http_clientimportHTTPException
exceptImportError:
fromhttp.clientimportHTTPSConnection
fromhttp.clientimportHTTPConnection
fromhttp.clientimportHTTPException
try:
fromsix.moves.urllib.parseimporturlparse
exceptImportError:
fromurllib.parseimporturlparse
# pylint: enable=g-import-not-at-top
# pylint: enable=g-importing-member
# Set up logger as soon as possible
formatter=logging.Formatter('[%(levelname)s] %(message)s')
handler=logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger=logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Custom exit codes for known issues.
# System exit codes in python are valid from 0 - 256, so we will map some common
# ones here to understand successes and failures.
# Uses lower ints to not collide w/ HTTP status codes that the script may return
EXIT_CODE_SUCCESS=0
EXIT_CODE_SYS_ERROR=1
EXIT_CODE_INVALID_REQUEST_VALUES=2
EXIT_CODE_GENERIC_HTTPLIB_ERROR=3
EXIT_CODE_HTTP_TIMEOUT=4
EXIT_CODE_HTTP_REDIRECT_ERROR=5
EXIT_CODE_HTTP_NOT_FOUND_ERROR=6
EXIT_CODE_HTTP_SERVER_ERROR=7
EXIT_CODE_HTTP_UNKNOWN_ERROR=8
MAX_EXIT_CODE=8
# All used http verbs
POST='POST'
defunwrap_kwarg_namespace(func):
"""Transform a Namespace object from argparse into proper args and kwargs.
For a function that will be delegated to from argparse, inspect all of the
argments and extract them from the Namespace object.
Args:
func: the function that we are wrapping to modify behavior
Returns:
a new function that unwraps all of the arguments in a namespace and then
delegates to the passed function with those args.
"""
# When we move to python 3, getfullargspec so that we can tell the
# difference between args and kwargs -- then this could be used for functions
# that have both args and kwargs
if'getfullargspec'indir(inspect):
argspec=inspect.getfullargspec(func)
else:
argspec=inspect.getargspec(func) # Python 2 compatibility.
defwrapped(argparse_namespace=None, **kwargs):
"""Take a Namespace object and map it to kwargs.
Inspect the argspec of the passed function. Loop over all the args that
are present in the function and try to map them by name to arguments in the
namespace. For keyword arguments, we do not require that they be present
in the Namespace.
Args:
argparse_namespace: an arparse.Namespace object, the result of calling
argparse.ArgumentParser().parse_args()
**kwargs: keyword arguments that may be passed to the original function
Returns:
The return of the wrapped function from the parent.
Raises:
ValueError in the event that an argument is passed to the cli that is not
in the set of named kwargs
"""
ifnotargparse_namespace:
returnfunc(**kwargs)
reserved_namespace_keywords= ['func']
new_kwargs= {}
args=argspec.argsor []
forarg_nameinargs:
passed_value=getattr(argparse_namespace, arg_name, None)
ifpassed_valueisnotNone:
new_kwargs[arg_name] =passed_value
fornamespace_keyinvars(argparse_namespace).keys():
# ignore namespace keywords that have been set not passed in via cli
ifnamespace_keyinreserved_namespace_keywords:
continue
# make sure that we haven't passed something we should be processing
ifnamespace_keynotinargs:
raiseValueError('CLI argument "{}" does not match any argument in '
'function {}'.format(namespace_key, func.__name__))
returnfunc(**new_kwargs)
wrapped.__name__=func.__name__
returnwrapped
classNetworkRequest(object):
"""A container for an network request object.
This class holds on to all of the attributes necessary for making a
network request via httplib.
"""
def__init__(self, url, method, headers, body, timeout):
self.url=url.lower()
self.parsed_url=urlparse(self.url)
self.method=method
self.headers=headers
self.body=body
self.timeout=timeout
self.is_secure_connection=self.is_secure_connection()
defexecute_request(self):
""""Execute the request, and get a response.
Returns:
an HttpResponse object from httplib
"""
ifself.is_secure_connection:
conn=HTTPSConnection(self.get_hostname(), timeout=self.timeout)
else:
conn=HTTPConnection(self.get_hostname(), timeout=self.timeout)
conn.request(self.method, self.url, self.body, self.headers)
response=conn.getresponse()
returnresponse
defget_hostname(self):
"""Return the hostname for the url."""
returnself.parsed_url.netloc
defis_secure_connection(self):
"""Checks for a secure connection of https.
Returns:
True if the scheme is "https"; False if "http"
Raises:
ValueError when the scheme does not match http or https
"""
scheme=self.parsed_url.scheme
ifscheme=='http':
returnFalse
elifscheme=='https':
returnTrue
else:
raiseValueError('The url scheme is not "http" nor "https"'
': {}'.format(scheme))
defparse_colon_delimited_options(option_args):
"""Parses a key value from a string.
Args:
option_args: Key value string delimited by a color, ex: ("key:value")
Returns:
Return an array with the key as the first element and value as the second
Raises:
ValueError: If the key value option is not formatted correctly
"""
options= {}
ifnotoption_args:
returnoptions
forsingle_arginoption_args:
values=single_arg.split(':')
iflen(values) !=2:
raiseValueError('An option arg must be a single key/value pair '
'delimited by a colon - ex: "thing_key:thing_value"')
key=values[0].strip()
value=values[1].strip()
options[key] =value
returnoptions
defmake_request(request):
"""Makes a synchronous network request and return the HTTP status code.
Args:
request: a well formulated request object
Returns:
The HTTP status code of the network request.
'1' maps to invalid request headers.
"""
logger.info('Sending network request -')
logger.info('\tUrl: %s', request.url)
logger.debug('\tMethod: %s', request.method)
logger.debug('\tHeaders: %s', request.headers)
logger.debug('\tBody: %s', request.body)
try:
response=request.execute_request()
exceptsocket.timeout:
logger.exception(
'Timed out post request to %s in %d seconds for request body: %s',
request.url, request.timeout, request.body)
returnEXIT_CODE_HTTP_TIMEOUT
except (HTTPException, socket.error):
logger.exception(
'Encountered generic exception in posting to %s with request body %s',
request.url, request.body)
returnEXIT_CODE_GENERIC_HTTPLIB_ERROR
status=response.status
headers=response.getheaders()
logger.info('Received Network response -')
logger.info('\tStatus code: %d', status)
logger.debug('\tResponse headers: %s', headers)
ifstatus<200orstatus>299:
logger.error('Request (%s) failed with status code %d\n', request.url,
status)
# If we wanted this script to support get, we need to
# figure out what mechanism we intend for capturing the response
returnstatus
@unwrap_kwarg_namespace
defpost(url=None, header=None, body=None, timeout=5, verbose=False):
"""Sends a post request.
Args:
url: The url of the request
header: A list of headers for the request
body: The body for the request
timeout: Timeout in seconds for the request
verbose: Should debug logs be displayed
Returns:
Return an array with the key as the first element and value as the second
"""
ifverbose:
handler.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
try:
logger.info('Parsing headers: %s', header)
headers=parse_colon_delimited_options(header)
exceptValueError:
logging.exception('Could not parse the parameters with "--header": %s',
header)
returnEXIT_CODE_INVALID_REQUEST_VALUES
try:
request=NetworkRequest(url, POST, headers, body, float(timeout))
exceptValueError:
logger.exception('Invalid request values passed into the script.')
returnEXIT_CODE_INVALID_REQUEST_VALUES
status=make_request(request)
# View exit code after running to get the http status code: 'echo $?'
returnstatus
defget_argsparser():
"""Returns the argument parser.
Returns:
Argument parser for the script.
"""
parser=argparse.ArgumentParser(
description='The script takes in the arguments of a network request. '
'The network request is sent and the http status code will be'
'returned as the exit code.')
subparsers=parser.add_subparsers(help='Commands:')
post_parser=subparsers.add_parser(
post.__name__, help='{} help'.format(post.__name__))
post_parser.add_argument(
'--url',
help='Request url. Ex: https://www.google.com/somePath/',
required=True,
dest='url')
post_parser.add_argument(
'--header',
help='Request headers as a space delimited list of key '
'value pairs. Ex: "key1:value1 key2:value2"',
action='append',
required=False,
dest='header')
post_parser.add_argument(
'--body',
help='The body of the network request',
required=True,
dest='body')
post_parser.add_argument(
'--timeout',
help='The timeout in seconds',
default=10.0,
required=False,
dest='timeout')
post_parser.add_argument(
'--verbose',
help='Should verbose logging be outputted',
action='store_true',
default=False,
required=False,
dest='verbose')
post_parser.set_defaults(func=post)
returnparser
defmap_http_status_to_exit_code(status_code):
"""Map an http status code to the appropriate exit code.
Exit codes in python are valid from 0-256, so we want to map these to
predictable exit codes within range.
Args:
status_code: the input status code that was output from the network call
function
Returns:
One of our valid exit codes declared at the top of the file or a generic
unknown error code
"""
ifstatus_code<=MAX_EXIT_CODE:
returnstatus_code
ifstatus_code>199andstatus_code<300:
returnEXIT_CODE_SUCCESS
ifstatus_code==302:
returnEXIT_CODE_HTTP_REDIRECT_ERROR
ifstatus_code==404:
returnEXIT_CODE_HTTP_NOT_FOUND_ERROR
ifstatus_code>499:
returnEXIT_CODE_HTTP_SERVER_ERROR
returnEXIT_CODE_HTTP_UNKNOWN_ERROR
defmain():
"""Main function to run the program.
Parse system arguments and delegate to the appropriate function.
Returns:
A status code - either an http status code or a custom error code
"""
parser=get_argsparser()
subparser_action=parser.parse_args()
try:
returnsubparser_action.func(subparser_action)
exceptValueError:
logger.exception('Invalid arguments passed.')
parser.print_help(sys.stderr)
returnEXIT_CODE_INVALID_REQUEST_VALUES
returnEXIT_CODE_GENERIC_HTTPLIB_ERROR
if__name__=='__main__':
exit_code=map_http_status_to_exit_code(main())
sys.exit(exit_code)