使用阿里云Serverless函数计算实现HTTP健康检查+故障短信通知

使用阿里云Serverless函数计算实现HTTP健康检查+故障短信通知

应用场景

定时对网站/API进行请求,根据请求响应判断服务是否可用,网站是否存在宕机,当发生宕机时,发送短信通知管理员.

技术使用

运行平台:阿里云函数计算
开发语言:Python3(小功能,精简,开发快,可在阿里云上在线编辑代码)
其它:阿里云短信接口

为何选用函数计算?

  1. 无需关注运维,仅需要编写核心代码,一个python脚本就够了(阿里云上可在线编辑代码,本地开发环境都无需搭建)
  2. 定时进行检测,只需要选用函数计算的“定时触发器”即可
  3. 根据代码的调用次数和运行时间计费(相对价格应该是非常低的)

过程

  1. 阿里云上开通函数计算服务
  2. 创建服务:函数计算-创建服务:httpchk
  3. 创建函数:语言Python-空白函数
  4. 创建函数:触发器-定时触发器:httpchk-trigger-时间间隔1分钟
  5. 创建函数:函数名称:httpchk-fc,
  6. 创建函数:代码方式:在线编辑
  7. 创建函数:函数执行内存: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'))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章