sondehub-infra/lambda/sqs_to_elk/__init__.py

35 lines
1.3 KiB
Python
Raw Normal View History

2021-05-20 08:43:50 +00:00
import json
2021-12-20 06:02:02 +00:00
import es
2021-05-20 08:43:50 +00:00
def lambda_handler(event, context):
payloads = {}
for record in event['Records']:
sns_message = json.loads(record["body"])
if type(json.loads(sns_message["Message"])) == dict:
incoming_payloads = [json.loads(sns_message["Message"])]
else:
incoming_payloads = json.loads(sns_message["Message"])
for payload in incoming_payloads:
index = payload['datetime'][:7]
2021-05-20 08:43:50 +00:00
if index not in payloads: # create index if not exists
payloads[index] = []
payloads[index].append(payload)
2021-05-20 08:43:50 +00:00
for index in payloads:
body=""
for payload in payloads[index]:
body += "{\"index\":{}}\n" + json.dumps(payload) + "\n"
body += "\n"
2021-12-20 06:02:02 +00:00
result = es.request(body, f"telm-{index}/_doc/_bulk", "POST")
2021-05-20 08:43:50 +00:00
if 'errors' in result and result['errors'] == True:
error_types = [x['index']['error']['type'] for x in result['items'] if 'error' in x['index']] # get all the error types
print(event)
print(result)
2021-05-20 08:43:50 +00:00
error_types = [a for a in error_types if a != 'mapper_parsing_exception'] # filter out mapper failures since they will never succeed
if error_types:
raise RuntimeError