Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathlambda_function.py
More file actions
Latest commit
188 lines (146 loc) · 5.3 KB
/
Copy pathlambda_function.py
File metadata and controls
188 lines (146 loc) · 5.3 KB
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
from __future__ importprint_function
importbase64
importjson
importurllib
importboto3
importsocket
importssl
importre
importStringIO
importgzip
# Parameters
logmaticKey="<your_api_key>"
metadata= {
"your_metafields": {
"backend": "python"
},
"some_field": "change_me"
}
# Constants
host="api.logmatic.io"
raw_port=10514
# SSL security
# while creating the lambda function
enable_security=True
ssl_port=10515
deflambda_handler(event, context):
# Check prerequisites
iflogmaticKey=="<your_api_key>"orlogmaticKey=="":
raiseException(
"You must configure your API key before starting this lambda function (see #Parameters section)")
# Attach Logmatic.io's Socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port=raw_port
ifenable_security:
s=ssl.wrap_socket(s)
port=ssl_port
s.connect((host, port))
# Add the context to meta
metadata["aws"] = {}
metadata["aws"]["function_name"] =context.function_name
metadata["aws"]["function_version"] =context.function_version
metadata["aws"]["invoked_function_arn"] =context.invoked_function_arn
metadata["aws"]["memory_limit_in_mb"] =context.memory_limit_in_mb
try:
# Route to the corresponding parser
event_type=parse_event_type(event)
ifevent_type=="s3":
logs=s3_handler(s, event)
elifevent_type=="awslogs":
logs=awslogs_handler(s, event)
forloginlogs:
send_entry(s, log)
exceptExceptionase:
# Logs through the socket the error
err_message='Error parsing the object. Exception: {}'.format(str(e))
send_entry(s, err_message)
raisee
finally:
s.close()
# Utility functions
defparse_event_type(event):
if"Records"ineventandlen(event["Records"]) >0:
if"s3"inevent["Records"][0]:
return"s3"
elif"awslogs"inevent:
return"awslogs"
raiseException("Event type not supported (see #Event supported section)")
# Handle S3 events
defs3_handler(s, event):
s3=boto3.client('s3')
# Get the object from the event and show its content type
bucket=event['Records'][0]['s3']['bucket']['name']
key=urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
# Extract the S3 object
response=s3.get_object(Bucket=bucket, Key=key)
body=response['Body']
data=body.read()
structured_logs= []
# If the name has a .gz extension, then decompress the data
ifkey[-3:] =='.gz':
withgzip.GzipFile(fileobj=StringIO.StringIO(data)) asdecompress_stream:
data=decompress_stream.read()
ifis_cloudtrail(str(key)) isTrue:
cloud_trail=json.loads(data)
foreventincloud_trail['Records']:
# Create structured object
structured_line=merge_dicts(event, {"aws": {"s3": {"bucket": bucket, "key": key}}})
structured_logs.append(structured_line)
else:
# Send lines to Logmatic.io
forlineindata.splitlines():
# Create structured object
structured_line= {"aws": {"s3": {"bucket": bucket, "key": key}}, "message": line}
structured_logs.append(structured_line)
returnstructured_logs
# Handle CloudWatch events and logs
defawslogs_handler(s, event):
# Get logs
withgzip.GzipFile(fileobj=StringIO.StringIO(base64.b64decode(event["awslogs"]["data"]))) asdecompress_stream:
data=decompress_stream.read()
logs=json.loads(str(data))
structured_logs= []
# Send lines to Logmatic.io
forloginlogs["logEvents"]:
# Create structured object and send it
structured_line=merge_dicts(log, {
"aws": {
"awslogs": {
"logGroup": logs["logGroup"],
"logStream": logs["logStream"],
"owner": logs["owner"]
}
}
})
structured_logs.append(structured_line)
returnstructured_logs
defsend_entry(s, log_entry):
# The log_entry can only be a string or a dict
ifisinstance(log_entry, str):
log_entry= {"message": log_entry}
elifnotisinstance(log_entry, dict):
raiseException(
"Cannot send the entry as it must be either a string or a dict. Provided entry: "+str(log_entry))
# Merge with metadata
log_entry=merge_dicts(log_entry, metadata)
# Send to Logmatic.io
str_entry=json.dumps(log_entry)
s.send((logmaticKey+" "+str_entry+"\n").encode("UTF-8"))
defmerge_dicts(a, b, path=None):
ifpathisNone: path= []
forkeyinb:
ifkeyina:
ifisinstance(a[key], dict) andisinstance(b[key], dict):
merge_dicts(a[key], b[key], path+ [str(key)])
elifa[key] ==b[key]:
pass# same leaf value
else:
raiseException(
'Conflict while merging metadatas and the log entry at %s'%'.'.join(path+ [str(key)]))
else:
a[key] =b[key]
returna
defis_cloudtrail(key):
regex=re.compile('\d+_CloudTrail_\w{2}-\w{4,9}-[12]_\d{8}T\d{4}Z.+.json.gz$', re.I)
match=regex.search(key)
returnbool(match)