Skip to content

Commit

Permalink
[Monitor][Feature]az vm monitor metrics tail: support query metrics f…
Browse files Browse the repository at this point in the history
…or vm(#11528)
  • Loading branch information
mmyyrroonn authored Dec 25, 2019
1 parent efab83e commit 93a50bb
Show file tree
Hide file tree
Showing 8 changed files with 1,711 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/azure-cli/HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Release History
**Compute**

* Fix `vm create` failure in Azure Stack profile.
* vm monitor metrics tail/list-definitions: support query metric and list definitions for a vm.

2.0.78
++++++
Expand Down
57 changes: 57 additions & 0 deletions src/azure-cli/azure/cli/command_modules/vm/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -2431,3 +2431,60 @@
type: group
short-summary: Manage log analytics workspace for a vm.
"""

helps['vm monitor metrics'] = """
type: group
short-summary: Manage metrics for a vm.
"""

helps['vm monitor metrics tail'] = """
type: command
short-summary: List the metric values for a VM.
parameters:
- name: --aggregation
short-summary: The list of aggregation types (space-separated) to retrieve.
populator-commands:
- az vm monitor metrics list-definitions -n MyVM -g MyRG --query "@[*].supportedAggregationTypes"
- name: --interval
short-summary: >
The interval over which to aggregate metrics, in ##h##m format.
- name: --filter
short-summary: A string used to reduce the set of metric data returned. eg. "LUN eq '*'"
long-summary: 'For a full list of filters, see the filter string reference at https://docs.microsoft.com/rest/api/monitor/metrics/list'
- name: --metadata
short-summary: Return the metadata values instead of metric data
- name: --dimension
short-summary: The list of dimensions (space-separated) the metrics are queried into.
populator-commands:
- az vm monitor metrics list-definitions -n MyVM -g MyRG --query "@[*].dimensions"
- name: --namespace
short-summary: Namespace to query metric definitions for.
- name: --offset
short-summary: >
Time offset of the query range, in ##d##h format.
long-summary: >
Can be used with either --start-time or --end-time. If used with --start-time, then
the end time will be calculated by adding the offset. If used with --end-time (default), then
the start time will be calculated by subtracting the offset. If --start-time and --end-time are
provided, then --offset will be ignored.
- name: --metrics
short-summary: >
Space-separated list of metric names to retrieve.
populator-commands:
- az vm monitor metrics list-definitions -n MyVM -g MyRG --query "@[*].name.value"
examples:
- name: List CPU usage of VM for past one hour
text: >
az vm monitor metrics tail --name myVM -g myRG --metric "Percentage CPU"
- name: List one hour CPU usage of VM started at 2019-12-18T00:00:00Z
text: >
az vm monitor metrics tail --name myVM -g myRG --metric "Percentage CPU" --start-time 2019-12-18T00:00:00Z
- name: List CPU usage of VM for past one hour with filter
text: >
az vm monitor metrics tail --name myVM -g myRG --metrics "Per Disk Read Bytes/sec" --filter "SlotId eq '*'"
"""

helps['vm monitor metrics list-definitions'] = """
type: command
short-summary: List the metric definitions for a VM.
"""
34 changes: 33 additions & 1 deletion src/azure-cli/azure/cli/command_modules/vm/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from knack.arguments import CLIArgumentType

from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.parameters import get_datetime_type
from azure.cli.core.util import get_default_admin_username
from azure.cli.core.commands.validators import (
get_default_location_from_resource_group, validate_file_or_dict)
Expand All @@ -21,11 +22,14 @@
from azure.cli.command_modules.vm._validators import (
validate_nsg_name, validate_vm_nics, validate_vm_nic, validate_vm_disk, validate_vmss_disk,
validate_asg_names_or_ids, validate_keyvault, _validate_proximity_placement_group,
process_gallery_image_version_namespace)
process_gallery_image_version_namespace, validate_vm_name_for_monitor_metrics)

from azure.cli.command_modules.vm._vm_utils import MSI_LOCAL_ID
from azure.cli.command_modules.vm._image_builder import ScriptType

from azure.cli.command_modules.monitor.validators import validate_metric_dimension
from azure.cli.command_modules.monitor.actions import get_period_type


# pylint: disable=too-many-statements, too-many-branches, too-many-locals
def load_arguments(self, _):
Expand Down Expand Up @@ -844,6 +848,34 @@ def load_arguments(self, _):
with self.argument_context('vm monitor log show') as c:
c.argument('analytics_query', options_list=['--analytics-query', '-q'], help="Query to execute over Log Analytics data.")
c.argument('timespan', help="Timespan over which to query. Defaults to querying all available data.")

with self.argument_context('vm monitor metrics') as c:
c.argument('metricnamespace', options_list=['--namespace'],
help='Namespace to query metric definitions for.')

with self.argument_context('vm monitor metrics tail') as c:
from azure.mgmt.monitor.models import AggregationType
c.extra('resource_group_name', required=True)
c.argument('resource', arg_type=existing_vm_name, help='Name or ID of a virtual machine', validator=validate_vm_name_for_monitor_metrics, id_part=None)
c.argument('metadata', action='store_true')
c.argument('dimension', nargs='*', validator=validate_metric_dimension)
c.argument('aggregation', arg_type=get_enum_type(t for t in AggregationType if t.name != 'none'), nargs='*')
c.argument('metrics', nargs='*')
c.argument('orderby',
help='Aggregation to use for sorting results and the direction of the sort. Only one order can be specificed. Examples: sum asc')
c.argument('top', help='Max number of records to retrieve. Valid only if --filter used.')
c.argument('filters', options_list=['--filter'])
c.argument('metric_namespace', options_list=['--namespace'])

with self.argument_context('vm monitor metrics tail', arg_group='Time') as c:
c.argument('start_time', arg_type=get_datetime_type(help='Start time of the query.'))
c.argument('end_time', arg_type=get_datetime_type(help='End time of the query. Defaults to the current time.'))
c.argument('offset', type=get_period_type(as_timedelta=True))
c.argument('interval', arg_group='Time', type=get_period_type())

with self.argument_context('vm monitor metrics list-definitions') as c:
c.extra('resource_group_name', required=True)
c.argument('resource_uri', arg_type=existing_vm_name, help='Name or ID of a virtual machine', validator=validate_vm_name_for_monitor_metrics, id_part=None)
# endregion

# region disk encryption set
Expand Down
10 changes: 10 additions & 0 deletions src/azure-cli/azure/cli/command_modules/vm/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ def validate_keyvault(cmd, namespace):
'vaults', 'Microsoft.KeyVault')


def validate_vm_name_for_monitor_metrics(cmd, namespace):
if hasattr(namespace, 'resource'):
namespace.resource = _get_resource_id(cmd.cli_ctx, namespace.resource, namespace.resource_group_name,
'virtualMachines', 'Microsoft.Compute')
elif hasattr(namespace, 'resource_uri'):
namespace.resource_uri = _get_resource_id(cmd.cli_ctx, namespace.resource_uri, namespace.resource_group_name,
'virtualMachines', 'Microsoft.Compute')
del namespace.resource_group_name


def _validate_proximity_placement_group(cmd, namespace):
from msrestazure.tools import parse_resource_id

Expand Down
23 changes: 23 additions & 0 deletions src/azure-cli/azure/cli/command_modules/vm/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
from azure.cli.core.commands import DeploymentOutputLongRunningOperation, CliCommandType
from azure.cli.core.commands.arm import deployment_validate_table_format, handle_template_based_exception

from azure.cli.command_modules.monitor._exception_handler import monitor_exception_handler
from azure.cli.command_modules.monitor._client_factory import cf_metric_def
from azure.cli.core.profiles import ResourceType


# pylint: disable=line-too-long, too-many-statements, too-many-locals
def load_command_table(self, _):
Expand Down Expand Up @@ -177,6 +181,16 @@ def load_command_table(self, _):
operations_tmpl='azure.mgmt.compute.operations#DiskEncryptionSetsOperations.{}',
client_factory=cf_disk_encryption_set
)
monitor_custom = CliCommandType(
operations_tmpl='azure.cli.command_modules.monitor.custom#{}',
exception_handler=monitor_exception_handler)

metric_definitions_sdk = CliCommandType(
operations_tmpl='azure.mgmt.monitor.operations#MetricDefinitionsOperations.{}',
resource_type=ResourceType.MGMT_MONITOR,
client_factory=cf_metric_def,
operation_group='metric_definitions',
exception_handler=monitor_exception_handler)

with self.command_group('disk', compute_disk_sdk, operation_group='disks', min_api='2017-03-30') as g:
g.custom_command('create', 'create_managed_disk', supports_no_wait=True, table_transformer=transform_disk_show_table_output, validator=process_disk_or_snapshot_create_namespace)
Expand Down Expand Up @@ -457,3 +471,12 @@ def load_command_table(self, _):

with self.command_group('vm monitor log', log_analytics_data_plane_sdk, client_factory=cf_log_analytics_data_plane) as g:
g.custom_command('show', 'execute_query_for_vm', transform=transform_log_analytics_query_output)

with self.command_group('vm monitor metrics', custom_command_type=monitor_custom, command_type=metric_definitions_sdk, resource_type=ResourceType.MGMT_MONITOR, operation_group='metric_definitions', min_api='2018-01-01', is_preview=True) as g:
from azure.cli.command_modules.monitor.transformers import metrics_table, metrics_definitions_table
from azure.cli.core.profiles._shared import APIVersionException
try:
g.custom_command('tail', 'list_metrics', command_type=monitor_custom, table_transformer=metrics_table)
g.command('list-definitions', 'list', table_transformer=metrics_definitions_table)
except APIVersionException:
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

from azure_devtools.scenario_tests import RecordingProcessor


class TimeSpanProcessor(RecordingProcessor):
def __init__(self, replacement):
self._replacement = replacement

def process_request(self, request):
request.uri = self._replace_timespan(request.uri)

return request

def _replace_timespan(self, val):
import re
# subscription presents in all api call
retval = re.sub('timespan=((.*?)(&|$))',
r'timespan={}\3'.format(self._replacement),
val,
flags=re.IGNORECASE)
return retval
Loading

0 comments on commit 93a50bb

Please sign in to comment.