使用阿里雲Serverless函數計算實現HTTP健康檢查+故障短信通知
應用場景
定時對網站/API進行請求,根據請求響應判斷服務是否可用,網站是否存在宕機,當發生宕機時,發送短信通知管理員.
技術使用
運行平臺:阿里雲函數計算
開發語言:Python3(小功能,精簡,開發快,可在阿里雲上在線編輯代碼)
其它:阿里雲短信接口
爲何選用函數計算?
- 無需關注運維,僅需要編寫核心代碼,一個python腳本就夠了(阿里雲上可在線編輯代碼,本地開發環境都無需搭建)
- 定時進行檢測,只需要選用函數計算的“定時觸發器”即可
- 根據代碼的調用次數和運行時間計費(相對價格應該是非常低的)
過程
- 阿里雲上開通函數計算服務
-
創建服務:函數計算-創建服務:
httpchk
- 創建函數:語言Python-空白函數
-
創建函數:觸發器-定時觸發器:
httpchk-trigger
-時間間隔1分鐘 - 創建函數:函數名稱:httpchk-fc,
- 創建函數:代碼方式:在線編輯
- 創建函數:函數執行內存:128MB(足足夠用)
函數代碼:
# -*- coding: utf-8 -*-
import logging
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
# 待檢測的網址,僅支持GET請求
urls = ["https://www.baidu.com","http://www.mtain.top"]
# 接收短信通知的手機號碼
phone = "180000000"
# 阿里雲短信接口相關信息
accessKeyId = 'xxxx'
accessSecret = 'xxxx'
signName = 'xxxxx'
templateCode = 'SMS_xxxx'
logger = logging.getLogger()
def handler(event, context):
for url in urls:
do_httpchk(url)
def do_httpchk(url):
logger.info('檢測網站:{}'.format(url))
try:
req=requests.get(url)
logger.info('網站:{}響應正常,返回數據長度:{}'.format(url,len(req.text)))
except Exception as e:
logger.error('網站:{}服務異常,{}'.format(url,e))
send_sms()
def send_sms():
client = AcsClient(accessKeyId, accessSecret, 'default')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https') # https | http
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('PhoneNumbers', phone)
request.add_query_param('SignName', signName)
request.add_query_param('TemplateCode', templateCode)
# 阿里雲短信變量 [a-zA-Z0-9] 且 長度小於20
web_name = url.replace('https://','').replace('http://','').replace('.','0')[0:18]
request.add_query_param('TemplateParam', '{"code":"'+web_name+'"}')
response = client.do_action(request)
logger.info('Send SMS Response:'+str(response, encoding = 'utf-8'))