《Windows Azure Platform 系列文章目录》
之前遇到的项目中,客户需要在Python环境下,监控Azure VM的CPU利用率,在这里简单记录一下。
笔者的环境是Windows 10,如果需要Python开发,首先需要准备以下环境:
1.安装Python,下载地址:https://www.python.org/downloads/,我这里分别安装了Python 2.7.15和Python 3.7.0
2.安装PyCharm,下载地址:https://www.jetbrains.com/pycharm/download/#section=windows
选择导入开发环境配置文件,我们选择不导入。
3.配置PyCharm,我们配置运行环境:
4.因为笔者用的是Azure China服务,我们在上图中,需要增加相应的package。我们查询到package名字为mcazurerm
5.然后对mcazurerm进行配置,我们点击External Libraries,Site-packages,mcazurerm,然后点击settings.py
增加SNAPSHOT_API = '2016-04-30-preview'。如下图:
6.获得azure tenant id, appid, app secret, 订阅id,资源组名称,虚拟机名称。具体可以参考之前的内容:
https://www.cnblogs.com/threestone/p/9343146.html
7.vmlist.py的代码如下,分别实现了2个方法,list VM和获得CPU利用率。
#!/usr/bin/env python
# -*- coding:utf8 -*-
import xdrlib ,sys import xlrd import mcazurerm import json import mcazurerm.restfns #from restfns import do_delete, do_get, do_get_next, do_patch, do_post, do_put #from settings import azure_rm_endpoint, SNAPSHOT_API #from adalfns import get_access_token import datetime tenant_id = '这里输入tenantid' app_id = '这里输入appid' app_secret = '这里输入appsecret' subscription_id = '这里输入订阅ID' location = 'chinaeast' rg = '这里输入资源组名称' vmname = '这里输入Azure RM机器名' vmname2= '这里输入另外要监控的机器名' newapiversion='2016-09-01' # create an authentication token access_token = mcazurerm.get_access_token( tenant_id, app_id, app_secret ) def listvm(access_token, subscription_id, resource_group): endpoint = ''.join([mcazurerm.settings.azure_rm_endpoint, '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines', '?api-version=', mcazurerm.settings.SNAPSHOT_API]) return mcazurerm.restfns.do_get(endpoint,access_token) def GetCPU(access_toke,subscription_id,resource_group): endpoint = "".join([mcazurerm.settings.azure_rm_endpoint, "/subscriptions/", subscription_id, "/resourceGroups/", resource_group, "/providers/Microsoft.Compute/virtualMachines/",vmname, "/providers/microsoft.insights/metrics" "?$filter=(name.value eq 'Percentage CPU') and timeGrain eq duration'PT1M'", " and startTime eq 2018-08-22T08:19:26.2644638Z and endTime eq 2018-08-23T08:19:29.0454921Z", "&api-version=",newapiversion ]) print(endpoint) return mcazurerm.restfns.do_get(endpoint,access_token) def GetNetworkIn(access_toke,subscription_id,resource_group): endpoint = "".join([mcazurerm.settings.azure_rm_endpoint, "/subscriptions/", subscription_id, "/resourceGroups/", resource_group, "/providers/Microsoft.Compute/virtualMachines/",vmname, "/providers/microsoft.insights/metrics" "?$filter=(name.value eq 'Network In') and timeGrain eq duration'PT1M'", " and startTime eq 2018-08-22T08:19:26.2644638Z and endTime eq 2018-08-23T08:19:29.0454921Z", "&api-version=",newapiversion ]) return mcazurerm.restfns.do_get(endpoint,access_token) #https://docs.microsoft.com/en-us/rest/api/monitor/activitylogs/list#get_activity_logs_with_filter_and_select #By reource group def GetOperationByResourceGroup(access_toke,subscription_id,resource_group): endpoint = "".join([mcazurerm.settings.azure_rm_endpoint, "/subscriptions/", subscription_id, "/providers/microsoft.insights/eventtypes/management/values", "?api-version=", newapiversion, "&$filter=eventTimestamp ge '2018-08-01T20:00:00Z' and eventTimestamp le '2018-08-23T20:00:00Z' and resourceGroupName eq '",rg, "'" ]) return mcazurerm.restfns.do_get(endpoint,access_token) #by resource URI resourceuri="".join(["/subscriptions/",subscription_id ,"/resourceGroups/",rg, "/providers/Microsoft.Compute/VirtualMachines/",vmname2]) def GetOperationByResourceURI(access_toke,subscription_id,resource_group): endpoint = "".join([mcazurerm.settings.azure_rm_endpoint, "/subscriptions/", subscription_id, "/providers/microsoft.insights/eventtypes/management/values", "?api-version=", newapiversion, "&$filter=eventTimestamp ge '2018-08-01T20:00:00Z' and eventTimestamp le '2018-08-23T20:00:00Z' and resourceUri eq '",resourceuri, "'" ]) return mcazurerm.restfns.do_get(endpoint,access_token) vmlistreturn1 = listvm(access_token,subscription_id,rg) vmlistreturn2 = GetCPU(access_token,subscription_id,rg) vmlistreturn3 = GetNetworkIn(access_token,subscription_id,rg) vmlistreturn4 = GetOperationByResourceGroup(access_token,subscription_id,rg) vmlistreturn5 = GetOperationByResourceURI(access_token,subscription_id,rg) print(vmlistreturn2) print(vmlistreturn3) print(vmlistreturn4) print(vmlistreturn5)
8.其他REST API,可以参考Azure MSDN文档:
https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines
9.另外如果需要监控Azure China CDN流量的话,请参考下面的内容。我们点击下图的CDN Manage
10.在弹出的窗口中,找到安全管理,秘钥管理。如下图:
11.点击创建秘钥,如下图:
12.获取到秘钥的ID和Key
13.在Python中,增加如下代码:
cdnsubscription_id = 'CDN所在的订阅ID' cdnendpoint_id='CDN上面的Endpoint ID,具体的返回方法请参考下面的步骤' apiversion='1.0' cdnkeyid='输入上面步骤的cdnkeyid' cdnkeyvalue='输入上面步骤的cdnkey value' def calculate_authorization_header(request_url, request_time, key_id, key_value, http_method): """ Calculate the authorization header. @request_url: Complete request URL with scheme, host, path and queries @request_time: UTC request time with format yyyy-MM-dd hh:mm:ss @key_id: API key ID @key_value: API key value @http_method: Http method in upper case """ urlparts = urlparse.urlparse(request_url) queries = urlparse.parse_qs(urlparts.query) ordered_queries = collections.OrderedDict(sorted(queries.items())) message = "%s %s %s %s" % (urlparts.path, ", ".join(['%s:%s' % (key, value[0]) for (key, value) in ordered_queries.items()]), request_time, http_method) digest = hmac.new(bytearray(key_value, "utf-8"), bytearray(message, "utf-8"), hashlib.sha256).hexdigest().upper() return "AzureCDN %s:%s" % (key_id, digest) requesturl= "".join(["https://restapi.cdn.azure.cn/subscriptions/", cdnsubscription_id, "/endpoints?apiVersion=",apiversion ]) currentUTCTime = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") CDNheader = calculate_authorization_header(requesturl,currentUTCTime,cdnkeyid,cdnkeyvalue,'GET') #这个接口 返回CDN Endpoint ID CDNlist= mcazurerm.restfns.do_CDNget(requesturl,currentUTCTime,CDNheader) #https://docs.azure.cn/zh-cn/cdn/cdn-api-get-subscription-volume #startTime yyyy-MM-ddThh:mm:ssZ #endTime yyyy-MM-ddThh:mm:ssZ #granularity PerFiveMinutes,PerHour,PerDay requesturl= "".join(["https://restapi.cdn.azure.cn/subscriptions/", cdnsubscription_id, "/endpoints/",cdnendpoint_id, "/volume?apiVersion=",apiversion, "&startTime=2018-08-18T00:00:00Z&endTime=2018-08-20T06:32:53Z&granularity=PerHour" ]) currentUTCTime = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") CDNheader = calculate_authorization_header(requesturl,currentUTCTime,cdnkeyid,cdnkeyvalue,'GET') CDNlist= mcazurerm.restfns.do_CDNget(requesturl,currentUTCTime,CDNheader)
14.修改restfns.py,增加方法:
def do_CDNget(endpoint, requestdate, access_token): headers = { "x-azurecdn-request-date": requestdate, "Authorization": access_token } return requests.get(endpoint, headers=headers).json()