日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

Python 自動化: eip、cen監控數據對接到 grafana

來源: 責編: 時間:2023-11-15 09:20:33 304觀看
導讀概覽日常運維中,我們有時需要關注阿里云中 EIP 和 CEN 的監控數據,如果每次登錄到平臺查看,不太方便。可以通過 API 獲取監控數據,并輸入到 influxDB,然后再到 Grafana 中展示,以便進行實施監控和可視化。第一步:準備工作在

GVj28資訊網——每日最新資訊28at.com

概覽

GVj28資訊網——每日最新資訊28at.com

日常運維中,我們有時需要關注阿里云中 EIP 和 CEN 的監控數據,如果每次登錄到平臺查看,不太方便。GVj28資訊網——每日最新資訊28at.com

可以通過 API 獲取監控數據,并輸入到 influxDB,然后再到 Grafana 中展示,以便進行實施監控和可視化。GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

第一步:準備工作

GVj28資訊網——每日最新資訊28at.com

在開始之前,我們需要確保已經完成以下準備工作GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

準備阿里云的EIP和CEN實例

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

這一步省略GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

了解如何獲取EIP和CEN數據

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

了解如何獲取 EIP 和 CEN 數據

我的方式是 EIP 通過 EIP 產品的 API 獲取的,調試鏈接如下GVj28資訊網——每日最新資訊28at.com

https://next.api.aliyun.com/api/Vpc/2016-04-28/DescribeEipMonitorData?params={"RegionId":"cn-hangzhou"}GVj28資訊網——每日最新資訊28at.com

輸入 RegionId 和 AllocationId 等必選信息后,復制平臺生成的代碼,進行更改,下文會介紹如何更改GVj28資訊網——每日最新資訊28at.com

圖片圖片GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

CEN 的監控數據未找到具體的 API,但可以通過云監控的數據獲取,也是很方便的,鏈接如下GVj28資訊網——每日最新資訊28at.com

https://api.aliyun.com/api/Cms/2019-01-01/DescribeMetricDataGVj28資訊網——每日最新資訊28at.com

獲取 CEN 的具體數據時,可以通過 https://cms.console.aliyun.com/metric-meta/acs_cen/cen_tr?spm=a2c4g.11186623.0.0.252476ab1Ldq0T 得到GVj28資訊網——每日最新資訊28at.com

實際上,EIP 的數據也可以通過云監控獲取GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

安裝Python和所需的依賴庫

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

下面示例的版本是截止發文時間最新版本,實際使用時,可以登錄到上面的阿里云開放平臺查看最新的版本GVj28資訊網——每日最新資訊28at.com

pip install alibabacloud_vpc20160428==5.1.0pip install alibabacloud_cms20190101==2.0.11

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

安裝InfluxDB,并進行初始化配置

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

1. 為方便使用,我這里是使用 Docker 運行的 InfluxdbGVj28資訊網——每日最新資訊28at.com

cd /data/influxdb# 生成初始的配置文件docker run --rm influxdb:2.7.1 influxd print-config > config.yml# 啟動容器docker run --name influxdb -d -p 8086:8086 --volume `pwd`/influxdb2:/var/lib/influxdb2 --volume `pwd`/config.yml:/etc/influxdb2/config.yml influxdb:2.7.1

2. 安裝完成后,可通過 http://ip:8086 登錄到 InfluxdbGVj28資訊網——每日最新資訊28at.com

3. 創建 bucketGVj28資訊網——每日最新資訊28at.com

只需要創建一個 bucket 就可以了,bucket 類似 MySQL 的 databaseGVj28資訊網——每日最新資訊28at.com

4. 獲取 API Token,在 Python 插入數據時會用到GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

安裝Grafana,并進行基本的配置

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

省略GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

第二步:獲取API訪問憑證

GVj28資訊網——每日最新資訊28at.com

為了能夠通過API訪問阿里云的 EIP 和 CEN 數據,我們需要獲取訪問憑證。具體步驟如下GVj28資訊網——每日最新資訊28at.com

  1. 登錄阿里云控制臺
  2. 創建 RAM 用戶并分配相應的權限
  3. 獲取 RAM 用戶的 Access Key ID 和 Access Key Secret

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

第三步:編寫Python腳本

GVj28資訊網——每日最新資訊28at.com

使用Python編寫腳本來獲取 EIP 和 CEN 的監控數據,并將其存儲到 InfluxDB 中GVj28資訊網——每日最新資訊28at.com

本文僅展示部分代碼,如需完整的代碼,請聯系本公眾號獲取~GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

調整從阿里云復制的示例代碼

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

1. 修改構造函數,可以傳如 access_key_id 和 access_key_secretGVj28資訊網——每日最新資訊28at.com

def __init__(self, access_key_id: str=access_key_id, access_key_secret: str=access_key_secret):        self.access_key_id = access_key_id        self.access_key_secret = access_key_secret

GVj28資訊網——每日最新資訊28at.com

2. 修改獲取 eip 數據的函數GVj28資訊網——每日最新資訊28at.com

def get_eip_monitor_data(self, region_id, allocation_id, start_time: str, end_time: str):        '''        參考文檔:        https://api.aliyun.com/api/Vpc/2016-04-28/DescribeEipMonitorData?params={%22RegionId%22:%22cn-hangzhou%22}        Args:            region_id (_type_): _description_            allocation_id (_type_): _description_            start_time (str): utc時間            end_time (_type_): utc時間        Yields:            _type_: _description_            eip_tx: 流出的流量。單位: Byte            eip_rx: 流入的流量。單位: Byte        '''        # 請確保代碼運行環境設置了環境變量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。        # 工程代碼泄露可能會導致 AccessKey 泄露,并威脅賬號下所有資源的安全性。以下代碼示例使用環境變量獲取 AccessKey 的方式進行調用,僅供參考,建議使用更安全的 STS 方式,更多鑒權訪問方式請參見:https://help.aliyun.com/document_detail/378659.html        client = self.create_client(endpoint=f'vpc.{region_id}.aliyuncs.com', access_key_id=self.access_key_id, access_key_secret=self.access_key_secret)        describe_eip_monitor_data_request = vpc_20160428_models.DescribeEipMonitorDataRequest(            region_id=region_id,            allocation_id=allocation_id,            start_time=start_time,            end_time=end_time        )        log.debug(msg=describe_eip_monitor_data_request)        runtime = util_models.RuntimeOptions()        log.debug(msg=runtime)        try:            # 復制代碼運行請自行打印 API 的返回值            results = client.describe_eip_monitor_data_with_options(describe_eip_monitor_data_request, runtime).body.eip_monitor_datas.eip_monitor_data            for result in results:                yield result        except Exception as error:            log.error(msg=error)            return UtilClient.assert_as_string(error.message)

GVj28資訊網——每日最新資訊28at.com

3. 修改獲取 cen 數據的函數GVj28資訊網——每日最新資訊28at.com

def get_cen_monitor_data(self, namespace, metric_name, start_time: str, end_time: str):        # 請確保代碼運行環境設置了環境變量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。        # 工程代碼泄露可能會導致 AccessKey 泄露,并威脅賬號下所有資源的安全性。以下代碼示例使用環境變量獲取 AccessKey 的方式進行調用,僅供參考,建議使用更安全的 STS 方式,更多鑒權訪問方式請參見:https://help.aliyun.com/document_detail/378659.html        client = self.create_client(access_key_id=self.access_key_id, access_key_secret=self.access_key_secret)        describe_metric_list_request = cms_20190101_models.DescribeMetricListRequest(            namespace=namespace,            metric_name=metric_name,            start_time=start_time,            end_time=end_time,        )        runtime = util_models.RuntimeOptions()        try:            # 復制代碼運行請自行打印 API 的返回值            return client.describe_metric_list_with_options(describe_metric_list_request, runtime).body.datapoints        except Exception as error:            # 如有需要,請打印 error            UtilClient.assert_as_string(error.message)

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

編寫InfluxDB相關的代碼

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

將 InfluxDB 的寫入代碼獨立出來可以方便后續其他業務的調用GVj28資訊網——每日最新資訊28at.com

下面的代碼在獲取 token 時,使用了 1password,可視情況進行修改,例如通過環境變量的方式獲取 TokenGVj28資訊網——每日最新資訊28at.com

#!/usr/bin/env python3import influxdb_client, timeimport datetimefrom influxdb_client import InfluxDBClient, Point, WritePrecisionfrom influxdb_client.client.write_api import SYNCHRONOUSfrom modules.onepassword import OnePasswordmy1p = OnePassword()class InfluxClient:    token = my1p.get_item_by_title(title='my_influxdb')['api']    def __init__(self, url: str='http://10.1.1.1:8086', org: str='tyun', token: str=token):        self.url = url        self.org = org        self.token = token        def create_client(self):        return influxdb_client.InfluxDBClient(url=self.url, token=self.token, org=self.org)    def write_aliyun_eip(self, bucket: str='example', table_name: str='test1', location: str=None, eip_tx: int=None, eip_rx: int=None, time_stamp: str=None):        write_api = self.create_client().write_api(write_optinotallow=SYNCHRONOUS)        point = (            Point(table_name)            .tag("location", location)            .field("eip_tx", eip_tx)            .field("eip_rx", eip_rx)            .time(time_stamp)        )        write_api.write(bucket=bucket, org=self.org, record=point)    def write_cen(self, bucket: str='example', table_name: str='test1', location: str=None, tr_instance_id: str=None, value: int=None, time_stamp: str=None):        write_api = self.create_client().write_api(write_optinotallow=SYNCHRONOUS)        point = (            Point(table_name)            .tag("location", location)            .tag("tr_instance_id", tr_instance_id)            .field("value", value)            .time(time_stamp)        )        write_api.write(bucket=bucket, org=self.org, record=point)def main():    influx_client = InfluxClient()     for i in range(5):        influx_client.write_data(bucket='example', table_name='test1', locatinotallow='hangzhou', EipBandwidth=i, EipFlow=i)        time.sleep(1)if __name__ == '__main__':    main()

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

編寫主程序

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

1. 獲取 eip 并插入到 influxdbGVj28資訊網——每日最新資訊28at.com

#!/usr/bin/env python3from collections import namedtuplefrom modules.aliyun.eip import Eipfrom modules.database.influxdb.write import InfluxClientfrom modules.tools.my_time import MyDatetime as my_timeeip = Eip()influx_client = InfluxClient()def insert_data(region_id, location, table_name, allocation_id, start_time, end_time):    '''    _summary_    Args:        region_id (_type_): _description_        location (_type_): _description_        table_name (_type_): _description_        allocation_id (_type_): _description_        start_time (_type_): _description_        interval (int, optional): 取值的范圍, 默認是5.    '''    eip_datas = eip.get_eip_monitor_data(region_id=region_id, allocation_id=allocation_id, start_time=start_time, end_time=end_time)    for eip_data in eip_datas:        # print(eip_data)        influx_client.write_aliyun_eip(bucket='example',                                       table_name=table_name,                                       locatinotallow=location,                                       eip_rx=eip_data.eip_rx,                                       eip_tx=eip_data.eip_tx,                                       time_stamp=eip_data.time_stamp)Instance = namedtuple('Instance', ['region_id', 'allocation_id', 'bandwidth', 'env'])hangzhou = Instance(region_id='hangzhou', allocation_id='eip-xxxxxxxxx', bandwidth='100m', env='prod')eip_site_list = [hangzhou]for eip_site in eip_site_list:    insert_data(region_id=f'cn-{eip_site.region_id}',                 locatinotallow=f'cn-{eip_site.region_id}',                table_name='eip',                allocation_id=eip_site.allocation_id,                start_time=my_time.get_utc_now_str_offset(offset=-60*10),                end_time=my_time.get_utc_now_str()                )

GVj28資訊網——每日最新資訊28at.com

2. 獲取 cen 數據并插入到 influxdbGVj28資訊網——每日最新資訊28at.com

#!/usr/bin/env python3import astfrom modules.aliyun.metrics import Metricsfrom modules.database.influxdb.write import InfluxClientfrom modules.tools.my_time import MyDatetime as my_timefrom modules.logger.client import LogClientmetrics = Metrics()influx_client = InfluxClient()log = LogClient(app='example_traffic')def tr_instance_id_to_location(tr_instance_id):    if tr_instance_id == 'tr-xxxxxxxxxxxxx':        location = 'hangzhou'        bandwidth = '20m'    else:        location = 'none'    return location, bandwidthmetric_names = ['AttachmentOutRate', 'AttachmentInRate']for metric_name in metric_names:    results = metrics.get_cen_monitor_data(namespace='acs_cen',                                            metric_name=metric_name,                                            start_time=my_time.get_utc_now_str_offset(offset=-60*10),                                           end_time=my_time.get_utc_now_str())    log.debug(msg=results)    for result in ast.literal_eval(results):        result['metric_name'] = metric_name        trInstanceId = result['trInstanceId']        result['location'] = tr_instance_id_to_location(tr_instance_id=trInstanceId)[0]        result['bandwidth'] = tr_instance_id_to_location(tr_instance_id=trInstanceId)[1]                log.info(msg=metric_name + ' ' + my_time.timestamp_to_str(timestamp=result['timestamp']) + ' ' + ' ' + result['location'] + ' ' + str(result['Value']))        influx_client.write_cen(bucket='example',                                 table_name=metric_name,                                 locatinotallow=result['location'],                                tr_instance_id=result['trInstanceId'],                                 value=result['Value'],                                 time_stamp=my_time.timestamp_to_str(timestamp=result['timestamp']))

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

第四步:配置Grafana

GVj28資訊網——每日最新資訊28at.com

在Grafana中配置 InfluxDB 數據源,并創建相應的儀表盤來展示 EIP 和 CEN 的監控數據。具體步驟如下:GVj28資訊網——每日最新資訊28at.com

  1. 添加 InfluxDB 數據源,并配置連接信息我用的是 Flux 的查詢語言,配置數據源時,需要注意以下事項

數據源名字推薦使用:InfluxDB-Flux,注明是 Flux 類型的數據源GVj28資訊網——每日最新資訊28at.com

InfluxDB Details 填寫 Organization、Token、Default Bucket 即可GVj28資訊網——每日最新資訊28at.com

不用填寫 HTTP 認證GVj28資訊網——每日最新資訊28at.com

  1. 創建儀表盤,配置 eip 和 cen 的查詢語句· EIP 接收方向的流量
from(bucket: "example")  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)  |> filter(fn: (r) => r["_measurement"] == "eip")  |> filter(fn: (r) => r["_field"] == "eip_rx")  |> filter(fn: (r) => r["location"] == "cn-hangzhou")  |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)  |> map(fn: (r) => ({ r with _value: r._value / 8 }))  |> yield(name: "last")

GVj28資訊網——每日最新資訊28at.com

  •  EIP 發送方向的流量
from(bucket: "example")  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)  |> filter(fn: (r) => r["_measurement"] == "eip")  |> filter(fn: (r) => r["_field"] == "eip_tx")  |> filter(fn: (r) => r["location"] == "cn-hangzhou")  |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)  |> map(fn: (r) => ({ r with _value: r._value / 8 }))  |> yield(name: "last")

GVj28資訊網——每日最新資訊28at.com

  •  CEN 發送方向的流量
from(bucket: "example")  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)  |> filter(fn: (r) => r["_measurement"] == "AttachmentOutRate")  |> filter(fn: (r) => r["_field"] == "value")  |> filter(fn: (r) => r["location"] == "hangzhou")  |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)  |> yield(name: "last")

GVj28資訊網——每日最新資訊28at.com

  • CEN 接收方向流量
from(bucket: "example")  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)  |> filter(fn: (r) => r["_measurement"] == "AttachmentInRate")  |> filter(fn: (r) => r["_field"] == "value")  |> filter(fn: (r) => r["location"] == "hangzhou")  |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)  |> yield(name: "last")

GVj28資訊網——每日最新資訊28at.com

  1. eip 和 cen 的數據單位都是 bit/sec(SI)GVj28資訊網——每日最新資訊28at.com

  2. 建議配置 Grafana 面板的 ThresholdsGVj28資訊網——每日最新資訊28at.com

    100M為 100000000,配置后會顯示一條紅線,可以更直觀的看到流量的占用情況GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

GVj28資訊網——每日最新資訊28at.com

總結

GVj28資訊網——每日最新資訊28at.com

通過本文的步驟,我們可以通過API獲取阿里云 EIP 和 CEN 的監控數據,將其存儲到 InfluxDB,并通過 Grafana 進行實時監控和可視化。這為我們提供了一種自動化的方式來監控和管理阿里云網絡資源。GVj28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-25471-0.htmlPython 自動化: eip、cen監控數據對接到 grafana

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 來看看,這些Java編程小技巧肯定有你不知道的

下一篇: SpringBoot2.7升級到3.0注意事項及相關變化

標簽:
  • 熱門焦點
  • 5月iOS設備好評榜:iPhone 14僅排第43?

    來到新的一月,安兔兔的各個榜單又重新匯總了數據,像安卓陣營的榜單都有著比較大的變動,不過iOS由于設備的更新換代并沒有那么快,所以相對來說變化并不大,特別是iOS好評榜,老款設
  • 一年經驗在二線城市面試后端的經驗分享

    忠告這篇文章只適合2年內工作經驗、甚至沒有工作經驗的朋友閱讀。如果你是2年以上工作經驗,請果斷劃走,對你沒啥幫助~主人公這篇文章內容來自 「升職加薪」星球星友 的投稿,坐
  • 企業采用CRM系統的11個好處

    客戶關系管理(CRM)軟件可以為企業提供很多的好處,從客戶保留到提高生產力。  CRM軟件用于企業收集客戶互動,以改善客戶體驗和滿意度。  CRM軟件市場規模如今超過580
  • 自律,給不了Keep自由!

    來源 | 互聯網品牌官作者 | 李大為編排 | 又耳 審核 | 谷曉輝自律能不能給用戶自由暫時不好說,但大概率不能給Keep自由。近日,全球最大的在線健身平臺Keep正式登陸港交所,努力
  • 年輕人的“職場羞恥感”,無處不在

    作者:馮曉亭 陶 淘 李 欣 張 琳 馬舒葉來源:燃次元“人在職場,應該選擇什么樣的著裝?”近日,在網絡上,一個與著裝相關的帖子引發關注,在該帖子里,一位在高級寫字樓亞洲金
  • 三星推出Galaxy Tab S9系列平板電腦以及Galaxy Watch6系列智能手表

    2023年7月26日,三星電子正式發布了Galaxy Z Flip5與Galaxy Z Fold5。除此之外,Galaxy Tab S9系列平板電腦以及三星Galaxy Watch6系列智能手表也同期
  • 半導體需求下滑 三星電子DS業務部門今年營業虧損預計超10萬億韓元

    7月17日消息,據外媒報道,去年下半年開始的半導體需求下滑,影響到了三星電子、SK海力士、英特爾等諸多廠商,營收明顯下滑,部分廠商甚至出現了虧損。作為
  • 電博會與軟博會實現"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發揮展會拉動人流、信息流、資金流實現快速交互流動的作用,繼而推動區域經濟良性發展;又可以聚
  • 北京:科技教育體驗基地開始登記

      北京“科技館之城”科技教育體驗基地登記和認證工作日前啟動。首批北京科技教育體驗基地擬于2023年全國科普日期間掛牌,后續還將開展常態化登記。  北京科技教育體驗基
Top 主站蜘蛛池模板: 永仁县| 浙江省| 延边| 鹤峰县| 墨竹工卡县| 江达县| 金溪县| 普兰县| 疏附县| 铜陵市| 碌曲县| 夹江县| 左云县| 景德镇市| 余姚市| 青田县| 丽江市| 辽宁省| 富源县| 冀州市| 稷山县| 霞浦县| 浦城县| 南通市| 伊春市| 和顺县| 五家渠市| 莎车县| 商城县| 应用必备| 道真| 马山县| 武义县| 历史| 宜黄县| 师宗县| 杭锦后旗| 华阴市| 建平县| 桃江县| 汾阳市|