def mirror_request_to_elasticsearch(request: Union[HttpRequest, Request]): """ Duplicate request and send-again against this server, with the ES header attached to mirror non-elasticsearch load against elasticsearch for load testing """ url = request.build_absolute_uri() data = json.dumps(request.data) headers = { **request.headers, HttpHeaders.parse_header_name(EXPERIMENTAL_API_HEADER): ELASTICSEARCH_HEADER_VALUE, } logger.warning( "Mirroring inbound request with elasticsearch experimental header.") # NOTE: Purposely desiring an immediate timeout, with ignoring of that timeout error, # since this is a fire-and-forget way to siphon off duplicate load-testing traffic to the server, # without disrupting the primary request try: if request.method == "GET": requests.get(url, data, headers=headers, timeout=0.01) elif request.method == "POST": requests.post(url, data, headers=headers, timeout=0.01) else: pass # TODO: Preemptive timeout still seems to cause the request to be recorded as 500 with: # ConnectionResetError: [Errno 54] Connection reset by peer. # See if this can be avoided in a different way than forcing an early timeout except (requests.exceptions.Timeout, ConnectionResetError): pass except Exception as exc: logger.exception("Mirrored request using Elasticsearch failed", exc_info=exc)
def test_parse_header_name(self): tests = ( ('PATH_INFO', None), ('HTTP_ACCEPT', 'Accept'), ('HTTP_USER_AGENT', 'User-Agent'), ('HTTP_X_FORWARDED_PROTO', 'X-Forwarded-Proto'), ('CONTENT_TYPE', 'Content-Type'), ('CONTENT_LENGTH', 'Content-Length'), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
def test_parse_header_name(self): tests = ( ('PATH_INFO', None), ('HTTP_ACCEPT', 'Accept'), ('HTTP_USER_AGENT', 'User-Agent'), ('HTTP_X_FORWARDED_PROTO', 'X-Forwarded-Proto'), ('CONTENT_TYPE', 'Content-Type'), ('CONTENT_LENGTH', 'Content-Length'), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
def test_parse_header_name(self): tests = ( ("PATH_INFO", None), ("HTTP_ACCEPT", "Accept"), ("HTTP_USER_AGENT", "User-Agent"), ("HTTP_X_FORWARDED_PROTO", "X-Forwarded-Proto"), ("CONTENT_TYPE", "Content-Type"), ("CONTENT_LENGTH", "Content-Length"), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
def _bad_token_message(self, reason, token_source): if token_source != 'POST': # Assume it is a settings.CSRF_HEADER_NAME value. header_name = HttpHeaders.parse_header_name(token_source) token_source = f'the {header_name!r} HTTP header' return f'CSRF token from {token_source} {reason}.'