44import urllib .request as urllib2
55import os
66import json
7+ import threading
78
89website_url = json .loads (os .environ ['Website_URL' ])
910metricname = os .environ ['metricname' ]
@@ -36,17 +37,16 @@ def check_site(url, metric):
3637 STAT = 1
3738 print ("Checking %s " % url )
3839 request = urllib2 .Request (url )
39-
4040 try :
41- response = urllib2 .urlopen (request , timeout = timeout )
41+ response = urllib2 .urlopen (request ,timeout = timeout )
4242 response .close ()
4343 except urllib2 .URLError as e :
4444 if hasattr (e , 'code' ):
4545 print ("1st if" )
4646 print ("[Error:] Connection to %s failed with code: " % url + str (e .code ))
4747 STAT = int (e .code )
4848 # write_metric(STAT, metric, url)
49- if hasattr (e , 'reason' ):
49+ elif hasattr (e , 'reason' ):
5050 print ("2nd if" )
5151 print ("[Error:] Connection to %s failed with code: " % url + str (e .reason ))
5252 STAT = 501
@@ -57,27 +57,36 @@ def check_site(url, metric):
5757 print ("[Error:] Connection to %s failed with code: " % url + str (e .code ))
5858 STAT = int (e .code )
5959 # write_metric(STAT, metric, url)
60- if hasattr (e , 'reason' ):
60+ elif hasattr (e , 'reason' ):
6161 print ("4th if" )
6262 print ("[Error:] Connection to %s failed with code: " % url + str (e .reason ))
6363 STAT = 501
6464 # write_metric(STAT, metric, url)
65- if STAT != 501 :
65+ print (STAT )
66+ if STAT != 501 and STAT == 1 :
6667 STAT = response .getcode ()
6768
6869 return STAT
6970
71+ def run_thread (site ):
72+ r = check_site (site ,metricname )
73+ if r == 200 or r == 304 or r == 400 :
74+ print ("Site %s is up" % site )
75+ write_metric (200 , metricname , site )
76+ else :
77+ print ("[Error:] Site %s down" % site )
78+ write_metric (int (r ), metricname , site )
79+
7080def handler (event , context ):
7181
7282 # Change these to your actual websites. Remember, the more websites you list
7383 # the longer the lambda function will run
7484 websiteurls = website_url
85+ t = [0 ]* len (website_url )
86+ for i in range (len (websiteurls )):
87+ t [i ] = threading .Thread (target = run_thread , args = (website_url [i ],))
88+ t [i ].start ()
7589
76- for site in websiteurls :
77- r = check_site (site ,metricname )
78- if r == 200 or r == 304 or r == 400 :
79- print ("Site %s is up" % site )
80- write_metric (200 , metricname , site )
81- else :
82- print ("[Error:] Site %s down" % site )
83- write_metric (int (r ), metricname , site )
90+ for i in range (len (t )):
91+ t [i ].join ()
92+ print ("Done!" )
0 commit comments