函數計算自動化運維實戰 2 -- 事件觸發 eip 自動轉移

函數計算

阿里雲函數計算是一個事件驅動的全託管計算服務。經過函數計算,您無需管理服務器等基礎設施,只需編寫代碼並上傳。函數計算會爲您準備好計算資源,以彈性、可靠的方式運行您的代碼,並提供日誌查詢,性能監控,報警等功能。藉助於函數計算,您能夠快速構建任何類型的應用和服務,無需管理和運維。更棒的是,您只須要爲代碼實際運行消耗的資源付費,而代碼未運行則不產生費用。html

雲監控

阿里雲雲監控爲雲上用戶提供開箱即用的企業級開放型一站式監控解決方案。涵蓋IT設施基礎監控,外網網絡質量撥測監控,基於事件、自定義指標、日誌的業務監控。爲您全方位提供更高效、更全面、更省錢的監控服務。json

雲監控提供了豐富事件,而且事件還在不斷豐富中(雲產品系統事件監控), 豐富的事件觸發自定義處理的函數,能夠實現更加完美的的自動化運維。api

專題傳送門 => 函數計算進行自動化運維專題

示例場景

假設兩臺 ECS 機器 A, B, A 機器出現了宕機,這個時候須要把 A 機器上的 eip 遷移到備用機器 B 上,這個利用雲監控的報警和函數計算能夠實現 EIP 的自動遷移, 雲監控檢測到 A 宕機這個事件,而後觸發函數執行,函數實現 eip 的自動遷移服務器

操做步驟

注:記得給函數的 service 的 role 設置操做 ecs 和 eip 的權限微信

1

2

3

4

  • mock調試

5

6

7

代碼

# -*- coding: utf-8 -*-
import logging
import json, random, string, time
from aliyunsdkcore import client
from aliyunsdkvpc.request.v20160428.AssociateEipAddressRequest import AssociateEipAddressRequest
from aliyunsdkvpc.request.v20160428.UnassociateEipAddressRequest import UnassociateEipAddressRequest
from aliyunsdkvpc.request.v20160428.DescribeEipAddressesRequest import DescribeEipAddressesRequest
from aliyunsdkcore.auth.credentials import StsTokenCredential
LOGGER = logging.getLogger()
clt = None
def handler(event, context):
  creds = context.credentials
  sts_token_credential = StsTokenCredential(creds.access_key_id, creds.access_key_secret, creds.security_token)
  '''
  {
    "product": "ECS",
    "content": {
        "executeFinishTime": "2018-06-08T01:25:37Z",
        "executeStartTime": "2018-06-08T01:23:37Z",
        "ecsInstanceName": "timewarp",
        "eventId": "e-t4nhcpqcu8fqushpn3mm",
        "eventType": "InstanceFailure.Reboot",
        "ecsInstanceId": "i-bp18l0uopocfc98xxxx" 
    },
    "resourceId": "acs:ecs:cn-hangzhou:123456789:instance/i-bp18l0uopocfc98xxxx",
    "level": "CRITICAL",
    "instanceName": "instanceName",
    "status": "Executing",
    "name": "Instance:SystemFailure.Reboot:Executing", 
    "regionId": "cn-hangzhou"
  }
  '''
  evt = json.loads(event)
  content = evt.get("content");
  ecsInstanceId = content.get("ecsInstanceId");
  regionId = evt.get("regionId");
  
  global clt
  clt = client.AcsClient(region_id=regionId, credential=sts_token_credential)
  
  name = evt.get("name");
  eipId = "eip-bp1nexxxc7zjfnex6i0";
  standbyEcsId = "i-bp19yycxx7yroukxpv"
  name = name.lower()
  
  if name in ['Disk:Stalled:Executing'.lower(), 'Instance:SystemFailure.Reboot:Executing'.lower(), "Instance:InstanceFailure.Reboot:Executing".lower()]:
    print("move eip to standbyEcs");
    move_eip(ecsInstanceId, standbyEcsId, eipId) # move eip to standbyEcs
  else:
    # other event to do 
    pass
  
def getEipStatus(eip):
  request = DescribeEipAddressesRequest()
  request.set_AllocationId(eip)
  request.add_query_param("RegionId", "cn-hangzhou")
  response = _send_request(request)
  if isinstance(response, dict) and "RequestId" in response:
    EipAddresses = response.get('EipAddresses', {})
    EipAddress = EipAddresses['EipAddress'][0]
    status = EipAddress['Status']
    return status
  else:
    LOGGER.error("getEipAddressDesc {} fail".format(eip))
def unAssociateEip(ecs_id, eip):
  request = UnassociateEipAddressRequest()
  request.set_AllocationId(eip)
  request.set_InstanceType('EcsInstance')
  request.set_InstanceId(ecs_id)
  response = _send_request(request)
  if isinstance(response, dict) and "RequestId" in response:
    LOGGER.info("UnassociateEipAddress {} from {} succ".format(ecs_id, eip))
  else:
    LOGGER.error("UnassociateEipAddress {} from {} fail".format(ecs_id, eip))
def associateEip(ecs_id, eip):
  associte_request = AssociateEipAddressRequest()
  associte_request.set_AllocationId(eip)
  associte_request.set_InstanceType('EcsInstance')
  associte_request.set_InstanceId(ecs_id)
  associte_response = _send_request(associte_request)
  if isinstance(associte_response, dict) and "RequestId" in associte_response:
    LOGGER.info("AssociateEipAddress {} to {} succ".format(eip, ecs_id))
    return True
  return False
def move_eip(from_ecs, to_ecs, eip):
  unAssociateEip(from_ecs, eip)
  # wait unAssociateEip ...
  time.sleep(3)
  # retry 30s util sucess
  for i in xrange(10):
    eip_status = getEipStatus(eip).lower()
    if eip_status == 'available':
      if associateEip(to_ecs, eip):
        LOGGER.info("AssociateEipAddress {} to {} succ".format(eip, to_ecs))
        return
    else:
      LOGGER.info("eip status = {}".format(eip_status))
      time.sleep(3)
  LOGGER.info("AssociateEipAddress {} to {} fail".format(eip, to_ecs))
# send open api request
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action_with_exception(request)
        LOGGER.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        LOGGER.error(e)

「阿里巴巴雲原生微信公衆號(ID:Alicloudnative)關注微服務、Serverless、容器、Service Mesh 等技術領域、聚焦雲原生流行技術趨勢、雲原生大規模的落地實踐,作最懂雲原生開發者的技術公衆號。」網絡

相關文章
相關標籤/搜索