×
Community Blog CloudMonitor Alert + Function Compute to Slack

CloudMonitor Alert + Function Compute to Slack

본 블로그는 알리바바 클라우드의 파트너인 메가존의 정지훈 매니저가 작성한 내용입니다.

1

Overview

알리바바 클라우드의 CloudMonitor(CMS)에서 Slack Webhook을 지원하기 이전에는 CMS에서 Function Compute를 연동하여 Function Compute에서 Slack으로 Webhook을 발생시켜 알람을 받을 수 있었습니다. 현재는 CMS에서 Webhook을 정식지원하기 때문에 굳이 Function Compute를 연동하여 사용할 필요가 없지만, CMS에서 Slack으로 다이렉트 Webhook을 통한 알람이 가독성이 그리 좋지 못한 관계로 Function Compute에서 CMS 메시지를 보기 좋게 수정하여 전달 할 수 있습니다.

Detail

  • Create Slack App (생략)
  • Function Compute Setting
  • Function Compute Code
  • Alibaba Cloud - Cloud Monitor Setting (수정)

Create Slack App

이전 글에서 Slack App을 구성한 것을 그대로 사용할 예정입니다. Slack App 설정은 [[CloudMonitor] Alibaba Cloud CloudMonitor Alert to Slack](https://room-nine.tistory.com/entry/CloudMonitor-Alibaba-Cloud-CloudMonitor-Alert-to-Slack "[CloudMonitor] Alibaba Cloud CloudMonitor Alert to Slack") 해당 글의 Create Slack App 부분을 참조 하시길 바랍니다.

Function Compute Settting

CMS에서 발생한 메트릭 / 이벤트를 Function Compute에서 처리 할 수 있도록 구성 합니다.

[Function Compute] - [Services & Functions] 메뉴에서 서비스를 생성해 줍니다.

2

위와 같이 Service를 생성 이후에 내부에 Functions 를 생성합니다.

> [Basic Settings]

3

Function Name을 지정해주고 Handler Type을 HTTP Handler 로 설정합니다.

> [Code]

4

> [Advanced Setting]

해당 설정에서는 별도의 설정은 필요 없습니다.

5

> [Enviroment Variables]

몇개의 환경변수 설정이 필요합니다.
JSON 형식으로 변경하여 아래의 환경 변수를 적용합니다.

{ 
"LD_LIBRARY_PATH": "/code/.fun/root/usr/local/lib:/code/.fun/root/usr/lib:/code/.fun/root/usr/lib/x86_64-linux-gnu:/code/.fun/root/usr/lib64:/code/.fun/root/lib:/code/.fun/root/lib/x86_64-linux-gnu:/code/.fun/root/python/lib/python2.7/site-packages:/code/.fun/root/python/lib/python3.6/site-packages:/code:/code/lib:/usr/local/lib", 
"NODE_PATH": "/code/node_modules:/usr/local/lib/node_modules", 
"PATH": "/code/.fun/root/usr/local/bin:/code/.fun/root/usr/local/sbin:/code/.fun/root/usr/bin:/code/.fun/root/usr/sbin:/code/.fun/root/sbin:/code/.fun/root/bin:/code:/code/node_modules/.bin:/code/.fun/python/bin:/code/.fun/node_modules/.bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/sbin:/bin", 
"PYTHONUSERBASE": "/code/.fun/python" 
}

6

> [Trigger Configurations]

Request Method 값은 POST를 제외하고 나머지는 제거 해도 동작에 문제가 없습니다.

7

Create 눌러 Function 생성을 진행 합니다.

Function Compute Code

우선 기본적인 코드는 아래와 같습니다.

import logging
import requests
import json
import urllib.parse

_# Pretty-print and properly escape the JSON_
_# text passed to us by CloudMonitor, so that_
_# we can display it in Slack_
def pprint_json(leading_char, parsed_json):
    output_text = '\n'

    for key in parsed_json:
        item = parsed_json[key]

        if isinstance(item, dict): _# We need to go deeper!_
            output_text += key + ':'
            output_text += pprint_json(leading_char + '\t', item)
        else:
            output_text += "{}{}: {}\n".format(leading_char, key, item)
    return output_text

_# Main function (called the "handler": takes JSON_
_# from CloudMonitor callbacks and sends it on to_
_# Slack as (nicely?) formatted text_
def handler(environ, start_response):
    logger = logging.getLogger()

    context = environ['fc.context']
    request_uri = environ['fc.request_uri']


_# This code does nothing, but is left in_
_# as an example of how you *could* process_
_# request parameters. We don't use it as we are only_
_# interested in the request body, not parameters._
    for k, v in environ.items():
        if k.startswith('HTTP_'):
        _# process custom request headers_
        pass

_# Determine size of request body, if it is zero we exit here: there's no need_
_# to call the Slack webhook_

    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0
        err = "Request body size was zero, exiting"
        logger.info(err)
        return [err.encode()]

_# Unpack and parse the CloudMonitor request body: we will exit with an_
_# error if we encounter any issues here_
    try:
        request_body = environ['wsgi.input'].read(request_body_size)
        request_body_string = urllib.parse.unquote(request_body.decode())
        request_body_json = urllib.parse.parse_qs(request_body_string)
        output = pprint_json('', request_body_json)
    except:
        err = "Something went wrong processing the request body. Check your Function Compute logs."
        logger.info(err)
        return [err.encode()]


_# Log contents of output here, to help us determine if any issues_
_# were encountered_

    logger.info(output)

_# URL of the Slack webhook_
    end_url = '슬랙 Webhook Applicaion URL 입력'
    headers = {'Content-type': 'application/json'}

_# Deal with the possibility of an empty output_
    if output.strip() == '' or len(output) == 0:
        output = "CloudMonitor sent an empty notification. Check your logs."

_# Send message to slack_
    payload = {'text': output}
    r = requests.post(end_url, headers=headers, data=json.dumps(payload))

_# Send response (to indicate that the function has run successfully)_
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)

_# Output formatted text for debugging purposes_
    return [output.encode()]
    

여기서 Payload 부분에서 원하는 형식을 지정하여 해당 Payload 값을 담아 슬랙으로 호출하게 됩니다. Payload 구성을 볼 수 있는 사이트를 슬랙에서 제공하고 있습니다. 슬랙에서 제공하고 있는 Block kit Builder를 이용하여 슬랙으로 보낼 Payload 형식을 미리 구성해서 볼 수 있습니다.

https://app.slack.com/block-kit-builder

8

Block 형식이 적용된 Slack 얼럿 양식

Alibaba Cloud - Cloud Monitor Setting (수정)

[Alert Contacts] 에서 Webhook 주소를 Slack App 주소로 설정하였지만, 해당 글에서는 해당 얼럿 발생을 사용하지 않고 CMS에서 발생한 이벤트 / 메트릭을 Function Compute로 보내줘야합니다.

Set up an Event-based Alarm Rule

[CMS] - [Event Monitoring] - [System Event] - [Event-triggered Alert Rules] 에서 얼럿 룰 생성

9
10
11

ECS를 대상으로 선택하고 해당 룰을 Function Compute 에서 만든 Function으로 보내주면 됩니다.

Set Up A Metric-based Alarm Rule

기존 CMS의 Rule 세팅과 동일하게 진행하되 [Alerts] - [Alert Contacts] 에서 Webhook 주소를 cm-metric Function의 HTTP POST 트리거 URL을 넣어 줍니다.

12

Internet Endpoint 뒤에 Function 명을 넣어 Webhook 주소로 입력해 줍니다.

13

Test 버튼을 눌러 테스트를 해보면 Function Compute로 메트릭이 넘어가고, 이후 Function Compute Code에 설정된 Slack App 주소로 해당 메트릭을 전달하여 테스트 메시지를 확인해 볼 수 있습니다.

14

Slack으로 CMS의 메시지를 전달하는 2가지 방법에 대해 확인했습니다. 다만 해당 글은 처음에 Slack Webhook을 통한 메시지가 가독성이 떨어져 커스터마이징을 위한 Function Compute를 거쳐 CMS 메시지를 발송하는 방법도 알아보았는데, 현재는 CMS에서 보내는 모든 메트릭을 가져오게 되므로 사실 Alibaba Cloud 에서 지원하는 방법과 비교했을때 더 가독성이 떨어집니다. 필요한 데이터만 가져올 수 있는 방법을 찾게되면 추가 포스팅 진행 하겠습니다.

1 2 1
Share on

JJ Lim

21 posts | 4 followers

You may also like

Comments

Dikky Ryan Pratama June 26, 2023 at 12:43 am

Awesome!

JJ Lim

21 posts | 4 followers

Related Products