-
Notifications
You must be signed in to change notification settings - Fork 0
/
可参考的lamdba函数.py
352 lines (259 loc) · 11.6 KB
/
可参考的lamdba函数.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
问题描述:
【Rewards】exception 警报现在通过微信发送到企业微信
但是没有发送对应的Log
需要把Log通过微信发出去
解决指引:
可以参考SA PROD环境下的lambda函数
import json
import boto3
from datetime import datetime, timedelta
import time
import os
import requests
from requests_toolbelt import MultipartEncoder
client = boto3.client('logs')
file_name = "error-log.txt"
file_path = "/tmp/"
## bucket_name = "cloudwatchlog-export"
## s3_path = "log/20200520/" + file_name
def lambda_handler(event, context):
# TODO implement
message = event['Records'][0]['Sns']['Message']
print(message)
access_token = _get_access_token()
send_wechat_data(_get_send_text_content(message), access_token)
msgJson = json.loads(message)
logGroupName = ""
if msgJson['Trigger']['MetricName'] == "sa-redpackect-api-exception":
logGroupName = "/ecs/redpacket-api-prd-taskdefinition"
elif msgJson['Trigger']['MetricName'] == "sa-redpacket-batch-exception":
logGroupName = "/ecs/redpacket-batch-prd-taskdefinition"
elif msgJson['Trigger']['MetricName'] == "sa-ec-service-exception":
logGroupName = "/ecs/sa-ecommerce-prd-taskdefinition"
else:
logGroupName = "upsystem-api-error.log"
if msgJson['NewStateValue'] == "ALARM":
print("send Log file")
get_cloudwatch_log_to_file(logGroupName)
send_wechat_file(access_token)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
def get_cloudwatch_log_to_file(logGroupName):
string = ""
## For the latest
stream_response = client.describe_log_streams(
logGroupName=logGroupName, # Can be dynamic
orderBy='LastEventTime', # For the latest events
descending=True,
limit=1 # the last latest event, if you just want one
)
for log_stream in stream_response["logStreams"]:
latestlogStreamName = log_stream["logStreamName"]
firstEventTimestamp = log_stream["lastEventTimestamp"]
## print(firstEventTimestamp)
endTime = int(datetime.now().timestamp())*1000
startTime = int((datetime.now() - timedelta(minutes=2)).timestamp())*1000
response = client.get_log_events(
logGroupName=logGroupName,
logStreamName=latestlogStreamName,
startTime=startTime,
endTime=endTime,
)
for event in response["events"]:
## print(event["message"])
timestamp = event["timestamp"]
## print(timestamp)
utc_time = datetime.utcfromtimestamp(timestamp/1000)
date_time = utc_time + timedelta(hours=8)
## print(date_time)
timeStr = date_time.strftime("%Y-%m-%d %H:%M:%S")
string = string + timeStr + ' ' + event["message"] + '\n'
## Write file to temp file
newFile = open(file_path + file_name,'w')
n = newFile.write(string)
newFile.close()
## Read the file log to verify
## with open(file_path + file_name) as f:
## string2 = f.read()
## print(string2)
## Save to S3
## encoded_string = string.encode("utf-8")
## s3 = boto3.resource("s3")
## s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string)
def post_file_to_wechat_get_media_id(filepath, filename, access_token):
post_file_url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=file"
m = MultipartEncoder(
fields={filename: (filename, open(filepath + filename, 'rb'), 'text/plain')},
)
print(m)
r = requests.post(url=post_file_url, data=m, headers={'Content-Type': m.content_type})
print(r.text)
data = json.loads(r.text)
return data["media_id"]
def _get_access_token():
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
values = {'corpid': os.environ['CORP_ID'],
'corpsecret': os.environ['CORP_SECRET'],
}
req = requests.post(url, params=values)
data = json.loads(req.text)
## print(data)
return data["access_token"]
def send_wechat_file(access_token):
## access_token = _get_access_token()
media_id = post_file_to_wechat_get_media_id(file_path, file_name, access_token)
## print(media_id)
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send' + '?access_token=' + access_token
send_data = '{"msgtype": "file", "safe": 0, "agentid": %s, "toparty": "%s", "file": {"media_id": "%s"}}' % (
os.environ['AGENT_ID'], os.environ['PARTY_ID'], media_id)
r = requests.post(send_url, data=send_data)
## print(r.content)
return r.content
def send_wechat_data(message,access_token):
msg = message.encode('utf-8')
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send' + '?access_token=' + access_token
send_data = '{"msgtype": "text", "safe": 0, "agentid": %s, "toparty": "%s", "text": {"content": "%s"}}' % (
os.environ['AGENT_ID'], os.environ['PARTY_ID'], message)
print(message)
r = requests.post(send_url, data=send_data)
return r.content
def _get_send_text_content(message):
result_str = ''
msg_json = json.loads(message)
if msg_json['NewStateValue'] == "ALARM":
result_str = result_str + '***** ALARM *****\n\n'
else:
result_str = result_str + '***** RECOVERY *****\n\n'
result_str = result_str + 'Service:\n' + msg_json['Trigger']['MetricName'] + '\n\n'
result_str = result_str + 'Detail:\n' + msg_json['NewStateReason'] + '\n\n'
result_str = result_str + 'Time(UTC):\n' + msg_json['StateChangeTime'] + '\n'
return result_str
Rewards lamdba函数计划写成:
import json
import boto3
from datetime import datetime, timedelta
import time
import os
import requests
from requests_toolbelt import MultipartEncoder
client = boto3.client('logs')
file_name = "error-log.txt"
file_path = "/tmp/"
## bucket_name = "cloudwatchlog-export"
## s3_path = "log/20200520/" + file_name
def lambda_handler(event, context):
# TODO implement
message = event['Records'][0]['Sns']['Message']
print(message)
access_token = _get_access_token()
send_wechat_data(_get_send_text_content(message), access_token)
msgJson = json.loads(message)
logGroupName = ""
if msgJson['Trigger']['MetricName'] == "sa-redpackect-api-exception":
logGroupName = "/ecs/redpacket-api-prd-taskdefinition"
elif msgJson['Trigger']['MetricName'] == "sa-redpacket-batch-exception":
logGroupName = "/ecs/redpacket-batch-prd-taskdefinition"
elif msgJson['Trigger']['MetricName'] == "sa-ec-service-exception":
logGroupName = "/ecs/sa-ecommerce-prd-taskdefinition"
else:
logGroupName = "upsystem-api-error.log"
if msgJson['NewStateValue'] == "ALARM":
print("send Log file")
get_cloudwatch_log_to_file(logGroupName)
send_wechat_file(access_token)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
def get_cloudwatch_log_to_file(logGroupName):
string = ""
## For the latest
stream_response = client.describe_log_streams(
logGroupName=logGroupName, # Can be dynamic
orderBy='LastEventTime', # For the latest events
descending=True,
limit=1 # the last latest event, if you just want one
)
for log_stream in stream_response["logStreams"]:
latestlogStreamName = log_stream["logStreamName"]
firstEventTimestamp = log_stream["lastEventTimestamp"]
## print(firstEventTimestamp)
endTime = int(datetime.now().timestamp())*1000
startTime = int((datetime.now() - timedelta(minutes=2)).timestamp())*1000
response = client.get_log_events(
logGroupName=logGroupName,
logStreamName=latestlogStreamName,
startTime=startTime,
endTime=endTime,
)
for event in response["events"]:
## print(event["message"])
timestamp = event["timestamp"]
## print(timestamp)
utc_time = datetime.utcfromtimestamp(timestamp/1000)
date_time = utc_time + timedelta(hours=8)
## print(date_time)
timeStr = date_time.strftime("%Y-%m-%d %H:%M:%S")
string = string + timeStr + ' ' + event["message"] + '\n'
## Write file to temp file
newFile = open(file_path + file_name,'w')
n = newFile.write(string)
newFile.close()
## Read the file log to verify
## with open(file_path + file_name) as f:
## string2 = f.read()
## print(string2)
## Save to S3
## encoded_string = string.encode("utf-8")
## s3 = boto3.resource("s3")
## s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string)
def post_file_to_wechat_get_media_id(filepath, filename, access_token):
post_file_url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=file"
m = MultipartEncoder(
fields={filename: (filename, open(filepath + filename, 'rb'), 'text/plain')},
)
print(m)
r = requests.post(url=post_file_url, data=m, headers={'Content-Type': m.content_type})
print(r.text)
data = json.loads(r.text)
return data["media_id"]
def _get_access_token():
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
values = {'corpid': os.environ['CORP_ID'],
'corpsecret': os.environ['CORP_SECRET'],
}
req = requests.post(url, params=values)
data = json.loads(req.text)
## print(data)
return data["access_token"]
def send_wechat_file(access_token):
## access_token = _get_access_token()
media_id = post_file_to_wechat_get_media_id(file_path, file_name, access_token)
## print(media_id)
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send' + '?access_token=' + access_token
send_data = '{"msgtype": "file", "safe": 0, "agentid": %s, "toparty": "%s", "file": {"media_id": "%s"}}' % (
os.environ['AGENT_ID'], os.environ['PARTY_ID'], media_id)
r = requests.post(send_url, data=send_data)
## print(r.content)
return r.content
def send_wechat_data(message,access_token):
msg = message.encode('utf-8')
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send' + '?access_token=' + access_token
send_data = '{"msgtype": "text", "safe": 0, "agentid": %s, "toparty": "%s", "text": {"content": "%s"}}' % (
os.environ['AGENT_ID'], os.environ['PARTY_ID'], message)
print(message)
r = requests.post(send_url, data=send_data)
return r.content
def _get_send_text_content(message):
result_str = ''
msg_json = json.loads(message)
if msg_json['NewStateValue'] == "ALARM":
result_str = result_str + '***** ALARM *****\n\n'
else:
result_str = result_str + '***** RECOVERY *****\n\n'
result_str = result_str + 'Service:\n' + msg_json['Trigger']['MetricName'] + '\n\n'
result_str = result_str + 'Detail:\n' + msg_json['NewStateReason'] + '\n\n'
result_str = result_str + 'Time(UTC):\n' + msg_json['StateChangeTime'] + '\n'
return result_str