GCP Cloud Monitoring

GCP Cloud Monitoring

Cloud Monitoring: Qwik Start | Google Cloud Skills Boost 자료는 https://cloud.google.com/monitoring/quickstart-lamp 의 내용을 기반으로 하였음.

차트 및 대시보드

Cloud Monitoring은 서비스 또는 사용 중인 Google Cloud 리소스의 측정값을 수집하고 시각화 할 수 있는 도구이다. 현재 서비스의 부하나 성능을 확인하려면 차트 및 대시보드 도구를 사용해야 한다. 이 차트 및 대시보드는 기본적으로 생성된 서비스나 리소스에 따라 자동으로 구성되지만 커스텀 대시보드를 생성해 원하는 지표를 선택해 표시할 수 있다.

Cloud Monitoring에서 어떤 지표가 있는지 궁금하다면 아래 문서들을 참고하면 된다.

이 외에도 Anthos, AWS, Istio, Knative, k8s, External에 대한 측정 항목도 확인 할 수 있다. 참고로 Monitoring/Logging Agent 측정 항목도 존재하는데 이는 Legacy Agent로 Ops-Agent 사용을 권장하고 있다.

CPU, Memory 등의 경우는 GCP 에서 측정하는 항목(하이퍼바이저)과 작업 에이전트(OS 레벨)에서 수집하는 정보가 다를 수 있다.

Cloud Monitoring에 사용되는 측정 항목에 대한 시계열은 아래와 같은 구조를 가진다.

"timeSeries": [ { "points": [ // 타임 스탬프 측정 값 { "interval": { "startTime": "2020-07-27T20:20:21.597143Z", "endTime": "2020-07-27T20:20:21.597143Z" }, "value": { "doubleValue": 0.473005 } }, { "interval": { "startTime": "2020-07-27T20:19:21.597239Z", "endTime": "2020-07-27T20:19:21.597239Z" }, "value": { "doubleValue": 0.473025 } }, ], "resource": { // 모니터링 되는 리소스 정보 "type": "gce_instance", "labels": { "instance_id": "2708613220420473591", "zone": "us-east1-b", "project_id": "sampleproject" } }, "metric": { // 리소스에서 무엇을 측정하는지에 대한 정보 "labels": { "device": "sda1", "state": "free" }, "type": "agent.googleapis.com/disk/percent_used" }, "metricKind": "GAUGE", // 측정 값 간의 관계 "valueType": "DOUBLE", },

위 시계열 중 metricKind는 아래 세 가지 값을 가질 수 있다.

  • GAUGE : 시간별 온도 처럼 특정 시점의 측정 값을 저장

  • CUMULATIVE : 차량의 주행 거리 처럼 특정 시점의 누적 값을 저장

  • DELTA : 주식 종목 요약처럼 지정된 기간 동안 측정 된 값의 변화량을 저장

valueType은 INT64, DOUBLE, BOOL, STRING, DISTRIBUTION 중 하나의 값을 가질 수 있다.

 

위 시계열 데이터를 시각화 한 것이 Cloud Monitoring의 대시보드이다.

이 외에도 측정 항목 탐색기를 사용해 확인할 수도 있다.

 

대시 보드를 생성하는 방법은 Cloud Console에서 직접 생성하거나 Monitoring API를 사용해 생성하는 방법이 있다. API를 사용하는 방식은 시간이 너무 오래 걸릴 수 있기 때문에 json으로 대시보드 정보를 관리하고 싶다면 Console로 대시 보드 생성 후 API로 대시 보드 정보를 내보내면 된다. 자세한 내용은 아래 문서들을 확인하면 된다.

대시보드 내보내기

대시보드 이름, 화면출력

# 대시보드 name $ gcloud monitoring dashboards list --format="json" | jq -r '.[].name' projects/00000000000/dashboards/15116bf5-7e26-4fa3-b792-0956ec7cb860 projects/00000000000/dashboards/1ad7a984-050f-448d-b63d-db936bc037ac projects/00000000000/dashboards/21be73e9-3d5b-48d7-9945-c08d05dbb203 projects/00000000000/dashboards/28132add-2fbd-43e4-9790-c1f531261a4c projects/00000000000/dashboards/28ea549d-59c9-4c6f-b99a-bac3dfbf6bb8 .... # displayName $ gcloud monitoring dashboards describe projects/00000000000/dashboards/15116bf5-7e26-4fa3-b792-0956ec7cb860 --format="json" | jq -r '.displayName' gw-filestore-monitoring-dev $ gcloud monitoring dashboards list --format="json" | jq '.[] | {name: .name, displayName: .displayName}' { "name": "projects/00000000000/dashboards/15116bf5-7e26-4fa3-b792-0956ec7cb860", "displayName": "gw-filestore-monitoring-dev" } { "name": "projects/00000000000/dashboards/1ad7a984-050f-448d-b63d-db936bc037ac", "displayName": "gw-redis-monitoring-dev" }

 

대시보드를 내보낼때는 Google Cloud Console, API, gcloud를 사용할 수 있다.

아래 순서로 진행하면 된다.

모니터링 → Monitoring 대시보드 → JSON EDITOR → 내용 복사

자세한 내용은 이 문서를 확인

API + Shell Script를 사용해 Cloud Monitoring 대시보드를 내보내기 위해서는 사용자 인증정보가 필요하기 때문에 oauth2l 설치해서 사용해야 한다.

https://github.com/google/oauth2l

설치하면 아래와 같은 명령어를 사용해 대시보드 정보를 가져올 수 있다.

oauth2l curl --scope cloud-platform --url https://monitoring.googleapis.com/v1/projects/00000000000/dashboards/e2b86b2a-24e4-4f64-84f0-25ada4ba9e1c -- -v

하지만 위 방법으로 대시보드 정보를 가져올 경우 표준출력을 이용할 수가 없다.(표준 출력 제어가 안됨.)

아래 명령어를 사용하면 대시보드 정보를 출력시킬 수 있다.

https://cloud.google.com/sdk/gcloud/reference/monitoring/dashboards/describe

대시보드가 많으면 아래와 같이 스크립트를 만들어 활용하면 된다.

mkdir ./dashboard dashboard_name_arr=(`gcloud monitoring dashboards list --format="json" | jq -r '.[].name' | tr '\n' ' '`) for dashboard_name in $dashboard_name_arr do display_name=(`gcloud monitoring dashboards describe $dashboard_name --format="json" | jq -r '.displayName' | tr ' ' '_'`) echo $display_name gcloud monitoring dashboards describe $dashboard_name --format="json" > ./dashboard/$display_name.json done

 

 

위처럼 대시보드를 json 형식으로 내보냈다면 해당 파일과 아래 명령어를 사용해 대시보드를 다시 생성할 수도 있다.

https://cloud.google.com/sdk/gcloud/reference/monitoring/dashboards/create

대시보드가 많아서 Cloud Storage에 백업해 두었다면 아래와 같이 스크립트를 생성해 일괄 생성할 수도 있다.

gsutil cp gs://sample-gw-backup-dev/monitoring/dashboards/monitoring_dashboards_20220215.zip ~/ unzip ~/monitoring_dashboards_20220215.zip dashboard_name_arr=(`ls ./monitoring_dashboards_20220215 | tr ' ' '_'`) file_path=(`pwd`) for dashboard_name in $dashboard_name_arr do cat ./monitoring_dashboards_20220215/$dashboard_name | sed '/"name"/d' | sed '/"etag"/d' | tee ./monitoring_dashboards_20220215/$dashboard_name > /dev/null gcloud monitoring dashboards create --config-from-file=$file_path/monitoring_dashboards_20220215/$dashboard_name done

agent 개요

https://cloud.google.com/monitoring/agent/ops-agent

예전에는 모니터링 agent, 로깅 agent 가 따로 있었지만 현재는 통합되어 ops agent 를 설치하면 모니터링, 로깅 둘다 지원함. 위 문서에서 로깅 기능, 모니터링 기능 확인

 

측정 세부항목

https://cloud.google.com/monitoring/api/metrics_opsagent

agent 설치

https://cloud.google.com/monitoring/agent/ops-agent/install-index

설치방법은 세가지가 있음.

  • Agent Policies(GCP에서 제공하는 관리 프로그램) 를 이용. 이 경우에는 사전에 OS 구성 agent 가 설치되어 있어야 한다.

  • 자동화 도구(Ansible, Chef, Puppet 등 이용)

  • VM에 수동설치. 패키지명은 google-cloud-ops-agent 임. 수동설치도 CLI 를 이용할 수도 있고 GCP console 의 Compute Engine 이나 Cloud Monitoring 의 VM 대시보드를 이용할 수 있다. 윈도우즈 agent는 UI에서 지원이 안된다.

https://cloud.google.com/stackdriver/docs/solutions/agents/ops-agent/installation

Linux 설치

curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh sudo bash add-google-cloud-ops-agent-repo.sh --also-install .... Setting up google-cloud-ops-agent (2.7.0~ubuntu20.04) ... Created symlink /etc/systemd/system/multi-user.target.wants/google-cloud-ops-agent.service → /lib/systemd/system/google-cloud-ops-agent.service. google-cloud-ops-agent installation succeeded.

 

windows 설치 (Powershell)

(New-Object Net.WebClient).DownloadFile("https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.ps1", "${env:UserProfile}\add-google-cloud-ops-agent-repo.ps1") Invoke-Expression "${env:UserProfile}\add-google-cloud-ops-agent-repo.ps1 -AlsoInstall"

작동 확인

> Get-Service google-cloud-ops-agent Status Name DisplayName ------ ---- ----------- Running google-cloud-op... Google Cloud Ops Agent

agent 설치 후 로그 탐색기에서 해당 VM의 로그를 확인할 수 있다.

JVM 설정

N-GW에서 모니터링 대상 중 하나인 WAS 서버에는 Java로 되어 있는 어플리케이션이 배포 되어 있다. 때문에 JVM에서 측정항목을 수집할 필요가 있다. 해당 내용에 대한 문서는 이 문서를 참고.

JVM에서 측정항목을 수집하기 위해서는 Ops-Agent 2.2.0 이상이 설치되어 있어야 한다.

JDK 1.5부터 모니터링을 위해 JMX라는 API를 제공한다. Ops-Agent는 이 JMX를 사용해 측정항목을 수집한다. JMX는 의 엔드포인트를 노출하려면 아래와 같은 시스템 속성들을 설정해야 한다.

  • com.sun.management.jmxremote.port

  • com.sun.management.jmxremote.rmi.port

  • java.rmi.server.hostname (원격으로 노출할 경우)

rmi.port의 값은 port의 값과 동일하게 설정해야 한다. 그리고 현재 구성하려는 것은 내부 Ops-Agent에서 JMX 엔드포인드에 접근하는 것이기 때문에 java.rmi.server.hostname은 설정할 필요가 없다.

JMX 엔드포인트를 설정했으면 Ops-Agent에서 위 API를 통해 정보를 수집하도록 설정해야한다.

sudo tee /etc/google-cloud-ops-agent/config.yaml > /dev/null << EOF metrics: receivers: jvm_metrics: type: jvm endpoint: localhost:9999 collection_interval: 60s service: pipelines: jvm_pipeline: receivers: - jvm_metrics EOF sudo service google-cloud-ops-agent restart

endpoint에 JMX 엔드포인트를 설정하면 된다. java.rmi.server.host를 설정하지 않았으면 localhost로 지정하고, port는 com.sun.management.jmxremote.port 값으로 지정한다. 자세한 수집 구성은 이 문서를 참고하면 된다.

 

리소스 그룹

모니터링할 리소스들을 그룹으로 묶어서 관리할 수 있다. 이렇게 그룹화 하면 모니터링이나 알림들을 그룹 단위로 설정할 수 있게 된다. 그룹은 하위 그룹으로 최대 6단계 까지 포함 시킬 수 있으며, 이 하위 그룹을 사용하면 물리적/논리적 토폴리지를 관리할 수 있어 프로덕션 리소스 모니터링과 개발 리소스 모니터링을 쉽게 분리할 수 있다.

그룹을 만들면 Monitoring에서 그룹에 대한 대시보드를 만들어 확인할 수 있다. 그룹 대시보드의 경우 표준 대시보드 기준외에 그룹에 대한 기능을 추가로 제공한다. - https://cloud.google.com/monitoring/groups#using_groups

  • 그룹 수정/삭제

  • 그룹 종속 알림 정책 관리

  • 하위그룹 생성

  • 이슈/이벤트 확인

  • 그룹 리소스 확인 및 액세스

 

그룹 기준은 이름, 태그, 리전, 보안그룹, Cloud 계정 및 프로젝트, App Engine 앱, App Engine 서비스 등으로 나눌 수 있다. 이 중에서 선택해서 기준을 만들 수 있으며 한 그룹안에 여러 기준을 포함 시킬 수 있다.

만약에 기준으로 이름이나 태그를 선택할 경우 연산자를 선택해야한다.

  • 이름 선택시 연산자

  • 태그 선택시 연산자

이 그룹은 projects.groups API를 사용해 생성,수정,검색,삭제 등의 작업을 수행할 수 있지만, API를 사용해 만든 그룹은 UI에서 수정이 불가능하다.

참고로 그룹과 업타임 체크는 SDK로 제공하지 않는 것으로 보임.

 

가동시간 확인 및 알림 정책 만들기

업타임 체크

알림채널

알림채널로는 Mobile, PagerDuty, Slack, Webhooks, Email, SMS, Cloud Pub/Sub이 있다.

 

 

https://cloud.google.com/monitoring/alerts/using-channels-api#api-list-channels

API 이용하여 알림채널 추가하기. yaml 형태로 파일 작성.

$ cat <<EOF > channel-tjmoon.yaml displayName: tjmoon-email labels: email_address: tjmoon@samplecorp.com type: email EOF $ gcloud beta monitoring channels create --channel-content-from-file="channel-tjmoon.yaml"

메일 알림 채널은 그룹 메일도 설정 가능하다.

 

알림채널 google chat 연동하기

google chat 연동은 잘 사용하지 않기 때문에 slack 연동을 추천

알림채널 Slack 연동하기

알림정책

측정항목을 기준으로 알림 정책을 생성할 수 있다. 알림 정책에서 지정한 기준을 초과하면 정책 생성 시 지정한 알림 채널을 통해 알림 메세지를 보낸다.

알림 정책은 Google Cloud Console에서 쉽게 생성할 수 있다. API와 CLI로도 가능하지만 사전에 알림 정책을 정의해둔 파일을 가지고 있지 않다면 그냥 Cloud Console을 사용할 것을 권장.

Cloud Console로 알림 정책 관리

API 및 CLI로 알림 정책 관리

만약에 생성한 알림 정책을 파일로 백업해 보관하고 있다면 아래처럼 Script를 사용해 복구할 수 있다.

gsutil cp gs://sample-gw-backup-dev/monitoring/notification_policy/notification_policy_20220210.zip ./ unzip ./notification_policy_20220210.zip notification_policy_arr=(`ls ./notification_policy_20220210 | tr ' ' '_'`) file_path=(`pwd`) for notification_policy in $notification_policy_arr do cat ./notification_policy_20220210/$notification_policy | sed "s/sample-gw-dev-324106/sample-gw-prod/" | jq 'del(.name)' | jq 'del(.conditions[].name)' | jq 'del(.documentation)' | jq 'del(.notificationChannels[])' | jq 'del(.creationRecord)' | jq 'del(.mutationRecord)' | tee ./notification_policy_20220210/$notification_policy > /dev/null gcloud alpha monitoring policies create --policy-from-file=$file_path/notification_policy_20220210/$notification_policy done

로그 보기

Cloud Logging에서 로그 보면 됨.

메트릭

참고

Monitoring 코드 샘플 - https://cloud.google.com/monitoring/docs/samples