-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal_debugger.py
308 lines (261 loc) · 10.3 KB
/
local_debugger.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
# -*- coding: utf-8 -*-
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights
# Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
#
import argparse
import json
import socket
import os.path
import six
import re
import typing
if typing.TYPE_CHECKING:
from typing import Dict, Any, List, AnyStr, Tuple
if six.PY2:
import imp
else:
import importlib.util
HTTP_HEADER_DELIMITER = '\r\n'
HTTP_BODY_DELIMITER = '\r\n\r\n'
CONTENT_LENGTH = 'Content-Length'
if six.PY3:
HTTP_HEADER_DELIMITER = HTTP_HEADER_DELIMITER.encode('utf-8')
HTTP_BODY_DELIMITER = HTTP_BODY_DELIMITER.encode('utf-8')
CONTENT_LENGTH = CONTENT_LENGTH.encode('utf-8')
NUMBER_OF_UNACCEPTED_CONN = 0
CONTENT_LENGTH_REGEX = re.compile("Content-Length: (.*?)\r\n".encode('utf-8'))
def _validate_port(port_number):
# type: (int) -> None
"""
Validates the user provided port number.
Verifies port number is within the legal range
- [0, 65535]
:param port_number: Port Number where the socket
connection will be established.
:type port_number: int
:return: None
:raises: ValueError when port is not in legal range [0, 65535]
"""
if(port_number < 0 or port_number > 65535):
raise ValueError('Port out of legal range: {0}. The port number '
'should be in the range [0, 65535]'
.format(port_number))
if(port_number == 0):
print('The TCP server will listen on a port that is free. Check logs '
'to find out what port number is being used')
return None
def _validate_skillfile_exists(skill_entry_file):
# type: (str) -> None
"""
Validates the user provided skill file exists.
Verifies the skill file(responsible for initializing the skill builder
and managing handlers) exists in the path specified
:param skill_entry_file: Path of the skill file
:type skill_entry_file: str
:return: None
:raises: ValueError when file doesn't exist
"""
if not os.path.isfile(skill_entry_file):
raise ValueError("File not found: {0}".format(skill_entry_file))
return None
def _setup_and_validate_arguments():
# type: () -> argparse.Namespace
"""
Invokes fns to parse and validate arguments.
:param: None
:return: Parsed arguments
:rtype: argparse.Namespace
"""
parser = _parse_arguments()
args = parser.parse_args()
_validate_port(args.portNumber)
_validate_skillfile_exists(args.skillEntryFile)
return args
def _parse_arguments():
# type: () -> argparse.ArgumentParser
"""
Parses arguments(with help statments).
Parses user provided arguments - portNumber, skillEntryFile
and lambdaHandler name
:param: None
:return: Argument Parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--portNumber',
help='Port number to listen for incoming '
'skill requests',
default=0, type=int)
parser.add_argument('-f', '--skillEntryFile',
help='Location of the skill file where skill builder '
'and handlers are initialized', type=str)
parser.add_argument('-l', '--lambdaHandler',
help='Name of the lambda handler function',
default='handler', type=str)
return parser
def _get_request_envelope(data):
# type: (List[AnyStr]) -> Dict[str, str]
"""
Constructs the requestEnvelope
:param data: Incoming data on the socket connection captured in the
form of a list
:type skill_entry_file: List[str]
:return: Request body as a dictionary
:rtype: Dict[str, str]
"""
request_body = _combine_received_data(data).decode('utf-8')
print('Request envelope: {0}'.format(request_body))
return json.loads(request_body)
def _setup_socket():
# type: () -> socket.socket
"""
Setup socket to listen and respond to skill requests.
:param: None
:return: Socket for the local debugging.
:rtype: socket.socket
"""
local_debugger_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local_debugger_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', args.portNumber)
local_debugger_socket.bind(server_address)
print('Starting server on: {0}'.format(
local_debugger_socket.getsockname()))
return local_debugger_socket
def _initialize_skill_invoker():
# type: () -> Any
"""
Initialize skill invoker based on skill file path argument.
:param: None
:return: Module used to invoke the skill handler.
:rtype: Object
"""
if six.PY2:
skill_invoker = imp.load_source(
args.lambdaHandler, args.skillEntryFile)
else:
spec = importlib.util.spec_from_file_location(
args.lambdaHandler, args.skillEntryFile)
skill_invoker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(skill_invoker)
return skill_invoker
def _send_response(response, socket_connection):
# type: (str, socket.socket) -> None
"""
Sends http response to skill request.
:param reponse: Response envelope returned by the skill handler
:type reponse: str
:param socket_connection: Socket connection for sending skill response
:type socket_connection: socket.socket
:return: None
"""
print('Response envelope: {0}'.format(response))
socket_connection.send('HTTP/1.1 200 OK{0}Content-Type: application/json;'
'charset=UTF-8{0}Content-Length: {1}{2}{3}'.format(
HTTP_HEADER_DELIMITER.decode('utf-8'),
len(response),
HTTP_BODY_DELIMITER.decode(
'utf-8'), response).encode('utf-8'))
def _get_content_length_and_body(data, content_length):
# type(List[AnyStr], int) -> int, List[AnyStr], bool
"""
Gets the Content-Length value and start capturing request body.
Combines the data captured over the socket connection so far
and looks for Content-Length value and the start of request body
Following the HTTP request pattern as
HEADERS\r\n\r\nBody, the \r\n\r\n is used to extract the
body from the HTTP request. The original data List is overwritten
to start capturing just the request body
If both Content-Length and message body aren't discovered, the
original values are returned.
:param data: Data captured over socket connection
:type data: List[AnyStr]
:param content_length: Content-Length of the request body. Default is -1
:type content_length: int
:return content_length: Content-Length of the request body
:return data: Data captured over socket connection
:return content_length_unidentified: Boolean value whether Content-Length
has been identified. Defaults to True
:rtype: (int, List[AnyStr], bool)
"""
received_data = _combine_received_data(data)
content_length_unidentified = True
if (HTTP_BODY_DELIMITER in received_data and
CONTENT_LENGTH in received_data):
content_length = int(CONTENT_LENGTH_REGEX.findall(received_data)[0])
received_data = received_data.split(
HTTP_BODY_DELIMITER)[-1:][0]
content_length_unidentified = False
data = []
data.append(received_data)
return content_length, data, content_length_unidentified
def _combine_received_data(combined_data):
# type(List[AnyStr]) -> AnyStr
"""
Combines data captured over the socket connection to string or byte literal.
:param data: Data captured over socket connection
:type data: List[AnyStr]
:return combined_data: Combined string or byte literal
:rtype content_length: AnyStr
"""
if six.PY2:
combined_data = ''.join(combined_data)
else:
combined_data = b''.join(combined_data)
return combined_data
def _handle_skill_request(client_address, socket_connection, skill_invoker):
# type(Tuple, socket.socket, Any) -> None
"""
Receives data over the socket connection, invokes skill handler with request envelope and sends skill response
:param client_adress: Requestor address
:type client_adress: Tuple
:param socket_connection: Socket connection for receiving skill request
:type socket_connection: socket.socket
:param skill_invoker: Module used to invoke the skill handler.
:type skill_invoker: Object
:return: None
"""
print('Connection from {0}'.format(client_address))
content_length_unidentified = True
content_length = -1
data = []
while (content_length_unidentified or
len(_combine_received_data(data)) < content_length):
data.append(socket_connection.recv(16))
if content_length_unidentified:
content_length, data, content_length_unidentified = (
_get_content_length_and_body(data, content_length))
_send_response(json.dumps(getattr(skill_invoker, args.lambdaHandler)(
_get_request_envelope(data), None)), socket_connection)
def main():
try:
local_debugger_socket = _setup_socket()
# NUMBER_OF_UNACCEPTED_CONN is set to 0. The socket will
# accept any backlog connection requests.
local_debugger_socket.listen(NUMBER_OF_UNACCEPTED_CONN)
skill_invoker = _initialize_skill_invoker()
while True:
print('Waiting for a socket connection')
socket_connection, client_address = local_debugger_socket.accept()
try:
_handle_skill_request(client_address,
socket_connection, skill_invoker)
finally:
socket_connection.close()
finally:
local_debugger_socket.close()
if __name__ == '__main__':
args = _setup_and_validate_arguments()
main()