【发布时间】:2019-01-23 12:34:54
【问题描述】:
我正在尝试使用 azure python API 获取虚拟机的 CPU 利用率。 就像一个虚拟机有 2 个 cpu,我需要整体利用率(意味着 cpu1+ cpu2)。
获取虚拟机cpu利用率的可能方法有哪些?
【问题讨论】:
标签: azure azure-resource-manager azure-resource-group
我正在尝试使用 azure python API 获取虚拟机的 CPU 利用率。 就像一个虚拟机有 2 个 cpu,我需要整体利用率(意味着 cpu1+ cpu2)。
获取虚拟机cpu利用率的可能方法有哪些?
【问题讨论】:
标签: azure azure-resource-manager azure-resource-group
您可能可以使用 Python 的 Azure 监控库来获取 Azure VM 上的 百分比 CPU 指标。安装azure-mgmt-monitor包并调用MetricsOperations class
中的list方法import datetime
from azure.mgmt.monitor import MonitorManagementClient
# Get the ARM id of your resource. You might chose to do a "get"
# using the according management or to build the URL directly
# Example for a ARM VM
resource_id = (
"subscriptions/{}/"
"resourceGroups/{}/"
"providers/Microsoft.Compute/virtualMachines/{}"
).format(subscription_id, resource_group_name, vm_name)
# create client
client = MonitorManagementClient(
credentials,
subscription_id
)
# You can get the available metrics of this specific resource
for metric in client.metric_definitions.list(resource_id):
# azure.monitor.models.MetricDefinition
print("{}: id={}, unit={}".format(
metric.name.localized_value,
metric.name.value,
metric.unit
))
# Example of result for a VM:
# Percentage CPU: id=Percentage CPU, unit=Unit.percent
# Network In: id=Network In, unit=Unit.bytes
# Network Out: id=Network Out, unit=Unit.bytes
# Disk Read Bytes: id=Disk Read Bytes, unit=Unit.bytes
# Disk Write Bytes: id=Disk Write Bytes, unit=Unit.bytes
# Disk Read Operations/Sec: id=Disk Read Operations/Sec, unit=Unit.count_per_second
# Disk Write Operations/Sec: id=Disk Write Operations/Sec, unit=Unit.count_per_second
# Get CPU total of yesterday for this VM, by hour
today = datetime.datetime.now().date()
yesterday = today - datetime.timedelta(days=1)
metrics_data = client.metrics.list(
resource_id,
timespan="{}/{}".format(yesterday, today),
interval='PT1H',
metric='Percentage CPU',
aggregation='Total'
)
for item in metrics_data.value:
# azure.mgmt.monitor.models.Metric
print("{} ({})".format(item.name.localized_value, item.unit.name))
for timeserie in item.timeseries:
for data in timeserie.data:
# azure.mgmt.monitor.models.MetricData
print("{}: {}".format(data.time_stamp, data.total))
# Example of result:
# Percentage CPU (percent)
# 2016-11-16 00:00:00+00:00: 72.0
# 2016-11-16 01:00:00+00:00: 90.59
# 2016-11-16 02:00:00+00:00: 60.58
# 2016-11-16 03:00:00+00:00: 65.78
# 2016-11-16 04:00:00+00:00: 43.96
# 2016-11-16 05:00:00+00:00: 43.96
# 2016-11-16 06:00:00+00:00: 114.9
# 2016-11-16 07:00:00+00:00: 45.4
【讨论】: