parsers.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. # Copyright 2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. """Response parsers for the various protocol types.
  14. The module contains classes that can take an HTTP response, and given
  15. an output shape, parse the response into a dict according to the
  16. rules in the output shape.
  17. There are many similarities amongst the different protocols with regard
  18. to response parsing, and the code is structured in a way to avoid
  19. code duplication when possible. The diagram below is a diagram
  20. showing the inheritance hierarchy of the response classes.
  21. ::
  22. +--------------+
  23. |ResponseParser|
  24. +--------------+
  25. ^ ^ ^
  26. +--------------------+ | +-------------------+
  27. | | |
  28. +----------+----------+ +------+-------+ +-------+------+
  29. |BaseXMLResponseParser| |BaseRestParser| |BaseJSONParser|
  30. +---------------------+ +--------------+ +--------------+
  31. ^ ^ ^ ^ ^ ^
  32. | | | | | |
  33. | | | | | |
  34. | ++----------+-+ +-+-----------++ |
  35. | |RestXMLParser| |RestJSONParser| |
  36. +-----+-----+ +-------------+ +--------------+ +----+-----+
  37. |QueryParser| |JSONParser|
  38. +-----------+ +----------+
  39. The diagram above shows that there is a base class, ``ResponseParser`` that
  40. contains logic that is similar amongst all the different protocols (``query``,
  41. ``json``, ``rest-json``, ``rest-xml``). Amongst the various services there
  42. is shared logic that can be grouped several ways:
  43. * The ``query`` and ``rest-xml`` both have XML bodies that are parsed in the
  44. same way.
  45. * The ``json`` and ``rest-json`` protocols both have JSON bodies that are
  46. parsed in the same way.
  47. * The ``rest-json`` and ``rest-xml`` protocols have additional attributes
  48. besides body parameters that are parsed the same (headers, query string,
  49. status code).
  50. This is reflected in the class diagram above. The ``BaseXMLResponseParser``
  51. and the BaseJSONParser contain logic for parsing the XML/JSON body,
  52. and the BaseRestParser contains logic for parsing out attributes that
  53. come from other parts of the HTTP response. Classes like the
  54. ``RestXMLParser`` inherit from the ``BaseXMLResponseParser`` to get the
  55. XML body parsing logic and the ``BaseRestParser`` to get the HTTP
  56. header/status code/query string parsing.
  57. Return Values
  58. =============
  59. Each call to ``parse()`` returns a dict has this form::
  60. Standard Response
  61. {
  62. "ResponseMetadata": {"RequestId": <requestid>}
  63. <response keys>
  64. }
  65. Error response
  66. {
  67. "ResponseMetadata": {"RequestId": <requestid>}
  68. "Error": {
  69. "Code": <string>,
  70. "Message": <string>,
  71. "Type": <string>,
  72. <additional keys>
  73. }
  74. }
  75. """
  76. import re
  77. import base64
  78. import json
  79. import xml.etree.cElementTree
  80. import logging
  81. from kscore.compat import six, XMLParseError
  82. from kscore.utils import parse_timestamp, merge_dicts
  83. LOG = logging.getLogger(__name__)
  84. DEFAULT_TIMESTAMP_PARSER = parse_timestamp
  85. class ResponseParserFactory(object):
  86. def __init__(self):
  87. self._defaults = {}
  88. def set_parser_defaults(self, **kwargs):
  89. """Set default arguments when a parser instance is created.
  90. You can specify any kwargs that are allowed by a ResponseParser
  91. class. There are currently two arguments:
  92. * timestamp_parser - A callable that can parse a timetsamp string
  93. * blob_parser - A callable that can parse a blob type
  94. """
  95. self._defaults.update(kwargs)
  96. def create_parser(self, protocol_name):
  97. parser_cls = PROTOCOL_PARSERS[protocol_name]
  98. return parser_cls(**self._defaults)
  99. def create_parser(protocol):
  100. return ResponseParserFactory().create_parser(protocol)
  101. def _text_content(func):
  102. # This decorator hides the difference between
  103. # an XML node with text or a plain string. It's used
  104. # to ensure that scalar processing operates only on text
  105. # strings, which allows the same scalar handlers to be used
  106. # for XML nodes from the body and HTTP headers.
  107. def _get_text_content(self, shape, node_or_string):
  108. if hasattr(node_or_string, 'text'):
  109. text = node_or_string.text
  110. if text is None:
  111. # If an XML node is empty <foo></foo>,
  112. # we want to parse that as an empty string,
  113. # not as a null/None value.
  114. text = ''
  115. else:
  116. text = node_or_string
  117. return func(self, shape, text)
  118. return _get_text_content
  119. class ResponseParserError(Exception):
  120. pass
  121. class ResponseParser(object):
  122. """Base class for response parsing.
  123. This class represents the interface that all ResponseParsers for the
  124. various protocols must implement.
  125. This class will take an HTTP response and a model shape and parse the
  126. HTTP response into a dictionary.
  127. There is a single public method exposed: ``parse``. See the ``parse``
  128. docstring for more info.
  129. """
  130. DEFAULT_ENCODING = 'utf-8'
  131. def __init__(self, timestamp_parser=None, blob_parser=None):
  132. if timestamp_parser is None:
  133. timestamp_parser = DEFAULT_TIMESTAMP_PARSER
  134. self._timestamp_parser = timestamp_parser
  135. if blob_parser is None:
  136. blob_parser = self._default_blob_parser
  137. self._blob_parser = blob_parser
  138. def _default_blob_parser(self, value):
  139. # Blobs are always returned as bytes type (this matters on python3).
  140. # We don't decode this to a str because it's entirely possible that the
  141. # blob contains binary data that actually can't be decoded.
  142. return base64.b64decode(value)
  143. def parse(self, response, shape):
  144. """Parse the HTTP response given a shape.
  145. :param response: The HTTP response dictionary. This is a dictionary
  146. that represents the HTTP request. The dictionary must have the
  147. following keys, ``body``, ``headers``, and ``status_code``.
  148. :param shape: The model shape describing the expected output.
  149. :return: Returns a dictionary representing the parsed response
  150. described by the model. In addition to the shape described from
  151. the model, each response will also have a ``ResponseMetadata``
  152. which contains metadata about the response, which contains at least
  153. two keys containing ``RequestId`` and ``HTTPStatusCode``. Some
  154. responses may populate additional keys, but ``RequestId`` will
  155. always be present.
  156. """
  157. LOG.debug('Response headers: %s', response['headers'])
  158. LOG.debug('Response body:\n%s', response['body'])
  159. if response['status_code'] >= 301:
  160. if self._is_generic_error_response(response):
  161. parsed = self._do_generic_error_parse(response)
  162. else:
  163. parsed = self._do_error_parse(response, shape)
  164. else:
  165. parsed = self._do_parse(response, shape)
  166. # Inject HTTPStatusCode key in the response metadata if the
  167. # response metadata exists.
  168. if isinstance(parsed, dict) and 'ResponseMetadata' in parsed:
  169. parsed['ResponseMetadata']['HTTPStatusCode'] = (
  170. response['status_code'])
  171. return parsed
  172. def _is_generic_error_response(self, response):
  173. # There are times when a service will respond with a generic
  174. # error response such as:
  175. # '<html><body><b>Http/1.1 Service Unavailable</b></body></html>'
  176. #
  177. # This can also happen if you're going through a proxy.
  178. # In this case the protocol specific _do_error_parse will either
  179. # fail to parse the response (in the best case) or silently succeed
  180. # and treat the HTML above as an XML response and return
  181. # non sensical parsed data.
  182. # To prevent this case from happening we first need to check
  183. # whether or not this response looks like the generic response.
  184. if response['status_code'] >= 500:
  185. body = response['body'].strip()
  186. return body.startswith(b'<html>') or not body
  187. def _do_generic_error_parse(self, response):
  188. # There's not really much we can do when we get a generic
  189. # html response.
  190. LOG.debug("Received a non protocol specific error response from the "
  191. "service, unable to populate error code and message.")
  192. return {
  193. 'Error': {'Code': str(response['status_code']),
  194. 'Message': six.moves.http_client.responses.get(
  195. response['status_code'], '')},
  196. 'ResponseMetadata': {},
  197. }
  198. def _do_parse(self, response, shape):
  199. raise NotImplementedError("%s._do_parse" % self.__class__.__name__)
  200. def _do_error_parse(self, response, shape):
  201. raise NotImplementedError(
  202. "%s._do_error_parse" % self.__class__.__name__)
  203. def _parse_shape(self, shape, node):
  204. handler = getattr(self, '_handle_%s' % shape.type_name,
  205. self._default_handle)
  206. return handler(shape, node)
  207. def _handle_list(self, shape, node):
  208. # Enough implementations share list serialization that it's moved
  209. # up here in the base class.
  210. parsed = []
  211. member_shape = shape.member
  212. for item in node:
  213. parsed.append(self._parse_shape(member_shape, item))
  214. return parsed
  215. def _default_handle(self, shape, value):
  216. return value
  217. class BaseXMLResponseParser(ResponseParser):
  218. def __init__(self, timestamp_parser=None, blob_parser=None):
  219. super(BaseXMLResponseParser, self).__init__(timestamp_parser,
  220. blob_parser)
  221. self._namespace_re = re.compile('{.*}')
  222. def _handle_map(self, shape, node):
  223. parsed = {}
  224. key_shape = shape.key
  225. value_shape = shape.value
  226. key_location_name = key_shape.serialization.get('name') or 'key'
  227. value_location_name = value_shape.serialization.get('name') or 'value'
  228. if shape.serialization.get('flattened') and not isinstance(node, list):
  229. node = [node]
  230. for keyval_node in node:
  231. for single_pair in keyval_node:
  232. # Within each <entry> there's a <key> and a <value>
  233. tag_name = self._node_tag(single_pair)
  234. if tag_name == key_location_name:
  235. key_name = self._parse_shape(key_shape, single_pair)
  236. elif tag_name == value_location_name:
  237. val_name = self._parse_shape(value_shape, single_pair)
  238. else:
  239. raise ResponseParserError("Unknown tag: %s" % tag_name)
  240. parsed[key_name] = val_name
  241. return parsed
  242. def _node_tag(self, node):
  243. return self._namespace_re.sub('', node.tag)
  244. def _handle_list(self, shape, node):
  245. # When we use _build_name_to_xml_node, repeated elements are aggregated
  246. # into a list. However, we can't tell the difference between a scalar
  247. # value and a single element flattened list. So before calling the
  248. # real _handle_list, we know that "node" should actually be a list if
  249. # it's flattened, and if it's not, then we make it a one element list.
  250. if shape.serialization.get('flattened') and not isinstance(node, list):
  251. node = [node]
  252. return super(BaseXMLResponseParser, self)._handle_list(shape, node)
  253. def _handle_structure(self, shape, node):
  254. parsed = {}
  255. members = shape.members
  256. xml_dict = self._build_name_to_xml_node(node)
  257. for member_name in members:
  258. member_shape = members[member_name]
  259. if 'location' in member_shape.serialization:
  260. # All members with locations have already been handled,
  261. # so we don't need to parse these members.
  262. continue
  263. xml_name = self._member_key_name(member_shape, member_name)
  264. member_node = xml_dict.get(xml_name)
  265. if member_node is not None:
  266. parsed[member_name] = self._parse_shape(
  267. member_shape, member_node)
  268. elif member_shape.serialization.get('xmlAttribute'):
  269. attribs = {}
  270. location_name = member_shape.serialization['name']
  271. for key, value in node.attrib.items():
  272. new_key = self._namespace_re.sub(
  273. location_name.split(':')[0] + ':', key)
  274. attribs[new_key] = value
  275. if location_name in attribs:
  276. parsed[member_name] = attribs[location_name]
  277. return parsed
  278. def _member_key_name(self, shape, member_name):
  279. # This method is needed because we have to special case flattened list
  280. # with a serialization name. If this is the case we use the
  281. # locationName from the list's member shape as the key name for the
  282. # surrounding structure.
  283. if shape.type_name == 'list' and shape.serialization.get('flattened'):
  284. list_member_serialized_name = shape.member.serialization.get(
  285. 'name')
  286. if list_member_serialized_name is not None:
  287. return list_member_serialized_name
  288. serialized_name = shape.serialization.get('name')
  289. if serialized_name is not None:
  290. return serialized_name
  291. return member_name
  292. def _build_name_to_xml_node(self, parent_node):
  293. # If the parent node is actually a list. We should not be trying
  294. # to serialize it to a dictionary. Instead, return the first element
  295. # in the list.
  296. if isinstance(parent_node, list):
  297. return self._build_name_to_xml_node(parent_node[0])
  298. xml_dict = {}
  299. for item in parent_node:
  300. key = self._node_tag(item)
  301. if key in xml_dict:
  302. # If the key already exists, the most natural
  303. # way to handle this is to aggregate repeated
  304. # keys into a single list.
  305. # <foo>1</foo><foo>2</foo> -> {'foo': [Node(1), Node(2)]}
  306. if isinstance(xml_dict[key], list):
  307. xml_dict[key].append(item)
  308. else:
  309. # Convert from a scalar to a list.
  310. xml_dict[key] = [xml_dict[key], item]
  311. else:
  312. xml_dict[key] = item
  313. return xml_dict
  314. def _parse_xml_string_to_dom(self, xml_string):
  315. try:
  316. parser = xml.etree.cElementTree.XMLParser(
  317. target=xml.etree.cElementTree.TreeBuilder(),
  318. encoding=self.DEFAULT_ENCODING)
  319. parser.feed(xml_string)
  320. root = parser.close()
  321. except XMLParseError as e:
  322. raise ResponseParserError(
  323. "Unable to parse response (%s), "
  324. "invalid XML received:\n%s" % (e, xml_string))
  325. return root
  326. def _replace_nodes(self, parsed):
  327. for key, value in parsed.items():
  328. if value.getchildren():
  329. sub_dict = self._build_name_to_xml_node(value)
  330. parsed[key] = self._replace_nodes(sub_dict)
  331. else:
  332. parsed[key] = value.text
  333. return parsed
  334. @_text_content
  335. def _handle_boolean(self, shape, text):
  336. if text == 'true':
  337. return True
  338. else:
  339. return False
  340. @_text_content
  341. def _handle_float(self, shape, text):
  342. return float(text)
  343. @_text_content
  344. def _handle_timestamp(self, shape, text):
  345. return self._timestamp_parser(text)
  346. @_text_content
  347. def _handle_integer(self, shape, text):
  348. return int(text)
  349. @_text_content
  350. def _handle_string(self, shape, text):
  351. return text
  352. @_text_content
  353. def _handle_blob(self, shape, text):
  354. return self._blob_parser(text)
  355. _handle_character = _handle_string
  356. _handle_double = _handle_float
  357. _handle_long = _handle_integer
  358. class QueryParser(BaseXMLResponseParser):
  359. def _do_error_parse(self, response, shape):
  360. xml_contents = response['body']
  361. root = self._parse_xml_string_to_dom(xml_contents)
  362. parsed = self._build_name_to_xml_node(root)
  363. self._replace_nodes(parsed)
  364. # Once we've converted xml->dict, we need to make one or two
  365. # more adjustments to extract nested errors and to be consistent
  366. # with ResponseMetadata for non-error responses:
  367. # 1. {"Errors": {"Error": {...}}} -> {"Error": {...}}
  368. # 2. {"RequestId": "id"} -> {"ResponseMetadata": {"RequestId": "id"}}
  369. if 'Errors' in parsed:
  370. parsed.update(parsed.pop('Errors'))
  371. if 'RequestId' in parsed:
  372. parsed['ResponseMetadata'] = {'RequestId': parsed.pop('RequestId')}
  373. return parsed
  374. def _do_parse(self, response, shape):
  375. xml_contents = response['body']
  376. root = self._parse_xml_string_to_dom(xml_contents)
  377. parsed = {}
  378. if shape is not None:
  379. start = root
  380. if 'resultWrapper' in shape.serialization:
  381. start = self._find_result_wrapped_shape(
  382. shape.serialization['resultWrapper'],
  383. root)
  384. parsed = self._parse_shape(shape, start)
  385. self._inject_response_metadata(root, parsed)
  386. return parsed
  387. def _find_result_wrapped_shape(self, element_name, xml_root_node):
  388. mapping = self._build_name_to_xml_node(xml_root_node)
  389. return mapping[element_name]
  390. def _inject_response_metadata(self, node, inject_into):
  391. mapping = self._build_name_to_xml_node(node)
  392. child_node = mapping.get('ResponseMetadata')
  393. if child_node is not None:
  394. sub_mapping = self._build_name_to_xml_node(child_node)
  395. for key, value in sub_mapping.items():
  396. sub_mapping[key] = value.text
  397. inject_into['ResponseMetadata'] = sub_mapping
  398. class EC2QueryParser(QueryParser):
  399. def _inject_response_metadata(self, node, inject_into):
  400. mapping = self._build_name_to_xml_node(node)
  401. child_node = mapping.get('requestId')
  402. if child_node is not None:
  403. inject_into['ResponseMetadata'] = {'RequestId': child_node.text}
  404. def _do_error_parse(self, response, shape):
  405. # EC2 errors look like:
  406. # <Response>
  407. # <Errors>
  408. # <Error>
  409. # <Code>InvalidInstanceID.Malformed</Code>
  410. # <Message>Invalid id: "1343124"</Message>
  411. # </Error>
  412. # </Errors>
  413. # <RequestID>12345</RequestID>
  414. # </Response>
  415. # This is different from QueryParser in that it's RequestID,
  416. # not RequestId
  417. original = super(EC2QueryParser, self)._do_error_parse(response, shape)
  418. original['ResponseMetadata'] = {
  419. 'RequestId': original.pop('RequestID')
  420. }
  421. return original
  422. class BaseJSONParser(ResponseParser):
  423. def _handle_structure(self, shape, value):
  424. member_shapes = shape.members
  425. if value is None:
  426. # If the comes across the wire as "null" (None in python),
  427. # we should be returning this unchanged, instead of as an
  428. # empty dict.
  429. return None
  430. final_parsed = {}
  431. for member_name in member_shapes:
  432. member_shape = member_shapes[member_name]
  433. json_name = member_shape.serialization.get('name', member_name)
  434. raw_value = value.get(json_name)
  435. if raw_value is not None:
  436. final_parsed[member_name] = self._parse_shape(
  437. member_shapes[member_name],
  438. raw_value)
  439. return final_parsed
  440. def _handle_map(self, shape, value):
  441. parsed = {}
  442. key_shape = shape.key
  443. value_shape = shape.value
  444. for key, value in value.items():
  445. actual_key = self._parse_shape(key_shape, key)
  446. actual_value = self._parse_shape(value_shape, value)
  447. parsed[actual_key] = actual_value
  448. return parsed
  449. def _handle_blob(self, shape, value):
  450. return self._blob_parser(value)
  451. def _handle_timestamp(self, shape, value):
  452. return self._timestamp_parser(value)
  453. def _do_error_parse(self, response, shape):
  454. body = self._parse_body_as_json(response['body'])
  455. error = {"Error": {"Message": '', "Code": ''}, "ResponseMetadata": {}}
  456. # Error responses can have slightly different structures for json.
  457. # The basic structure is:
  458. #
  459. # {"__type":"ConnectClientException",
  460. # "message":"The error message."}
  461. # The error message can either come in the 'message' or 'Message' key
  462. # so we need to check for both.
  463. error['Error']['Message'] = body.get('message',
  464. body.get('Message', ''))
  465. code = body.get('__type')
  466. if code is not None:
  467. # code has a couple forms as well:
  468. # * "com.aws.dynamodb.vAPI#ProvisionedThroughputExceededException"
  469. # * "ResourceNotFoundException"
  470. if '#' in code:
  471. code = code.rsplit('#', 1)[1]
  472. error['Error']['Code'] = code
  473. self._inject_response_metadata(error, response['headers'])
  474. return error
  475. def _inject_response_metadata(self, parsed, headers):
  476. if 'x-amzn-requestid' in headers:
  477. parsed.setdefault('ResponseMetadata', {})['RequestId'] = (
  478. headers['x-amzn-requestid'])
  479. def _parse_body_as_json(self, body_contents):
  480. if not body_contents:
  481. return {}
  482. body = body_contents.decode(self.DEFAULT_ENCODING)
  483. original_parsed = json.loads(body)
  484. return original_parsed
  485. class JSONParser(BaseJSONParser):
  486. """Response parse for the "json" protocol."""
  487. def _do_parse(self, response, shape):
  488. # The json.loads() gives us the primitive JSON types,
  489. # but we need to traverse the parsed JSON data to convert
  490. # to richer types (blobs, timestamps, etc.
  491. if shape is not None:
  492. original_parsed = self._parse_body_as_json(response['body'])
  493. parsed = self._parse_shape(shape, original_parsed)
  494. else:
  495. parsed = self._parse_body_as_json(response['body'])
  496. self._inject_response_metadata(parsed, response['headers'])
  497. return parsed
  498. def _do_error_parse(self, response, shape):
  499. body = self._parse_body_as_json(response['body'])
  500. if "Error" in body or "error" in body:
  501. error = {"ResponseMetadata": {}, 'Error': body.get("Error", body.get("error", {}))}
  502. else:
  503. if "Code" in body or "code" in body:
  504. code = body.get("Code", body.get("code"))
  505. else:
  506. code = response['status_code']
  507. if "Message" in body or "message" in body:
  508. message = body.get("Message", body.get("message"))
  509. else:
  510. message = str(body)
  511. error = {"ResponseMetadata": {}, 'Error': {'Code': code, 'Message': message}}
  512. error['ResponseMetadata'].update(RequestId=body.get("RequestId"))
  513. return error
  514. class BaseRestParser(ResponseParser):
  515. def _do_parse(self, response, shape):
  516. final_parsed = {}
  517. final_parsed['ResponseMetadata'] = self._populate_response_metadata(
  518. response)
  519. if shape is None:
  520. return final_parsed
  521. member_shapes = shape.members
  522. self._parse_non_payload_attrs(response, shape,
  523. member_shapes, final_parsed)
  524. self._parse_payload(response, shape, member_shapes, final_parsed)
  525. return final_parsed
  526. def _populate_response_metadata(self, response):
  527. metadata = {}
  528. headers = response['headers']
  529. if 'x-amzn-requestid' in headers:
  530. metadata['RequestId'] = headers['x-amzn-requestid']
  531. elif 'x-amz-request-id' in headers:
  532. metadata['RequestId'] = headers['x-amz-request-id']
  533. # HostId is what it's called whenver this value is returned
  534. # in an XML response body, so to be consistent, we'll always
  535. # call is HostId.
  536. metadata['HostId'] = headers.get('x-amz-id-2', '')
  537. return metadata
  538. def _parse_payload(self, response, shape, member_shapes, final_parsed):
  539. if 'payload' in shape.serialization:
  540. # If a payload is specified in the output shape, then only that
  541. # shape is used for the body payload.
  542. payload_member_name = shape.serialization['payload']
  543. body_shape = member_shapes[payload_member_name]
  544. if body_shape.type_name in ['string', 'blob']:
  545. # This is a stream
  546. body = response['body']
  547. if isinstance(body, bytes):
  548. body = body.decode(self.DEFAULT_ENCODING)
  549. final_parsed[payload_member_name] = body
  550. else:
  551. original_parsed = self._initial_body_parse(response['body'])
  552. final_parsed[payload_member_name] = self._parse_shape(
  553. body_shape, original_parsed)
  554. else:
  555. original_parsed = self._initial_body_parse(response['body'])
  556. body_parsed = self._parse_shape(shape, original_parsed)
  557. final_parsed.update(body_parsed)
  558. def _parse_non_payload_attrs(self, response, shape,
  559. member_shapes, final_parsed):
  560. headers = response['headers']
  561. for name in member_shapes:
  562. member_shape = member_shapes[name]
  563. location = member_shape.serialization.get('location')
  564. if location is None:
  565. continue
  566. elif location == 'statusCode':
  567. final_parsed[name] = self._parse_shape(
  568. member_shape, response['status_code'])
  569. elif location == 'headers':
  570. final_parsed[name] = self._parse_header_map(member_shape,
  571. headers)
  572. elif location == 'header':
  573. header_name = member_shape.serialization.get('name', name)
  574. if header_name in headers:
  575. final_parsed[name] = self._parse_shape(
  576. member_shape, headers[header_name])
  577. def _parse_header_map(self, shape, headers):
  578. # Note that headers are case insensitive, so we .lower()
  579. # all header names and header prefixes.
  580. parsed = {}
  581. prefix = shape.serialization.get('name', '').lower()
  582. for header_name in headers:
  583. if header_name.lower().startswith(prefix):
  584. # The key name inserted into the parsed hash
  585. # strips off the prefix.
  586. name = header_name[len(prefix):]
  587. parsed[name] = headers[header_name]
  588. return parsed
  589. def _initial_body_parse(self, body_contents):
  590. # This method should do the initial xml/json parsing of the
  591. # body. We we still need to walk the parsed body in order
  592. # to convert types, but this method will do the first round
  593. # of parsing.
  594. raise NotImplementedError("_initial_body_parse")
  595. class RestJSONParser(BaseRestParser, BaseJSONParser):
  596. def _initial_body_parse(self, body_contents):
  597. return self._parse_body_as_json(body_contents)
  598. def _do_error_parse(self, response, shape):
  599. error = super(RestJSONParser, self)._do_error_parse(response, shape)
  600. self._inject_error_code(error, response)
  601. return error
  602. def _inject_error_code(self, error, response):
  603. # The "Code" value can come from either a response
  604. # header or a value in the JSON body.
  605. body = self._initial_body_parse(response['body'])
  606. if 'x-amzn-errortype' in response['headers']:
  607. code = response['headers']['x-amzn-errortype']
  608. # Could be:
  609. # x-amzn-errortype: ValidationException:
  610. code = code.split(':')[0]
  611. error['Error']['Code'] = code
  612. elif 'code' in body or 'Code' in body:
  613. error['Error']['Code'] = body.get(
  614. 'code', body.get('Code', ''))
  615. class RestXMLParser(BaseRestParser, BaseXMLResponseParser):
  616. def _initial_body_parse(self, xml_string):
  617. if not xml_string:
  618. return xml.etree.cElementTree.Element('')
  619. return self._parse_xml_string_to_dom(xml_string)
  620. def _do_error_parse(self, response, shape):
  621. # We're trying to be service agnostic here, but S3 does have a slightly
  622. # different response structure for its errors compared to other
  623. # rest-xml serivces (route53/cloudfront). We handle this by just
  624. # trying to parse both forms.
  625. # First:
  626. # <ErrorResponse xmlns="...">
  627. # <Error>
  628. # <Type>Sender</Type>
  629. # <Code>InvalidInput</Code>
  630. # <Message>Invalid resource type: foo</Message>
  631. # </Error>
  632. # <RequestId>request-id</RequestId>
  633. # </ErrorResponse>
  634. if response['body']:
  635. # If the body ends up being invalid xml, the xml parser should not
  636. # blow up. It should at least try to pull information about the
  637. # the error response from other sources like the HTTP status code.
  638. try:
  639. return self._parse_error_from_body(response)
  640. except ResponseParserError as e:
  641. LOG.debug(
  642. 'Exception caught when parsing error response body:',
  643. exc_info=True)
  644. return self._parse_error_from_http_status(response)
  645. def _parse_error_from_http_status(self, response):
  646. return {
  647. 'Error': {
  648. 'Code': str(response['status_code']),
  649. 'Message': six.moves.http_client.responses.get(
  650. response['status_code'], ''),
  651. },
  652. 'ResponseMetadata': {
  653. 'RequestId': response['headers'].get('x-amz-request-id', ''),
  654. 'HostId': response['headers'].get('x-amz-id-2', ''),
  655. }
  656. }
  657. def _parse_error_from_body(self, response):
  658. xml_contents = response['body']
  659. root = self._parse_xml_string_to_dom(xml_contents)
  660. parsed = self._build_name_to_xml_node(root)
  661. self._replace_nodes(parsed)
  662. if root.tag == 'Error':
  663. # This is an S3 error response. First we'll populate the
  664. # response metadata.
  665. metadata = self._populate_response_metadata(response)
  666. # The RequestId and the HostId are already in the
  667. # ResponseMetadata, but are also duplicated in the XML
  668. # body. We don't need these values in both places,
  669. # we'll just remove them from the parsed XML body.
  670. parsed.pop('RequestId', '')
  671. parsed.pop('HostId', '')
  672. return {'Error': parsed, 'ResponseMetadata': metadata}
  673. elif 'RequestId' in parsed:
  674. # Other rest-xml serivces:
  675. parsed['ResponseMetadata'] = {'RequestId': parsed.pop('RequestId')}
  676. default = {'Error': {'Message': '', 'Code': ''}}
  677. merge_dicts(default, parsed)
  678. return default
  679. PROTOCOL_PARSERS = {
  680. 'ec2': EC2QueryParser,
  681. 'query': QueryParser,
  682. 'query-json': JSONParser,
  683. 'kcs': JSONParser,
  684. 'custom-body': JSONParser,
  685. 'json': JSONParser,
  686. 'json2': JSONParser,
  687. 'rest-json': RestJSONParser,
  688. 'rest-xml': RestXMLParser,
  689. }