티스토리 뷰

DevOps

GCP Monitoring Mattermost Notification

kingsubin 2023. 5. 12. 19:36

Notification Channel

참조: https://cloud.google.com/monitoring/support/notification-options

 

알림 채널 만들기 및 관리  |  Cloud Monitoring  |  Google Cloud

Google Cloud 콘솔에서 Cloud Monitoring 알림 정책을 사용하여 알림 채널을 구성하는 방법을 알아봅니다.

cloud.google.com

 

Notification Channel 추가
먼저 이메일을 추가해 줬다. 근데 문서를 보면 여러 알림 채널을 권장하고 있다. (We recommend that you create multiple notification channels for redundancy purposes.)
사내메신저로 사용하고 있는 mattermost 를 추가해야겠다. 근데 따로 지원하지 않아서 Pub/Sub 을 사용해야 한다.


Pub/Sub 알림 채널 구성

service account 확인
첫 번째 알림 채널을 추가하면 Cloud Monitoring 이 서비스 계정을 만들고 Monitoring Notification Service Agent 를 부여한다.

 

service account format:
service-PROJECT_NUMBER@gcp-sa-monitoring-notification.iam.gserviceaccount.com

 

topic 생성
Pub/Sub 에서 monitoring-notification 이라는 topic 을 생성해 준다.

 

service account 권한 부여
Notification Channel 에서 Pub/Sub 을 추가하려고 하면 메시지가 뜬다.

 

알림 서비스 계정이 Pub/Sub 토픽에 publish 할 권한이 필요하다.
특정 토픽이 아니라 모든 토픽에 접근하려면 IAM 에서 서비스 계정에 Pub/Sub Publisher 권한을 주면 된다.

 

권한 부여가 완료되면 Pub/Sub 채널을 추가해 준다.


Cloud Run

토픽을 구독하여 mattermost 에 메시지를 보내는 서비스를 만들어보자.
Cloud Functions 와 Cloud Run 선택지가 2개 있었는데 Cloud Functions 의 경우에는 보지 않은 CloudEvent 사양을 봐야 해서 번거로웠고 Cloud Run 을 주로 사용하고 있어서 Cloud Run 을 선택했다.

 

환경설정
먼저 mattermost API 를 참조해서 메시지를 보낼 때 필요한 authorization token, channel id 을 가져온다.
cloud run 설정에서 secret manager 를 사용할 수도 있는데 일단 environment variables 를 추가해서 사용하겠다.

const CHANNEL_ID = process.env.mattermostChannelId;  
const AUTH_TOKEN = process.env.mattermostAuthToken;

 

mattermost message 보내기
스키마를 PubsubMessage, monitoring notification 보고 잘 조작해서 메시지를 만들자.

request 에서 PubsubMessage 를 벗기고 incident 객체만 뽑아낸다.

const { incident } = JSON.parse(  
    Buffer.from(requestBody.message.data, 'base64').toString(),  
);

 

incident 객체 안을 보면 정보가 많은데 일단 condition_name, scoping_project_id, state, started_at, ended_at, summary 만 뽑아서 사용해 보겠다.

 

started_at, ended_at 을 보면 epoch time 으로 들어와서 보기 쉽게 KST 로 바꿔주는 함수를 만들어준다.

const KST_OFFSET = 9 * 60 * 60 * 1000;
const convertEpochToKST = (epochTime) => {  
    return new Date(epochTime * 1000 + KST_OFFSET).toISOString();  
};

 

mattermost 에 보낼 메시지를 만든다.
mattermost message format 을 참조하면 더 이쁘게 만들 수 있다.

const message = `  
#### 🚨 ${incident.condition_name}  
- **project:** \`${incident.scoping_project_id}\`  
- **state:** \`${incident.state}\`  
- **started_at:** \`${convertEpochToKST(incident.started_at)}\`  
- **ended_at:** \`${  
incident.ended_at ? convertEpochToKST(incident.ended_at) : null  
}\`  
- **summary:** \`${incident.summary}\`  
`;

 

메시지를 보낸다.

const body = JSON.stringify({  
    channel_id: CHANNEL_ID,  
    message,  
}, null, 2);

await fetch(URL, {  
    method: 'POST',  
    headers: {  
        'Content-Type': 'application/json',  
        Authorization: `Bearer ${AUTH_TOKEN}`,  
    },  
    body,  
});

 

build, deploy
Dockerfile 을 만들고 빌드하여 registry 에 올리고 배포해 준다.
gcloud builds submit --tag IMAGE_URL
gcloud run deploy SERVICE --image IMAGE_URL


테스트

subscription
이전에 만든 monitoring-notification topic 을 subscribe 하는 subscription 을 만들자.
delivery type push 로 하고 endpoint url 에 위에서 만든 cloud run url 을 적어준다.

 

alerting policy
테스트를 위해 무조건 발생하는 policy 를 만들어준다.
나는 database cpu utilization 으로 선택하고 Threshold 를 5 로 해서 만들었다.

 

메시지 확인

이메일에 알림이 오고 mattermost 를 봐도 메시지가 잘 오는 걸 확인할 수 있다.

 

 

 

 

'DevOps' 카테고리의 다른 글

Linux 기초 명령어 모음  (0) 2024.03.03
Github Actions self-hosted runners  (1) 2023.06.03
ubuntu server 설정  (3) 2023.04.09
AWS GCP 도메인 이전  (0) 2023.01.04
Google Cloud Translation API detect confidence  (0) 2022.09.24