ฉันยังใหม่กับ Devops และการเขียนโค้ด ฉันกำลังสร้างเครื่องมือตรวจสอบ (grafana) ด้วย CloudWatch และ Lambda
ฉันมีรหัสที่ทำงานไม่ถูกต้อง มันส่ง Ping ไปที่เซิร์ฟเวอร์ ถ้ามันส่งคืน 200 มันจะกด 0 ในการวัด และเมื่อไซต์ล่ม มันควรจะกด 1 แต่เมื่อฉันพูดถึงในการวัดการเขียนให้เขียน 1 แทนที่จะเขียน 1 มันเขียน 100 และถ้าฉันพยายามที่จะทำอะไรก็ตาม ค่าอื่นๆ มันมากกว่า 100 ของการโพสต์ แต่น้อยกว่า 100 เป็นเพียงการโพสต์ 100
นี่คือรหัส:
import boto3
import urllib2
def write_metric(value, metric):
d = boto3.client('cloudwatch')
d.put_metric_data(Namespace='WebsiteStatus',
MetricData=[
{
'MetricName':metric,
'Dimensions':[
{
'Name': 'Status',
'Value': 'WebsiteStatusCode',
},
],
'Value': value,
},
]
)
def check_site(url, metric):
STAT = 1
print("Checking %s " % url)
request = urllib2.Request("https://" +url)
try:
response = urllib2.urlopen(request)
response.close()
except urllib2.URLError as e:
if hasattr(e, 'code'):
print ("[Error:] Connection to %s failed with code: " %url +str(e.code))
STAT = 100
write_metric(STAT, metric)
if hasattr(e, 'reason'):
print ("[Error:] Connection to %s failed with code: " % url +str(e.reason))
STAT = 100
write_metric(STAT, metric)
except urllib2.HTTPError as e:
if hasattr(e, 'code'):
print ("[Error:] Connection to %s failed with code: " % url + str(e.code))
STAT = 100
write_metric(STAT, metric)
if hasattr(e, 'reason'):
print ("[Error:] Connection to %s failed with code: " % url + str(e.reason))
STAT = 100
write_metric(STAT, metric)
print('HTTPError!!!')
if STAT != 100:
STAT = response.getcode()
return STAT
def lambda_handler(event, context):
websiteurls = [
"website.com"
]
metricname = 'SiteAvailability'
for site in websiteurls:
r = check_site(site,metricname)
if r == 200:
print("Site %s is up" %site)
write_metric(0, metricname)
else:
print("[Error:] Site %s down" %site)
write_metric(1, metricname)