使用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)
相关实践学习
通义万相文本绘图与人像美化
本解决方案展示了如何利用自研的通义万相AIGC技术在Web服务中实现先进的图像生成。
7天玩转云服务器
云服务器ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,可降低 IT 成本,提升运维效率。本课程手把手带你了解ECS、掌握基本操作、动手实操快照管理、镜像管理等。了解产品详情:&nbsp;https://www.aliyun.com/product/ecs
目录
相关文章
|
4月前
|
弹性计算 Devops Shell
用阿里云 DevOps Flow 实现 ECS 部署自动化:从准备到落地的完整指南
阿里云 DevOps Flow 是一款助力开发者实现自动化部署的高效工具,支持代码流水线构建、测试与部署至ECS实例,显著提升交付效率与稳定性。本文详解如何通过 Flow 自动部署 Bash 脚本至 ECS,涵盖环境准备、流水线搭建、源码接入、部署流程设计及结果验证,助你快速上手云上自动化运维。
429 0
|
5月前
|
运维 Prometheus 监控
3 年部署经验总结:用自动化工具轻松管理 300+ 服务器开源软件
三年前接手公司IT部门时,我满怀信心,却发现部署效率低下。尽管使用了GitLab、Jenkins、Zabbix等100+开源工具,部署仍耗时费力。文档厚重如百科,却难解实际困境。一次凌晨三点的加班让我下定决心改变现状。偶然看到一篇国外博客,介绍了自动化部署的高效方式,我深受启发。
256 0
|
3月前
|
弹性计算 人工智能 前端开发
在阿里云ECS上部署n8n自动化工作流:U2实例实战
本文介绍如何在阿里云ECS的u2i/u2a实例上部署开源工作流自动化平台n8n,利用Docker快速搭建并配置定时任务,实现如每日抓取MuleRun新AI Agent并推送通知等自动化流程。内容涵盖环境准备、安全组设置、实战案例与优化建议,助力高效构建低维护成本的自动化系统。
993 5
|
4月前
|
Ubuntu 安全 关系型数据库
安装MariaDB服务器流程介绍在Ubuntu 22.04系统上
至此, 您已经在 Ubuntu 22.04 系统上成功地完成了 MariadB 的标准部署流程,并且对其进行基础但重要地初步配置加固工作。通过以上简洁明快且实用性强大地操作流程, 您现在拥有一个待定制与使用地强大 SQL 数据库管理系统。
354 18
|
存储 Ubuntu Linux
HPE SPP 2025.09.00.00 - HPE 服务器固件、驱动程序和系统软件包 (Released Oct 2025)
HPE SPP 2025.09.00.00 - HPE 服务器固件、驱动程序和系统软件包
181 0
|
4月前
|
Ubuntu 安全 关系型数据库
安装MariaDB服务器流程介绍在Ubuntu 22.04系统上
至此, 您已经在 Ubuntu 22.04 系统上成功地完成了 MariadB 的标准部署流程,并且对其进行基础但重要地初步配置加固工作。通过以上简洁明快且实用性强大地操作流程, 您现在拥有一个待定制与使用地强大 SQL 数据库管理系统。
376 15
|
5月前
|
域名解析 运维 监控
阿里云轻量服务器的系统镜像和应用镜像的区别
轻量应用服务器是阿里云推出的易用型云服务器,支持一键部署、域名解析、安全管理和运维监控。本文介绍其系统镜像与应用镜像的区别及选择建议,助您根据业务需求和技术能力快速决策,实现高效部署。
|
5月前
|
存储 Linux 测试技术
HPE SPP 2025.07.00.00 - HPE 服务器固件、驱动程序和系统软件包
HPE SPP 2025.07.00.00 - HPE 服务器固件、驱动程序和系统软件包
231 4
|
6月前
|
监控 关系型数据库 数据库连接
FastAdmin系统框架通用操作平滑迁移到新服务器的详细步骤-优雅草卓伊凡
FastAdmin系统框架通用操作平滑迁移到新服务器的详细步骤-优雅草卓伊凡
234 3
FastAdmin系统框架通用操作平滑迁移到新服务器的详细步骤-优雅草卓伊凡

热门文章

最新文章

相关产品

  • 云服务器 ECS