Saya baru mengenal Devops dan coding. Saya sedang membangun alat pemantauan (grafana) dengan CloudWatch dan Lambda.
Saya memiliki kode yang tidak berfungsi dengan benar. Itu melakukan ping ke server. Jika mengembalikan 200, ia akan menekan 0 di metrik dan ketika situs sedang down, ia harus menekan 1 tetapi ketika saya menyebutkan di metrik tulis untuk menulis 1, alih-alih menulis 1, tulisannya 100 dan jika saya mencoba melakukan apa pun nilai lain lebih besar dari 100 postingannya tetapi kurang dari 100 hanya postingan 100.
Ini kodenya:
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)