Skip to content

Commit

Permalink
{Monitor} az monitor autoscale: Upgrade monitor autoscale version a…
Browse files Browse the repository at this point in the history
…nd support predicative metric show (Azure#24018)

* upgrade monitor autoscale version

* add monitor autoscale show predictive metric cmd

* upgrade mgmt monitor package
  • Loading branch information
AllyW authored Sep 30, 2022
1 parent 2f309cf commit 6cd8ced
Show file tree
Hide file tree
Showing 23 changed files with 6,181 additions and 3,612 deletions.
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/profiles/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def default_api_version(self):
'activity_logs': '2015-04-01',
'alert_rule_incidents': '2016-03-01',
'alert_rules': '2016-03-01',
'autoscale_settings': '2015-04-01',
'autoscale_settings': '2022-10-01',
'baseline': '2018-09-01',
'baselines': '2019-03-01',
'diagnostic_settings': '2021-05-01-preview',
Expand Down
8 changes: 7 additions & 1 deletion src/azure-cli/azure/cli/command_modules/monitor/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

# pylint: disable=line-too-long, too-many-statements
def load_arguments(self, _):
from azure.mgmt.monitor.models import ConditionOperator, TimeAggregationOperator, EventData
from azure.mgmt.monitor.models import ConditionOperator, TimeAggregationOperator, EventData, PredictiveAutoscalePolicyScaleMode
from .grammar.metric_alert.MetricAlertConditionValidator import dim_op_conversion, agg_conversion, op_conversion, sens_conversion
name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
webhook_prop_type = CLIArgumentType(validator=process_webhook_prop, nargs='*')
Expand Down Expand Up @@ -213,6 +213,12 @@ def load_arguments(self, _):
c.argument('min_count', type=int, help='The minimum number of instances.')
c.argument('max_count', type=int, help='The maximum number of instances.')

with self.argument_context('monitor autoscale', arg_group='Predictive Policy') as c:
c.argument('scale_look_ahead_time', help='The amount of time to specify by which instances are launched in advance. '
'It must be between 1 minute and 60 minutes in ISO 8601 format '
'(for example, 100 days would be P100D).')
c.argument('scale_mode', arg_type=get_enum_type(PredictiveAutoscalePolicyScaleMode), help='The predictive autoscale mode')

with self.argument_context('monitor autoscale profile') as c:
c.argument('autoscale_name', arg_type=autoscale_name_type, id_part=None)
c.argument('profile_name', arg_type=autoscale_profile_name_type, options_list=['--name', '-n'])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command_group(
"monitor autoscale",
)
class __CMDGroup(AAZCommandGroup):
"""Manage autoscale settings
"""
pass


__all__ = ["__CMDGroup"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from .__cmd_group import *
from ._show_predictive_metric import *
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command(
"monitor autoscale show-predictive-metric",
)
class ShowPredictiveMetric(AAZCommand):
"""Show predictive autoscale metric future data
"""

_aaz_info = {
"version": "2022-10-01",
"resources": [
["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings/{}/predictivemetrics", "2022-10-01"],
]
}

def _handler(self, command_args):
super()._handler(command_args)
self._execute_operations()
return self._output()

_args_schema = None

@classmethod
def _build_arguments_schema(cls, *args, **kwargs):
if cls._args_schema is not None:
return cls._args_schema
cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

# define Arg Group ""

_args_schema = cls._args_schema
_args_schema.autoscale_setting_name = AAZStrArg(
options=["--autoscale-setting-name"],
help="The autoscale setting name.",
required=True,
)
_args_schema.resource_group = AAZResourceGroupNameArg(
required=True,
)
_args_schema.aggregation = AAZStrArg(
options=["--aggregation"],
help="The list of aggregation types (comma separated) to retrieve.",
required=True,
)
_args_schema.interval = AAZDurationArg(
options=["--interval"],
help="The interval (i.e. timegrain) of the query.",
required=True,
)
_args_schema.metric_name = AAZStrArg(
options=["--metric-name"],
help="The names of the metrics (comma separated) to retrieve. Special case: If a metricname itself has a comma in it then use %2 to indicate it. Eg: 'Metric,Name1' should be **'Metric%2Name1'**",
required=True,
)
_args_schema.metric_namespace = AAZStrArg(
options=["--metric-namespace"],
help="Metric namespace to query metric definitions for.",
required=True,
)
_args_schema.timespan = AAZStrArg(
options=["--timespan"],
help="The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.",
required=True,
)
return cls._args_schema

def _execute_operations(self):
self.pre_operations()
self.PredictiveMetricGet(ctx=self.ctx)()
self.post_operations()

# @register_callback
def pre_operations(self):
pass

# @register_callback
def post_operations(self):
pass

def _output(self, *args, **kwargs):
result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
return result

class PredictiveMetricGet(AAZHttpOperation):
CLIENT_TYPE = "MgmtClient"

def __call__(self, *args, **kwargs):
request = self.make_request()
session = self.client.send_request(request=request, stream=False, **kwargs)
if session.http_response.status_code in [200]:
return self.on_200(session)

return self.on_error(session.http_response)

@property
def url(self):
return self.client.format_url(
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/autoscalesettings/{autoscaleSettingName}/predictiveMetrics",
**self.url_parameters
)

@property
def method(self):
return "GET"

@property
def error_format(self):
return "ODataV4Format"

@property
def url_parameters(self):
parameters = {
**self.serialize_url_param(
"autoscaleSettingName", self.ctx.args.autoscale_setting_name,
required=True,
),
**self.serialize_url_param(
"resourceGroupName", self.ctx.args.resource_group,
required=True,
),
**self.serialize_url_param(
"subscriptionId", self.ctx.subscription_id,
required=True,
),
}
return parameters

@property
def query_parameters(self):
parameters = {
**self.serialize_query_param(
"aggregation", self.ctx.args.aggregation,
required=True,
),
**self.serialize_query_param(
"interval", self.ctx.args.interval,
required=True,
),
**self.serialize_query_param(
"metricName", self.ctx.args.metric_name,
required=True,
),
**self.serialize_query_param(
"metricNamespace", self.ctx.args.metric_namespace,
required=True,
),
**self.serialize_query_param(
"timespan", self.ctx.args.timespan,
required=True,
),
**self.serialize_query_param(
"api-version", "2022-10-01",
required=True,
),
}
return parameters

@property
def header_parameters(self):
parameters = {
**self.serialize_header_param(
"Accept", "application/json",
),
}
return parameters

def on_200(self, session):
data = self.deserialize_http_content(session)
self.ctx.set_var(
"instance",
data,
schema_builder=self._build_schema_on_200
)

_schema_on_200 = None

@classmethod
def _build_schema_on_200(cls):
if cls._schema_on_200 is not None:
return cls._schema_on_200

cls._schema_on_200 = AAZObjectType()

_schema_on_200 = cls._schema_on_200
_schema_on_200.data = AAZListType()
_schema_on_200.interval = AAZStrType()
_schema_on_200.metric_name = AAZStrType(
serialized_name="metricName",
)
_schema_on_200.target_resource_id = AAZStrType(
serialized_name="targetResourceId",
)
_schema_on_200.timespan = AAZStrType()

data = cls._schema_on_200.data
data.Element = AAZObjectType()

_element = cls._schema_on_200.data.Element
_element.time_stamp = AAZStrType(
serialized_name="timeStamp",
flags={"required": True},
)
_element.value = AAZFloatType(
flags={"required": True},
)

return cls._schema_on_200


__all__ = ["ShowPredictiveMetric"]
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
# pylint: disable=too-many-locals
def autoscale_create(client, resource, count, autoscale_name=None, resource_group_name=None,
min_count=None, max_count=None, location=None, tags=None, disabled=None,
actions=None, email_administrator=None, email_coadministrators=None):
actions=None, email_administrator=None, email_coadministrators=None,
scale_mode=None, scale_look_ahead_time=None):

from azure.mgmt.monitor.models import (
AutoscaleSettingResource, AutoscaleProfile, AutoscaleNotification, ScaleCapacity,
EmailNotification, WebhookNotification)
EmailNotification, WebhookNotification, PredictiveAutoscalePolicy)
from azure.cli.core.azclierror import InvalidArgumentValueError
if not autoscale_name:
from msrestazure.tools import parse_resource_id
autoscale_name = parse_resource_id(resource)['name']
Expand All @@ -45,13 +47,27 @@ def autoscale_create(client, resource, count, autoscale_name=None, resource_grou
notification.email.custom_emails.append(email)
elif isinstance(action, WebhookNotification):
notification.webhooks.append(action)
predictive_policy = None
if scale_mode is not None and scale_look_ahead_time is not None:
predictive_policy = PredictiveAutoscalePolicy(
scale_mode=scale_mode,
scale_look_ahead_time=scale_look_ahead_time
)
elif scale_mode is not None:
predictive_policy = PredictiveAutoscalePolicy(
scale_mode=scale_mode
)
elif scale_look_ahead_time is not None:
raise InvalidArgumentValueError('scale-mode is required for setting predictive autoscale policy.')

autoscale = AutoscaleSettingResource(
location=location,
profiles=[default_profile],
tags=tags,
notifications=[notification],
enabled=not disabled,
autoscale_setting_resource_name=autoscale_name,
predictive_autoscale_policy=predictive_policy,
target_resource_uri=resource
)
if not (min_count == count and max_count == count):
Expand All @@ -60,12 +76,13 @@ def autoscale_create(client, resource, count, autoscale_name=None, resource_grou


# pylint: disable=too-many-locals
def autoscale_update(instance, count=None, min_count=None, max_count=None, tags=None, enabled=None,
def autoscale_update(instance, count=None, min_count=None, max_count=None, tags=None, enabled=None, # pylint:disable=too-many-statements,too-many-branches
add_actions=None, remove_actions=None, email_administrator=None,
email_coadministrators=None):
email_coadministrators=None, scale_mode=None, scale_look_ahead_time=None):
import json
from azure.mgmt.monitor.models import EmailNotification, WebhookNotification
from azure.mgmt.monitor.models import EmailNotification, WebhookNotification, PredictiveAutoscalePolicy
from azure.cli.command_modules.monitor._autoscale_util import build_autoscale_profile
from azure.cli.core.azclierror import InvalidArgumentValueError

if tags is not None:
instance.tags = tags
Expand Down Expand Up @@ -130,7 +147,16 @@ def autoscale_update(instance, count=None, min_count=None, max_count=None, tags=
notification.email.send_to_subscription_administrator = email_administrator
if email_coadministrators is not None:
notification.email.send_to_subscription_co_administrators = email_coadministrators

predictive_policy = instance.predictive_autoscale_policy
if scale_mode is not None:
if predictive_policy is None:
predictive_policy = PredictiveAutoscalePolicy(scale_mode=scale_mode)
else:
predictive_policy.scale_mode = scale_mode
if scale_look_ahead_time is not None and predictive_policy is not None:
predictive_policy.scale_look_ahead_time = scale_look_ahead_time
elif scale_look_ahead_time is not None and predictive_policy is None:
raise InvalidArgumentValueError('scale-mode is required for setting scale-look-ahead-time.')
return instance


Expand Down
Loading

0 comments on commit 6cd8ced

Please sign in to comment.