Application scenario
Regularly request the website / API, judge whether the service is available and whether the website is down according to the request response, and send a SMS to inform the administrator when there is a down time
engineering service
Operation platform: Alibaba cloud functional computing
Development language: Python 3 (small function, simplified, fast development, code can be edited online on Alibaba cloud)
Other: Alibaba cloud SMS interface
Why function calculation?
- No need to pay attention to O & M, just write core code, a python script is enough (Alibaba cloud can edit code online, and local development environment does not need to be built)
- For timing detection, only the "timing trigger" of function calculation is needed
- Based on the number of calls and running time of the code (the relative price should be very low)
process
- Alibaba cloud opens function computing service
- Create service: function calculation - create service: httpchk
- Create function: language Python - Blank function
- Create function: trigger timing trigger: httpchk trigger time interval 1 minute
- Create function: function name: httpchk FC,
- Creating functions: code by: editing Online
- Create function: function execution memory: 128MB (enough)
Function code:
# -*- coding: utf-8 -*- import logging import requests from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest # Web address to be detected, only GET requests are supported urls = ["https://www.baidu.com","http://www.mtain.top"] # Mobile number to receive SMS notification phone = "180000000" # Alibaba cloud SMS interface information 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('Testing website:{}'.format(url)) try: req=requests.get(url) logger.info('website:{}Normal response,Return data length:{}'.format(url,len(req.text))) except Exception as e: logger.error('website:{}Service exception,{}'.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) # Alibaba cloud SMS variable [a-zA-Z0-9] with length less than 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'))