使用OpenAPI自动化处理ECS系统事件

简介: 什么是系统事件 当您将业务系统部署到阿里云ECS后,阿里云保证ECS计算服务的高可用。在极少情况下,比如探测到ECS实例所在的硬件发生故障,会产生有计划的维护事件并通知您。 深入了解系统事件,请参考: 实例系统事件 让运维更高效:关于ECS系统事件 监控和应对系统事件的方式 为了业务的平稳运行,您需要监控ECS系统事件并及时合理地应对系统事件。

什么是系统事件

当您将业务系统部署到阿里云ECS后,阿里云保证ECS计算服务的高可用。在极少情况下,比如探测到ECS实例所在的硬件发生故障,会产生有计划的维护事件并通知您。

深入了解系统事件,请参考:

监控和应对系统事件的方式

为了业务的平稳运行,您需要监控ECS系统事件并及时合理地应对系统事件。

从控制台处理ECS主动运维事件请参考 ECS主动运维事件--让你HOLD住全场

相对于收到通知后登陆ECS控制台人工处理系统事件,通过程序自动化监控和处理系统事件,能够提高您的运维效率,消除遗漏或出错的可能性,让您的运维人员不用再为半夜的故障通知而烦恼。如果您保有较多的ECS实例,自动化程序的优点将会更加突出。

ECS为您提供了两个OpenAPI来监控实例的健康状态和系统事件。

1. DescribeInstancesFullStatus 查询实例的全状态信息

ECS实例全状态信息包括:

  • 实例的生命周期状态,比如实例处于Running还是Stopped状态
  • 实例的健康状态,比如您的实例处于Ok还是Warning状态
  • 处于待执行状态(Scheduled)的所有系统事件

这个OpenAPI关注实例的当前状态,它不会返回已经完结的历史事件。对于事前运维来说,我们只需要关注Scheduled状态的事件。事件处于Scheduled状态意味着现在仍处在用户操作窗口期。在事件的计划执行时间NotBefore之前,我们可以通过程序处理来避免事件执行。

首先,我们调用DescribeInstancesFullStatus OpenAPI来查询当前是否存在待执行的SystemMaintenance.Reboot事件。

def build_instance_full_status_request():
    request = DescribeInstancesFullStatusRequest()
    request.set_EventType('SystemMaintenance.Reboot')
    return request


# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = client.do_action_with_exception(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)


# only_check=True时仅检查是否存在SystemMaintenance.Reboot事件,为False时对SystemMaintenance.Reboot事件进行处理
def check_scheduled_reboot_events(only_check=False, instance_id=None):
    request = build_instance_full_status_request()
    if instance_id:
        request.set_InstanceIds([instance_id])
    response = _send_request(request)
    if response.get('Code') is None:
        instance_full_status_list = response.get('InstanceFullStatusSet').get('InstanceFullStatusType')
        # 因为指定了事件类型查询,无SystemMaintenance.Reboot系统事件的实例不会返回
        exist_reboot_event = len(instance_full_status_list) > 0
        if not exist_reboot_event:
            print "No scheduled SystemMaintenance.Reboot event found"
        if only_check:
            return exist_reboot_event
        for instance_full_status in instance_full_status_list:
            instance_id = instance_full_status.get('InstanceId')
            scheduled_reboot_events = instance_full_status.get('ScheduledSystemEventSet').get(
                'ScheduledSystemEventType')
            for scheduled_reboot_event in scheduled_reboot_events:
                handle_reboot_event(instance_id, scheduled_reboot_event)
    else:
        logging.error(str(response))

Tip:主动运维系统事件会留出足够长的用户操作窗口期,一般以天为单位。所以并不需要频繁的去轮询待执行的系统事件。未来我们将会提供基于消息队列的系统事件消费接口

如果发现存在SystemMaintenance.Reboot系统事件,您应该根据实例上运行的业务类型来决定是否需要自行处理。

Tip:即使由ECS系统执行重启,对您的重要数据进行提前备份也是一个好主意。

如果实例重启对业务有影响,你可能需要选择一个NotBefore之前的更合适的业务低谷时间点。您需要设定一个定时任务,在这个时间点执行重启操作。


def handle_reboot_event(instance_id, reboot_event):
    not_before_str = reboot_event.get('NotBefore')
    not_before = datetime.strptime(not_before_str, '%Y-%m-%dT%H:%M:%SZ')
    print "Instance %s has a SystemMaintenance.Reboot event scheduled to execute at %s" % (instance_id, str(not_before))
    # 根据你的业务特性选择not_before之前的影响最小的时间点
    # 使用定时任务在该时间点进行实例重启

    # 示例中简化为立即重启
    pre_reboot(instance_id)
    reboot_instance(instance_id)
    post_reboot(instance_id)


def reboot_instance(instance_id):
    print "Reboot instance %s now..." % instance_id
    reboot_request = RebootInstanceRequest()
    reboot_request.set_InstanceId(instance_id)
    _send_request(reboot_request)


def pre_reboot(instance_id):
    # 重启前做backup等等准备工作
    print "Do pre-reboot works..."


def post_reboot(instance_id):
    # 重启后做健康检查等等善后工作
    # 检查重启是否成功
    print "Do post-reboot works..."

    # 一般情况下重启成功后几秒后SystemMaintenance.Reboot事件将变为Avoided状态
    # 再次查询DescribeInstancesFullStatus确认SystemMaintenance.Reboot事件无法查询到
    wait_event_disappear(instance_id)

重启成功完成后,系统事件将在短时间内变为Avoided状态。

def wait_event_disappear(instance_id):
    wait_sec = 0
    while wait_sec < TIME_OUT:
        exist = check_scheduled_reboot_events(only_check=True, instance_id=instance_id)
        if not exist:
            print "SystemMaintenance.Reboot system event is avoided"
            return
        time.sleep(10)
        wait_sec += 10

您的自动化处理程序需要妥善处理各种异常情况,保证定时重启的及时性和稳定性。尤其注意的是,在事件状态变化前不要重复处理,以避免不必要的重启。

2. DescribeInstanceHistoryEvents 查询实例的历史事件

查询指定ECS实例的系统事件,默认查询已经处于非活跃状态的历史事件。如果指定全部的事件状态,可以查询包含活跃事件在内的所有事件。

此API默认只查询历史事件,它的用途是对实例的历史事件进行分析、复盘,追溯问题原因。某些事件类型比如SystemFailure.Reboot发生时,不一定会留出用户操作窗口期。比如非预期的紧急故障发生后,阿里云立刻进行了恢复并重启了您的实例。此类事件可以在历史事件中查询到。

总结

  1. 使用DescribeInstancesFullStatus来查询实例状态和Scheduled状态的系统事件
  2. 使用DescribeInstanceHistoryEvents对历史事件进行复盘。如果指定系统事件状态,也可以查询未结束的系统事件(Scheduled和Executing状态)。
  3. 使用自动化程序对Scheduled状态的系统事件进行处理
  4. 如果只需要查询系统事件,推荐使用DescribeInstanceHistoryEvents接口,性能更好。

未来我们将会发布更多类型的ECS实例和存储相关系统事件,覆盖更多运维场景,敬请期待!

完整的示例代码如下

#  coding=utf-8

# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
# if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
# make sure the sdk version is 4.4.3, you can use command 'pip show aliyun-python-sdk-ecs' to check

import json
import logging
from datetime import datetime
import time

from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstancesFullStatusRequest import DescribeInstancesFullStatusRequest
from aliyunsdkecs.request.v20140526.RebootInstanceRequest import RebootInstanceRequest

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')

# your access key Id
ak_id = "YOU_ACCESS_KEY_ID"
# your access key secret
ak_secret = "YOU_ACCESS_SECRET"
region_id = "cn-shanghai"
TIME_OUT = 5 * 60

client = client.AcsClient(ak_id, ak_secret, region_id)


def build_instance_full_status_request():
    request = DescribeInstancesFullStatusRequest()
    request.set_EventType('SystemMaintenance.Reboot')
    return request


# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = client.do_action_with_exception(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)


# only_check=True时仅检查是否存在SystemMaintenance.Reboot事件,为False时对SystemMaintenance.Reboot事件进行处理
def check_scheduled_reboot_events(only_check=False, instance_id=None):
    request = build_instance_full_status_request()
    if instance_id:
        request.set_InstanceIds([instance_id])
    response = _send_request(request)
    if response.get('Code') is None:
        instance_full_status_list = response.get('InstanceFullStatusSet').get('InstanceFullStatusType')
        # 因为指定了事件类型查询,无SystemMaintenance.Reboot系统事件的实例不会返回
        exist_reboot_event = len(instance_full_status_list) > 0
        if not exist_reboot_event:
            print "No scheduled SystemMaintenance.Reboot event found"
        if only_check:
            return exist_reboot_event
        for instance_full_status in instance_full_status_list:
            instance_id = instance_full_status.get('InstanceId')
            scheduled_reboot_events = instance_full_status.get('ScheduledSystemEventSet').get(
                'ScheduledSystemEventType')
            for scheduled_reboot_event in scheduled_reboot_events:
                handle_reboot_event(instance_id, scheduled_reboot_event)
    else:
        logging.error(str(response))


def handle_reboot_event(instance_id, reboot_event):
    not_before_str = reboot_event.get('NotBefore')
    not_before = datetime.strptime(not_before_str, '%Y-%m-%dT%H:%M:%SZ')
    print "Instance %s has a SystemMaintenance.Reboot event scheduled to execute at %s" % (instance_id, str(not_before))
    # 根据你的业务特性选择not_before之前的影响最小的时间点
    # 使用定时任务在该时间点进行实例重启

    # 示例中简化为立即重启
    pre_reboot(instance_id)
    reboot_instance(instance_id)
    post_reboot(instance_id)


def reboot_instance(instance_id):
    print "Reboot instance %s now..." % instance_id
    reboot_request = RebootInstanceRequest()
    reboot_request.set_InstanceId(instance_id)
    _send_request(reboot_request)


def pre_reboot(instance_id):
    # 重启前做backup等等准备工作
    print "Do pre-reboot works..."


def post_reboot(instance_id):
    # 重启后做健康检查等等善后工作
    # 检查重启是否成功
    print "Do post-reboot works..."

    # 一般情况下重启成功后几秒后SystemMaintenance.Reboot事件将变为Avoided状态
    # 再次查询DescribeInstancesFullStatus确认SystemMaintenance.Reboot事件无法查询到
    wait_event_disappear(instance_id)


def wait_event_disappear(instance_id):
    wait_sec = 0
    while wait_sec < TIME_OUT:
        exist = check_scheduled_reboot_events(only_check=True, instance_id=instance_id)
        if not exist:
            print "SystemMaintenance.Reboot system event is avoided"
            return
        time.sleep(10)
        wait_sec += 10


if __name__ == '__main__':
    check_scheduled_reboot_events(only_check=False)
相关实践学习
2分钟自动化部署人生模拟器
本场景将带你借助云效流水线Flow实现人生模拟器小游戏的自动化部署
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情:&nbsp;https://www.aliyun.com/product/ecs
目录
相关文章
|
1月前
|
人工智能 自然语言处理 数据挖掘
企业数字化转型的关键:如何利用OA系统实现自动化与智能决策
在数字化时代,传统办公系统已无法满足现代企业的需求。通过将RPA(机器人流程自动化)和AI(人工智能)技术与OA系统结合,企业能实现业务流程自动化、智能决策支持,大幅提升工作效率和资源配置优化,推动数字化转型。RPA可自动处理重复任务,如审批、数据同步等;AI则提供智能数据分析、预测和决策支持,两者协同作用,助力财务管理、人力资源管理、项目管理和客户服务等多个领域实现智能化升级。未来,智能化OA系统将进一步提升个性化服务、数据安全和协作能力,成为企业发展的关键驱动力。
|
24天前
|
监控 运维
HTTPS 证书自动化运维:https证书管理系统- 自动化监控
本文介绍如何设置和查看域名或证书监控。步骤1:根据证书状态选择新增域名或证书监控,线上部署推荐域名监控,未部署选择证书监控。步骤2:查询监控记录详情。步骤3:在详情页查看每日定时检测结果或手动测试。
HTTPS 证书自动化运维:https证书管理系统- 自动化监控
|
24天前
|
Linux 持续交付 调度
HTTPS 证书自动化运维:https证书管理系统-自动化部署
本指南介绍如何部署Linux服务器节点。首先复制生成的Linux脚本命令,然后将其粘贴到目标服务器上运行。接着刷新页面查看节点记录,并点击“配置证书”选择证书以自动部署。最后,节点部署完成,后续将自动调度,无需人工干预。
HTTPS 证书自动化运维:https证书管理系统-自动化部署
|
27天前
|
机器学习/深度学习 人工智能 运维
基于AI的自动化事件响应:智慧运维新时代
基于AI的自动化事件响应:智慧运维新时代
99 11
|
24天前
|
运维 监控 数据安全/隐私保护
HTTPS 证书自动化运维:HTTPS 证书管理系统之使用指南
本文详细介绍【灵燕空间HTTPS证书管理系统】(https://www.lingyanspace.com)的配置与使用,涵盖注册账户、邮箱配置及证书自动签发、监控和部署的一体化指南。通过页面顶部菜单的【视频教程】和【图文教程】,帮助用户从注册到实际应用全面掌握系统操作。最新迭代后,泛域名证书已包含根域名,无需额外申请多域名证书。
|
2月前
|
存储 人工智能 自然语言处理
ChatMCP:基于 MCP 协议开发的 AI 聊天客户端,支持多语言和自动化安装 MCP 服务器
ChatMCP 是一款基于模型上下文协议(MCP)的 AI 聊天客户端,支持多语言和自动化安装。它能够与多种大型语言模型(LLM)如 OpenAI、Claude 和 OLLama 等进行交互,具备自动化安装 MCP 服务器、SSE 传输支持、自动选择服务器、聊天记录管理等功能。
277 15
ChatMCP:基于 MCP 协议开发的 AI 聊天客户端,支持多语言和自动化安装 MCP 服务器
|
24天前
|
运维 监控 安全
HTTPS 证书自动化运维:HTTPS 证书管理系统之优势对比
本文详细介绍了一款功能强大的HTTPS证书管理系统,涵盖自动签发、更新、实时监控、部署一体化、自定义加密算法、集中管理和邮箱通知等功能。系统通过简化配置、智能引导、快速响应和多重防护等优势,确保企业和个人用户能高效、安全地管理证书,提升网站和应用的安全性。
|
2月前
|
人工智能 自然语言处理 JavaScript
Agent-E:基于 AutoGen 代理框架构建的 AI 浏览器自动化系统
Agent-E 是一个基于 AutoGen 代理框架构建的智能自动化系统,专注于浏览器内的自动化操作。它能够执行多种复杂任务,如填写表单、搜索和排序电商产品、定位网页内容等,从而提高在线效率,减少重复劳动。本文将详细介绍 Agent-E 的功能、技术原理以及如何运行该系统。
167 5
Agent-E:基于 AutoGen 代理框架构建的 AI 浏览器自动化系统
|
2月前
|
运维 Ubuntu 应用服务中间件
自动化运维之路:使用Ansible进行服务器管理
在现代IT基础设施中,自动化运维已成为提高效率和可靠性的关键。本文将引导您通过使用Ansible这一强大的自动化工具来简化日常的服务器管理任务。我们将一起探索如何配置Ansible、编写Playbook以及执行自动化任务,旨在为读者提供一条清晰的路径,从而步入自动化运维的世界。
|
2月前
|
运维 网络安全 Python
自动化运维:使用Ansible实现批量服务器配置
在快速迭代的IT环境中,高效、可靠的服务器管理变得至关重要。本文将介绍如何使用Ansible这一强大的自动化工具,来简化和加速批量服务器配置过程。我们将从基础开始,逐步深入到更复杂的应用场景,确保即使是新手也能跟上节奏。文章将不包含代码示例,而是通过清晰的步骤和逻辑结构,引导读者理解自动化运维的核心概念及其在实际操作中的应用。

相关产品

  • 云服务器 ECS