Skip to content

Commit 7c8ae37

Browse files
Jing-songkairu-ms
andauthored
{Scheduled-Query} Add scheduled query rules (Azure#3753)
* update SDK * parameter * Update src/scheduled-query/HISTORY.rst Co-authored-by: kai ru <69238381+kairu-ms@users.noreply.github.com> * Update src/scheduled-query/HISTORY.rst Co-authored-by: kai ru <69238381+kairu-ms@users.noreply.github.com> * Update src/scheduled-query/setup.py Co-authored-by: kai ru <69238381+kairu-ms@users.noreply.github.com> * update * Update test_scheduled_query.yaml * Update _params.py * Update HISTORY.rst Co-authored-by: kai ru <69238381+kairu-ms@users.noreply.github.com>
1 parent cae8b78 commit 7c8ae37

29 files changed

+2881
-1313
lines changed

src/scheduled-query/HISTORY.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22
33
Release History
44
===============
5+
0.4.0
6+
++++++
7+
* Add `--skip-query-validation` parameter
8+
* Add `--check-ws-alerts-storage` parameter
9+
* Add `--auto-mitigate` parameter
10+
* [Breaking Change] `--actions` are split into `--action-groups` and `--custom-properties`
11+
* [Breaking Change] the default value of `--mute-actions-duration` is changed to None
12+
513
0.3.1
614
++++++
715
* Support query placeholder for `--condition` parameter.

src/scheduled-query/azext_scheduled_query/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@ def __init__(self, cli_ctx=None):
1616
scheduled_query_custom = CliCommandType(
1717
operations_tmpl='azext_scheduled_query.custom#{}',
1818
client_factory=cf_scheduled_query)
19-
super(ScheduledQueryCommandsLoader, self).__init__(cli_ctx=cli_ctx,
20-
custom_command_type=scheduled_query_custom)
19+
super().__init__(cli_ctx=cli_ctx, custom_command_type=scheduled_query_custom)
2120

2221
def load_command_table(self, args):
2322
from azext_scheduled_query.commands import load_command_table

src/scheduled-query/azext_scheduled_query/_actions.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,9 @@ def __call__(self, parser, namespace, values, option_string=None):
3939
for item in ['time_aggregation', 'threshold', 'operator']:
4040
if not getattr(scheduled_query_condition, item, None):
4141
raise InvalidArgumentValueError(usage)
42-
except (AttributeError, TypeError, KeyError):
43-
raise InvalidArgumentValueError(usage)
44-
super(ScheduleQueryConditionAction, self).__call__(parser,
45-
namespace,
46-
scheduled_query_condition,
47-
option_string)
42+
except (AttributeError, TypeError, KeyError) as e:
43+
raise InvalidArgumentValueError(usage) from e
44+
super().__call__(parser, namespace, scheduled_query_condition, option_string)
4845

4946

5047
class ScheduleQueryConditionQueryAction(argparse.Action):
@@ -65,9 +62,9 @@ def __call__(self, parser, namespace, values, option_string=None):
6562
class ScheduleQueryAddAction(argparse._AppendAction):
6663

6764
def __call__(self, parser, namespace, values, option_string=None):
68-
from azext_scheduled_query.vendored_sdks.azure_mgmt_scheduled_query.models import Action
69-
action = Action(
70-
action_group_id=values[0],
71-
web_hook_properties=dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None
65+
from azext_scheduled_query.vendored_sdks.azure_mgmt_scheduled_query.models import Actions
66+
action = Actions(
67+
action_groups=values[0],
68+
custom_properties=dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None
7269
)
73-
super(ScheduleQueryAddAction, self).__call__(parser, namespace, action, option_string)
70+
super().__call__(parser, namespace, action, option_string)

src/scheduled-query/azext_scheduled_query/_client_factory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@
66

77
def cf_scheduled_query(cli_ctx, *_):
88
from azure.cli.core.commands.client_factory import get_mgmt_service_client
9-
from .vendored_sdks.azure_mgmt_scheduled_query._monitor_client import MonitorClient
10-
return get_mgmt_service_client(cli_ctx, MonitorClient).scheduled_query_rules
9+
from .vendored_sdks.azure_mgmt_scheduled_query._monitor_management_client import MonitorManagementClient
10+
return get_mgmt_service_client(cli_ctx, MonitorManagementClient).scheduled_query_rules

src/scheduled-query/azext_scheduled_query/_help.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@
1616
type: command
1717
short-summary: Create a scheduled query.
1818
parameters:
19-
- name: --action -a
20-
short-summary: Add an action group and optional webhook properties to fire when the alert is triggered.
19+
- name: --action-groups
20+
short-summary: Action Group resource Ids to invoke when the alert fires.
2121
long-summary: |
22-
Usage: --action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]
23-
24-
Multiple action groups can be specified by using more than one `--action` argument.
22+
Usage: --action-groups ACTION_GROUP_NAME_OR_ID [NAME_OR_ID,...]
23+
- name: --custom-properties
24+
short-summary: The properties of an alert payload.
25+
long-summary: |
26+
Usage: --custom-properties ALERT_PAYLOAD_PROPERTIES [KEY=VAL,KEY=VAL ...]
2527
- name: --condition
2628
short-summary: The condition which triggers the rule.
2729
long-summary: |
@@ -44,12 +46,14 @@
4446
type: command
4547
short-summary: Update a scheduled query.
4648
parameters:
47-
- name: --action -a
48-
short-summary: Add an action group and optional webhook properties to fire when the alert is triggered.
49+
- name: --action-groups
50+
short-summary: Action Group resource Ids to invoke when the alert fires.
4951
long-summary: |
50-
Usage: --action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]
51-
52-
Multiple action groups can be specified by using more than one `--action` argument.
52+
Usage: --action-groups ACTION_GROUP_NAME_OR_ID [NAME_OR_ID,...]
53+
- name: --custom-properties
54+
short-summary: The properties of an alert payload.
55+
long-summary: |
56+
Usage: --custom-properties ALERT_PAYLOAD_PROPERTIES [KEY=VAL,KEY=VAL ...]
5357
- name: --condition
5458
short-summary: The condition which triggers the rule.
5559
long-summary: |

src/scheduled-query/azext_scheduled_query/_params.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,21 @@
66

77
from azure.cli.core.commands.parameters import tags_type, get_three_state_flag
88
from azure.cli.command_modules.monitor.actions import get_period_type
9-
from azure.cli.command_modules.monitor.validators import get_action_group_validator
9+
from azext_scheduled_query._validators import validate_custom_properties
1010
from knack.arguments import CLIArgumentType
11-
from ._actions import ScheduleQueryConditionAction, ScheduleQueryAddAction, ScheduleQueryConditionQueryAction
11+
from ._actions import ScheduleQueryConditionAction, ScheduleQueryConditionQueryAction
1212

1313

1414
def load_arguments(self, _):
1515

1616
from azure.cli.core.commands.validators import get_default_location_from_resource_group
1717

1818
name_arg_type = CLIArgumentType(options_list=['--name', '-n'], metavar='NAME')
19+
custom_properties_arg_type = CLIArgumentType(
20+
validator=validate_custom_properties,
21+
options_list=['--custom-properties'],
22+
nargs='*',
23+
help='The properties of an alert payload.')
1924
with self.argument_context('monitor scheduled-query') as c:
2025
c.argument('rule_name', name_arg_type, id_part='name', help='Name of the scheduled query rule.')
2126
c.argument('location', validator=get_default_location_from_resource_group)
@@ -35,4 +40,12 @@ def load_arguments(self, _):
3540
c.argument('mute_actions_duration', type=get_period_type(as_timedelta=True),
3641
options_list=['--mute-actions-duration', '--mad'],
3742
help='Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
38-
c.argument('actions', options_list=['--action', '-a'], action=ScheduleQueryAddAction, nargs='+', validator=get_action_group_validator('actions'))
43+
c.argument('action_groups', options_list=['--action-groups'], nargs='+', help='Action Group resource Ids to invoke when the alert fires.')
44+
c.argument('custom_properties', custom_properties_arg_type)
45+
c.argument('auto_mitigate', arg_type=get_three_state_flag(),
46+
help='The flag that indicates whether the alert should be automatically resolved or not. The default is true.')
47+
c.argument('skip_query_validation', arg_type=get_three_state_flag(),
48+
help='The flag which indicates whether the provided query should be validated or not.')
49+
c.argument('check_workspace_alerts_storage', options_list=['--check-ws-alerts-storage', '--cwas'],
50+
arg_type=get_three_state_flag(),
51+
help="The flag which indicates whether this scheduled query rule should be stored in the customer's storage.")
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# --------------------------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for license information.
4+
# --------------------------------------------------------------------------------------------
5+
6+
7+
def validate_tag(string):
8+
result = {}
9+
if string:
10+
comps = string.split('=', 1)
11+
result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''}
12+
return result
13+
14+
15+
def validate_custom_properties(ns):
16+
if isinstance(ns.custom_properties, list):
17+
custom_properties_dict = {}
18+
for item in ns.custom_properties:
19+
custom_properties_dict.update(validate_tag(item))
20+
ns.custom_properties = custom_properties_dict

src/scheduled-query/azext_scheduled_query/custom.py

Lines changed: 73 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,52 @@ def _build_criteria(condition, condition_query):
2525
return ScheduledQueryRuleCriteria(all_of=condition)
2626

2727

28-
def create_scheduled_query(client, resource_group_name, rule_name, scopes, condition, condition_query=None,
29-
disabled=False, description=None, tags=None, location=None,
30-
actions=None, severity=2, window_size='5m', evaluation_frequency='5m',
31-
target_resource_type=None, mute_actions_duration='PT30M'):
32-
from .vendored_sdks.azure_mgmt_scheduled_query.models import ScheduledQueryRuleResource
28+
def create_scheduled_query(client,
29+
resource_group_name,
30+
rule_name,
31+
scopes,
32+
condition,
33+
action_groups=None,
34+
custom_properties=None,
35+
condition_query=None,
36+
disabled=False,
37+
description=None,
38+
tags=None,
39+
location=None,
40+
severity=2,
41+
window_size='5m',
42+
evaluation_frequency='5m',
43+
target_resource_type=None,
44+
mute_actions_duration=None,
45+
auto_mitigate=True,
46+
skip_query_validation=False,
47+
check_workspace_alerts_storage=False):
3348
criteria = _build_criteria(condition, condition_query)
34-
kwargs = {
35-
'description': description,
36-
'severity': severity,
37-
'enabled': not disabled,
38-
'scopes': scopes,
39-
'evaluation_frequency': evaluation_frequency,
40-
'window_size': window_size,
41-
'criteria': criteria,
42-
'target_resource_types': [target_resource_type] if target_resource_type else None,
43-
'actions': actions,
44-
'tags': tags,
45-
'location': location,
46-
'mute_actions_duration': mute_actions_duration
47-
}
48-
return client.create_or_update(resource_group_name, rule_name, ScheduledQueryRuleResource(**kwargs))
49+
parameters = {}
50+
actions = {}
51+
actions['action_groups'] = action_groups if action_groups is not None else []
52+
actions['custom_properties'] = custom_properties if custom_properties is not None else {}
53+
parameters['actions'] = actions
54+
parameters['scopes'] = scopes
55+
parameters['criteria'] = criteria
56+
if actions is not None:
57+
parameters['actions'] = actions
58+
parameters['enabled'] = not disabled
59+
if description is not None:
60+
parameters['description'] = description
61+
if tags is not None:
62+
parameters['tags'] = tags
63+
if location is not None:
64+
parameters['location'] = location
65+
parameters['severity'] = severity
66+
parameters['window_size'] = window_size
67+
parameters['evaluation_frequency'] = evaluation_frequency
68+
parameters['target_resource_types'] = [target_resource_type] if target_resource_type else None
69+
parameters['mute_actions_duration'] = mute_actions_duration
70+
parameters['auto_mitigate'] = auto_mitigate
71+
parameters['skip_query_validation'] = skip_query_validation
72+
parameters['check_workspace_alerts_storage_configured'] = check_workspace_alerts_storage
73+
return client.create_or_update(resource_group_name=resource_group_name, rule_name=rule_name, parameters=parameters)
4974

5075

5176
def list_scheduled_query(client, resource_group_name=None):
@@ -54,19 +79,43 @@ def list_scheduled_query(client, resource_group_name=None):
5479
return client.list_by_subscription()
5580

5681

57-
def update_scheduled_query(cmd, instance, tags=None, disabled=False, condition=None, condition_query=None,
58-
description=None, actions=None, severity=None, window_size=None,
59-
evaluation_frequency=None, mute_actions_duration=None):
82+
def update_scheduled_query(cmd,
83+
instance,
84+
tags=None,
85+
disabled=None,
86+
condition=None,
87+
action_groups=None,
88+
custom_properties=None,
89+
condition_query=None,
90+
description=None,
91+
severity=None,
92+
window_size=None,
93+
evaluation_frequency=None,
94+
mute_actions_duration=None,
95+
target_resource_type=None,
96+
auto_mitigate=None,
97+
skip_query_validation=None,
98+
check_workspace_alerts_storage=None
99+
):
60100
with cmd.update_context(instance) as c:
61101
c.set_param('tags', tags)
62102
c.set_param('enabled', not disabled)
63103
c.set_param('description', description)
64-
c.set_param('actions', actions)
104+
c.set_param('actions.action_groups', action_groups)
105+
c.set_param('actions.custom_properties', custom_properties)
65106
c.set_param('severity', severity)
66107
c.set_param('window_size', window_size)
67108
c.set_param('evaluation_frequency', evaluation_frequency)
68109
c.set_param('mute_actions_duration', mute_actions_duration)
110+
c.set_param('target_resource_type', target_resource_type)
111+
c.set_param('auto_mitigate', auto_mitigate)
112+
c.set_param('skip_query_validation', skip_query_validation)
113+
c.set_param('check_workspace_alerts_storage_configured', check_workspace_alerts_storage)
69114
if condition is not None:
70115
criteria = _build_criteria(condition, condition_query)
71116
c.set_param('criteria', criteria)
117+
if disabled is not None:
118+
c.set_param('enabled', not disabled)
119+
if auto_mitigate is not None:
120+
c.set_param('auto_mitigate', auto_mitigate)
72121
return instance

0 commit comments

Comments
 (0)