星期六, 1月 11, 2020

使用 Google Stackdriver Monitoring API Python Samples 監控 過去一週 CPU 小於 20% VM小記

20191229

使用 Google Stackdriver Monitoring API Python Samples 監控 過去一週 CPU 小於 20% VM小記

OS: container with openSUSE Leap 15.1

今天要來嘗試使用 Stackdriver monitor API 透過 python 列出過去一週 CPU 小於 20 % 的 VM

環境使用之前建立好的 openSUSE Leap 15.1, 上面已經安裝好雲端的工具

==== 在主機上面 ====

啟動 container

> docker  run  -v  ~/.aws:/root/.aws -v  ~/.azure:/root/.azure  -v ~/.config/gcloud:/root/.config/gcloud  -v  ~/.ssh:/root/.ssh  -it  sakana/ansible_opensuse151  /bin/bash

==== 在 container 內 ====

在這邊使用服務帳戶的方式來處理, 所以要先建立服務帳戶

建立的方式有 2 種

==== 1. GCP Console 方式 ====

登入 GCP console

點選 導覽選單 -- > IAM 與管理 -- > 服務帳戶 

點選 建立服務帳戶


輸入帳戶名稱 -- > 建立

角色的部分選取 監控/Monitoring 管理員  -- > 繼續


點選 建立金鑰

選取金鑰類型, 這邊我選 JSON  -- > 建立


下載金鑰到本機

點選 完成
完成服務帳號建立以及金鑰建立

==== 2. 指令方式 ====

參考官方網頁

建立服務帳戶

# gcloud iam service-accounts create test20200111 --project  YOUR_PROJECT_ID

  • test20200111 是服務帳戶名稱
  • YOUR_PROJECT_ID 請換成自己的 project id

向服務帳戶授予權限

用您的專案 ID 取代 [PROJECT_ID]
#gcloud  projects  add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/monitoring.admin"

  • 所以這邊可以觀察到 監控管理員的權限是綁定在 project
  • roles/monitoring.admin 是觀察來的, 可以透過 #gcloud  projects  get-iam-policy [PROJECT_ID] 來看相關的權限

另外網路上也有看到找出服務帳戶 Role 的過濾方式

# gcloud projects get-iam-policy [PROJECT_ID] --flatten="bindings[].members" --filter="bindings.members:[NAME]@[PROJECT_ID].iam.gserviceaccount.com"

---
bindings:
  members: serviceAccount:sakanatest-20200111-monitor@xxxxxxx.iam.gserviceaccount.com
  role: roles/monitoring.admin
etag: BwWb1FtLJ4s=
version: 1

產生金鑰檔案

用金鑰檔案的名稱取代 [FILE_NAME]
#gcloud  iam  service-accounts  keys  create  [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

created key [5abac9d47cd2g96386a05bad735d241d59a00897] of type [json] as [/root/test20200111.json] for [test20200111@xxxxxxxxx.iam.gserviceaccount.com]

  • 用指令的好處是可以直接指定憑證的位置, 我在下指令的時候是用 /root/test20200111.json

=================================

服務帳戶與金鑰準備好了之後, 接下來就是取得範例程式


更動的部分如下 ( 使用 diff 指令, 左邊是改寫, 右邊是 google 原來的範例 )

> diff snippets.py snippets-orig.py 

14,18d13
< # 
< # Edit by Max 2020/1/11
< # 因應工作需求, 改寫 snippets.py
< # File from https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/monitoring/api/v3/cloud-client
119,130d113
< # 改寫 list_time_series_aggregate
< # 
< # 這邊定義要查詢的區間
< query_time = input("Please input your query time in seconds, for example, 7 Days is 604800:  ") or 604800
< query_time_int=int(query_time) # 這邊將 query_time type 從 str 轉型為 int
< print("")
< cpu_threshold = input("Please input cpu usage under threshold, like 0.2 for 20%:  ") or 0.2
< cpu_threshold_float = float(cpu_threshold)
< print("")
140c123
<     interval.start_time.seconds = int(now - query_time_int) # 這邊用 query_time 來彈性調整
---
>     interval.start_time.seconds = int(now - 3600)
143c126
<     aggregation.alignment_period.seconds = query_time_int  # 這邊用 query_time 來彈性調整
---
>     aggregation.alignment_period.seconds = 1200  # 20 minutes
154,160c137
<       cpuUtil = result.points[0].value.double_value
<       if cpuUtil < cpu_threshold_float: #需要判斷的 CPU threshold, 用 cpu_threshold 來彈性調整
<           print("instance name:", result.metric.labels) # 列出 instance 名稱
<           # instance_id 是放在 resource.labels 下, 以字典的方式儲存, 所以透過 ['KEY_NAME'] 取出
<           print("instance id:", result.resource.labels['instance_id']) # 列出 instance id 來區別同樣名稱的 VM
<           print("CPU utilization:", cpuUtil *100, "% \n") # 列出 cpu 使用量
<     # print(result) 註解原來的方式
---
>         print(result)

接下來設定應用程式驗證作業需要的環境變數

定義 project , 請帶入自己 project ID
# export  GOOGLE_CLOUD_PROJECT=[PROJECT_ID]

定義剛剛的 json 檔案的路徑, 例如 /root/test20200111.json
# export GOOGLE_APPLICATION_CREDENTIALS="[path/key-name.json]"


確認有定義完成

# echo  $GOOGLE_CLOUD_PROJECT
# echo  $GOOGLE_APPLICATION_CREDENTIALS

使用 pip 安裝 python 相依性的套件
# pip  install  -r  requirements.txt

執行剛剛下載修改的 snippet.py

# python3  snippets.py  list-time-series-aggregate

Please input your query time in seconds, for example, 7 Days is 604800:  604800

Please input cpu usage under threshold, like 0.2 for 20%:  0.3

instance name: {'instance_name': 'test'}
instance id: 3255911329394624968
CPU utilization: 17.11500122 % 

instance name: {'instance_name': 'test2'}
instance id: 3713200083697575388
CPU utilization: 0.6797669215641027 % 

instance name: {'instance_name': 'test'}
instance id: 8590409858061083796
CPU utilization: 0.6412688036029409 % 

  • 這邊我改成互動的方式, 輸入要查詢的區間, 使用秒數爲單位
  • 輸入CPU 使用量的門檻值, 如果要列出 20% 以下就輸入 0.2

這樣就可以列出過去一週 CPU 小於 20 % 的 VM :)

另外補充, 當服務帳戶刪除的時候, 剛 members 與 Roles 還是在 project 上面, 所以要記得移除權限

例如
# gcloud projects remove-iam-policy-binding [PROJECT_ID] --member=serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com --role=roles/monitoring.admin

這樣又朝向 GCP 邁進一步

~ enjoy  it

Reference

星期日, 1月 05, 2020

三大雲平台工具容器升級小記 - 使用 python 3 with openSUSE Leap 15.1 Container

三大雲平台工具容器升級小記 - 使用 python 3  with openSUSE Leap 15.1 Container

OS: container with openSUSE Leap 15.1

上次升級是 2019/11/16 , 這次會來升級的原因是 
  • Google SDK 已經GA 支援 python 3,  274.0.0 以後的版本就支援 Python 3
  • awscli 使用 python 3 來安裝
  • Ansible with azure 使用 pip3 安裝

先整理結果

升級前
OS: openSUSE Leap 15.1
awscli:  aws-cli/1.16.282 Python/2.7.14
gcloud: Google Cloud SDK 271.0.0
azure-cli: 2.0.76

升級後
OS: openSUSE Leap 15.1
awscli:  aws-cli/1.16.310 Python/3.6.9
gcloud: Google Cloud SDK 274.0.1
azure-cli: 2.0.78

這次的做法還是會透過 docker build 指令來進行
  • 我有比較過 docker build 以及使用現有的 docker image 修改後再使用 docker commit 建立的 image 大小還是很有差異的

Dockerfile 的部分我是拿之前 openSUSE Leap 15.1 來修改

實際上只有修改
  • Update time
  • 使用 pip3 安裝 ansible[azure]
  • 使用 pip3 安裝 awscli
  • Google SDK 版本還有下載的檔案路徑以及檔案名稱


列出 diff 的結果給大家參考

> diff opensuseLeap151_ansible_Dockerfile opensuseLeap151_ansible_20200105_Dockerfile 

6c6
< # update: 20191122
---
> # update: 20200105
10,12c10,12
< RUN zypper install -y python2-pip && \
<   pip2 install --upgrade pip && \
<   pip2 install ansible[azure]
---
> RUN zypper install -y python3-pip && \
>   pip3 install --upgrade pip && \
>   pip3 install ansible[azure]
45c45
< RUN pip install awscli
---
> RUN pip3 install awscli
49c49
< # Install google cloud SDK 271
---
> # Install google cloud SDK 274.0.1
51,52c51,52
< RUN wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-271.0.0-linux-x86_64.tar.gz && \
<   tar zxvf google-cloud-sdk-271.0.0-linux-x86_64.tar.gz && \
---
> RUN wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-274.0.1-linux-x86_64.tar.gz && \
>   tar zxvf google-cloud-sdk-274.0.1-linux-x86_64.tar.gz && \




Dockerfile 內容如下

# openSUSE Leap 15.1 with ansible, azure-cli
FROM opensuse/leap:15.1

# Author
# MAINTAINER 已經棄用, 之後要使用 LABEL 方式
# update: 20200105
LABEL maintainer="sakana@cycu.org.tw"

# Install python2-pip, upgrade pip, ansible[azure]
RUN zypper install -y python3-pip && \
  pip3 install --upgrade pip && \
  pip3 install ansible[azure]

# Install openssh, set ls alias
RUN zypper install -y openssh
RUN echo "alias ls='ls --color=tty'" >> /root/.bashrc

# Install wget, download azure_rm.py, set permission
RUN zypper install -y wget && \
  wget  https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/azure_rm.py && \
  chmod a+x azure_rm.py && \
  mv azure_rm.py /root

# Create working directory in /root
RUN mkdir /root/.azure && \
  mkdir /root/.aws && \
  mkdir /root/playbook && \
  mkdir -p /root/.config/gcloud && \
  wget https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/template/ansible.cfg && \
  mv /ansible.cfg /root && \
  wget https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/template/hosts && \
  mv /hosts /root

# Install azure-cli
RUN zypper install -y curl && \
  rpm --import https://packages.microsoft.com/keys/microsoft.asc && \
  zypper addrepo --name 'Azure CLI' --check https://packages.microsoft.com/yumrepos/azure-cli azure-cli && \
  zypper install --from azure-cli -y azure-cli

#install vim tar gzip jq
RUN zypper install -y vim tar gzip jq
RUN echo "set encoding=utf8" > /root/.vimrc

# Install awscli
RUN pip3 install awscli
RUN echo "source /usr/bin/aws_bash_completer" >> /root/.bashrc


# Install google cloud SDK 274.0.1
ENV CLOUDSDK_CORE_DISABLE_PROMPTS 1
RUN wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-274.0.1-linux-x86_64.tar.gz && \
  tar zxvf google-cloud-sdk-274.0.1-linux-x86_64.tar.gz && \
  /google-cloud-sdk/install.sh && \
  echo "if [ -f '/google-cloud-sdk/path.bash.inc' ]; then . '/google-cloud-sdk/path.bash.inc'; fi" >> /root/.bashrc && \
  echo "if [ -f '/google-cloud-sdk/completion.bash.inc' ]; then . '/google-cloud-sdk/completion.bash.inc'; fi" >> /root/.bashrc



使用 docker build 指令建立 image

> docker build  -t  sakana/ansible_opensuse151:20200105  -f  ./opensuseLeap151_20200105_ansible_Dockerfile   .

  • 使用 -f 指定 Dockerfile 名稱
  • 最後是 ” . “ 目前的目錄


測試 container image

> docker  run  -v  ~/.aws:/root/.aws  -v  ~/.azure:/root/.azure  -v ~/.config/gcloud:/root/.config/gcloud  -it  sakana/ansible_opensuse151:20200105  /bin/bash

測試結果 OK, 建立  tag

觀察資訊
> docker  images

REPOSITORY                   TAG IMAGE ID           CREATED SIZE
sakana/ansible_opensuse151   20200105 06e961a97803        About a minute ago   1.32GB
sakana/ansible_opensuse151   latest 3d76040b20fb        6 weeks ago 1.19GB
opensuse/leap                15.1 fef5ad254f63        2 months ago 103MB

建立 tag 
> docker  tag  06e961a97803  sakana/ansible_opensuse151:latest

登入 docker
> docker  login

上傳 image
> docker  push  sakana/ansible_opensuse151:20200105

> docker  push  sakana/ansible_opensuse151:latest

完工, 以後使用就用

> docker  run  -v  ~/.aws:/root/.aws  -v  ~/.azure:/root/.azure  -v ~/.config/gcloud:/root/.config/gcloud  -it  sakana/ansible_opensuse151  /bin/bash


~ enjoy it

Reference: