diff --git a/.flake8 b/.flake8 index 4be1b3b4647..a55e5df96f0 100644 --- a/.flake8 +++ b/.flake8 @@ -28,3 +28,4 @@ exclude = vendored_sdks tests */command_modules/*/aaz + */_legacy diff --git a/pylintrc b/pylintrc index 1db71b778f6..32259397994 100644 --- a/pylintrc +++ b/pylintrc @@ -1,5 +1,5 @@ [MASTER] -ignore=tests,generated,vendored_sdks,privates +ignore=tests,generated,vendored_sdks,privates,_legacy ignore-patterns=test.*,azure_devops_build.* ignore-paths=.*/command_modules/.*/aaz reports=no diff --git a/src/azure-cli-core/azure/cli/core/aaz/__init__.py b/src/azure-cli-core/azure/cli/core/aaz/__init__.py index 6c53627cc6b..70d655aa0f9 100644 --- a/src/azure-cli-core/azure/cli/core/aaz/__init__.py +++ b/src/azure-cli-core/azure/cli/core/aaz/__init__.py @@ -21,7 +21,8 @@ AAZPaginationTokenArgFormat from ._base import has_value, AAZValuePatch, AAZUndefined from ._command import AAZCommand, AAZWaitCommand, AAZCommandGroup, \ - register_callback, register_command, register_command_group, load_aaz_command_table, link_helper + register_callback, register_command, register_command_group, load_aaz_command_table, \ + load_aaz_command_table_args_guided, link_helper from ._field_type import AAZIntType, AAZFloatType, AAZStrType, AAZBoolType, AAZDictType, AAZFreeFormDictType, \ AAZListType, AAZObjectType, AAZIdentityObjectType, AAZAnyType from ._operation import AAZHttpOperation, AAZJsonInstanceUpdateOperation, AAZGenericInstanceUpdateOperation, \ diff --git a/src/azure-cli-core/azure/cli/core/aaz/_command.py b/src/azure-cli-core/azure/cli/core/aaz/_command.py index 577d8a7cf45..943da6105ec 100644 --- a/src/azure-cli-core/azure/cli/core/aaz/_command.py +++ b/src/azure-cli-core/azure/cli/core/aaz/_command.py @@ -387,6 +387,181 @@ def decorator(cls): AAZ_PACKAGE_FULL_LOAD_ENV_NAME = 'AZURE_AAZ_FULL_LOAD' +def load_aaz_command_table_args_guided(loader, aaz_pkg_name, args): + """Args-guided AAZ command tree loader. + + Instead of importing the entire AAZ package tree (all __init__.py files which eagerly + import all command classes), this function navigates only to the relevant subtree based + on CLI args. For example, ``az monitor log-analytics workspace create --help`` only loads + the ``workspace`` sub-package and the ``_create`` module, skipping all other commands. + + This requires that AAZ ``__init__.py`` files do NOT contain wildcard imports + (``from ._create import *`` etc.) -- they should be empty (just the license header). + """ + profile_pkg = _get_profile_pkg(aaz_pkg_name, loader.cli_ctx.cloud) + + command_table = {} + command_group_table = {} + if args is None or os.environ.get(AAZ_PACKAGE_FULL_LOAD_ENV_NAME, 'False').lower() == 'true': + effective_args = None # fully load + else: + effective_args = list(args) + if profile_pkg is not None: + _load_aaz_by_pkg(loader, profile_pkg, effective_args, + command_table, command_group_table) + + for group_name, command_group in command_group_table.items(): + loader.command_group_table[group_name] = command_group + for command_name, command in command_table.items(): + loader.command_table[command_name] = command + return command_table, command_group_table + + +def _try_import_module(relative_name, package): + """Try to import a module by relative name, return None on failure.""" + try: + return importlib.import_module(relative_name, package) + except ModuleNotFoundError as ex: + # Only treat "module not found" for the requested module as a benign miss. + target_mod_name = f"{package}.{relative_name.lstrip('.')}" + if ex.name == target_mod_name: + return None + # Different module is missing; propagate so the real error surfaces. + raise + except ImportError: + logger.error("Error importing module %r from package %r", relative_name, package) + raise + + +def _register_from_module(loader, mod, command_table, command_group_table): + """Scan a module's namespace for AAZCommand/AAZCommandGroup classes and register them.""" + for value in mod.__dict__.values(): + if not isinstance(value, type): + continue + if value.__module__ != mod.__name__: # skip imported classes + continue + if issubclass(value, AAZCommandGroup) and value.AZ_NAME: + command_group_table[value.AZ_NAME] = value(cli_ctx=loader.cli_ctx) + elif issubclass(value, AAZCommand) and value.AZ_NAME: + command_table[value.AZ_NAME] = value(loader=loader) + + +def _get_pkg_children(pkg): + """List child entries of a package using pkgutil. + + Returns two sets: (file_stems, subdir_names). + - file_stems: module-like stems, e.g. {'_create', '_list', '__cmd_group'} + - subdir_names: sub-package directory names, e.g. {'namespace', 'eventhub'} + """ + import pkgutil + file_stems = set() + subdir_names = set() + + pkg_path = getattr(pkg, '__path__', None) + if not pkg_path: + return file_stems, subdir_names + + for _importer, name, ispkg in pkgutil.iter_modules(pkg_path): + if ispkg: + if not name.startswith('_'): + subdir_names.add(name) + else: + file_stems.add(name) + + return file_stems, subdir_names + + +def _load_aaz_by_pkg(loader, pkg, args, command_table, command_group_table): + """Recursively navigate the AAZ package tree guided by CLI args. + + - args is None -> full recursive load of all commands under this package. + - args is empty list -> args exhausted; load current level's commands and sub-group headers. + - args has items -> try to match first arg as a command module or sub-package, + recurse with remaining args on match. + - no match on first arg -> load current level's commands and sub-group headers. + """ + base_module = pkg.__name__ + file_stems, subdir_names = _get_pkg_children(pkg) + + if args is not None and args and not args[0].startswith('-'): + first_arg = args[0].lower().replace('-', '_') + + # First arg matches a command module (e.g. "create" -> "_create") + if f"_{first_arg}" in file_stems: + mod = _try_import_module(f"._{first_arg}", base_module) + if mod: + _register_from_module(loader, mod, command_table, command_group_table) + return + + # First arg matches a sub-package (command group) + if first_arg in subdir_names: + sub_module = f"{base_module}.{first_arg}" + mod = _try_import_module('.__cmd_group', sub_module) + if mod: + _register_from_module(loader, mod, command_table, command_group_table) + sub_pkg = _try_import_module(f'.{first_arg}', base_module) + if sub_pkg: + _load_aaz_by_pkg(loader, sub_pkg, args[1:], command_table, command_group_table) + return + + # Load __cmd_group + all command modules at this level + mod = _try_import_module('.__cmd_group', base_module) + if mod: + _register_from_module(loader, mod, command_table, command_group_table) + + for stem in file_stems: + if stem.startswith('_') and not stem.startswith('__'): + mod = _try_import_module(f'.{stem}', base_module) + if mod: + _register_from_module(loader, mod, command_table, command_group_table) + + for subdir in subdir_names: + sub_module = f"{base_module}.{subdir}" + if args is None: + # Full load -> recurse into every sub-package + sub_pkg = _try_import_module(f'.{subdir}', base_module) + if sub_pkg: + _load_aaz_by_pkg(loader, sub_pkg, None, command_table, command_group_table) + else: + # Args exhausted / not matched -> load sub-group header and the first + # command so the group is non-empty and the parser creates a subparser + # for it (required for help output). + # TODO: After optimized loading is applied to the whole CLI, revisit + # this and consider a lighter approach (e.g. parser-level fix) to + # avoid importing one command per trimmed sub-group. + mod = _try_import_module('.__cmd_group', sub_module) + if mod: + _register_from_module(loader, mod, command_table, command_group_table) + sub_pkg = _try_import_module(f'.{subdir}', base_module) + if sub_pkg: + _load_first_command(loader, sub_pkg, command_table) + + +def _load_first_command(loader, pkg, command_table): + """Load the first available command module from a package. + + This ensures the command group is non-empty so the parser creates a subparser + for it, which is required for it to appear in help output. + """ + file_stems, subdir_names = _get_pkg_children(pkg) + base_module = pkg.__name__ + + # Try to load a command module at this level first + for stem in sorted(file_stems): + if stem.startswith('_') and not stem.startswith('__'): + mod = _try_import_module(f'.{stem}', base_module) + if mod: + _register_from_module(loader, mod, command_table, {}) + return + + # No command at this level, recurse into the first sub-package + for subdir in sorted(subdir_names): + sub_pkg = _try_import_module(f'.{subdir}', base_module) + if sub_pkg: + _load_first_command(loader, sub_pkg, command_table) + return + + def load_aaz_command_table(loader, aaz_pkg_name, args): """ This function is used in AzCommandsLoader.load_command_table. It will load commands in module's aaz package. diff --git a/src/azure-cli/azure/cli/command_modules/monitor/LEGACY_FALLBACK.md b/src/azure-cli/azure/cli/command_modules/monitor/LEGACY_FALLBACK.md new file mode 100644 index 00000000000..c63a7b832d4 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/LEGACY_FALLBACK.md @@ -0,0 +1,55 @@ +# Monitor Module: Legacy Fallback + +## Overview + +The monitor module ships a vendored copy of the pre-refactor code in `_legacy/`. Users can switch to this snapshot via config if the refactored implementation causes issues: + +```bash +az config set monitor.use_legacy=true # enable legacy mode +az config set monitor.use_legacy=false # switch back to new mode (default) +``` + +A warning is logged each time legacy mode is active. + +## How It Works + +In `__init__.py`, `MonitorCommandsLoader` reads the `monitor.use_legacy` config (default `false`): + +- **New mode** — loads from `aaz/`, `operations/`, and `commands.py` using `load_aaz_command_table_args_guided`. +- **Legacy mode** — loads from `_legacy/aaz/`, `_legacy/commands.py` using `load_aaz_command_table`. Arguments come from `_legacy/_params.py`. + +The `_legacy/` folder is a frozen snapshot extracted from the `dev` branch. All absolute imports were rewritten from `azure.cli.command_modules.monitor.` to `azure.cli.command_modules.monitor._legacy.`. + +## Known Adjustments + +- **`_legacy/_params.py`**: Removed `monitor metrics alert update` argument registrations (lines for `add_actions`, `remove_actions`, `add_conditions`, `remove_conditions`) because the AAZ `MetricsAlertUpdate._build_arguments_schema` already defines them, and the old-style `action=MetricAlertAddAction` overrides corrupt AAZ argument parsing. +- **Tests**: `test_monitor_general_operations.py` mocks `gen_guid` at both `azure.cli.command_modules.monitor.operations.monitor_clone_util` and `azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util` so tests pass in either mode. +- **Linting**: `_legacy/` is excluded via `pylintrc` (`ignore` list) and `.flake8` (`exclude` list). + +## Dropping Legacy Support + +When legacy mode is no longer needed: + +1. **Delete the `_legacy/` folder**: + ```bash + rm -rf src/azure-cli/azure/cli/command_modules/monitor/_legacy/ + ``` + +2. **Simplify `__init__.py`** — remove `_use_legacy`, `_load_legacy_command_table`, and the dispatch in `load_command_table` / `load_arguments`. Inline `_load_new_command_table` as the sole `load_command_table`: + ```python + # Remove these + _CONFIG_SECTION = 'monitor' + _USE_LEGACY_CONFIG_KEY = 'use_legacy' + self._use_legacy = ... + def _load_legacy_command_table(self, args): ... + + # Keep only _load_new_command_table logic directly in load_command_table + ``` + +3. **Clean up tests** — remove the second `mock.patch` line for `_legacy` in `test_monitor_general_operations.py`: + ```python + # Remove this line from each mock.patch block: + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', ...) + ``` + +4. **Revert linter config** — remove `_legacy` from `pylintrc` `ignore` and `*/_legacy` from `.flake8` `exclude`. diff --git a/src/azure-cli/azure/cli/command_modules/monitor/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/__init__.py index f36e4de78f3..06e805a602d 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/__init__.py @@ -3,10 +3,16 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from knack.log import get_logger + from azure.cli.core import AzCommandsLoader from azure.cli.core.commands import AzArgumentContext, CliCommandType +from azure.cli.command_modules.monitor._help import helps # pylint: disable=unused-import + +logger = get_logger(__name__) -from azure.cli.command_modules.monitor._help import helps # pylint: disable=unused-import +_CONFIG_SECTION = 'monitor' +_USE_LEGACY_CONFIG_KEY = 'use_legacy' # pylint: disable=line-too-long @@ -33,31 +39,84 @@ class MonitorCommandsLoader(AzCommandsLoader): def __init__(self, cli_ctx=None): from azure.cli.core.profiles import ResourceType - monitor_custom = CliCommandType( - operations_tmpl='azure.cli.command_modules.monitor.custom#{}') + self._use_legacy = cli_ctx.config.getboolean( + _CONFIG_SECTION, _USE_LEGACY_CONFIG_KEY, fallback=False) if cli_ctx else False + if self._use_legacy: + monitor_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.custom#{}') + else: + monitor_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor.custom#{}') super().__init__(cli_ctx=cli_ctx, resource_type=ResourceType.MGMT_MONITOR, argument_context_cls=MonitorArgumentContext, custom_command_type=monitor_custom) def load_command_table(self, args): - from azure.cli.command_modules.monitor.commands import load_command_table + if self._use_legacy: + return self._load_legacy_command_table(args) + return self._load_new_command_table(args) + + def _load_legacy_command_table(self, args): + """Load commands from the vendored _legacy snapshot (pre-refactor code from dev branch).""" from azure.cli.core.aaz import load_aaz_command_table + + logger.warning( + "The monitor module is using legacy mode. " + "To switch to the new optimized implementation, run: " + "az config set %s.%s=false", + _CONFIG_SECTION, _USE_LEGACY_CONFIG_KEY) + + try: + from ._legacy import aaz as legacy_aaz + except ImportError: + legacy_aaz = None + if legacy_aaz: + load_aaz_command_table( + loader=self, + aaz_pkg_name=legacy_aaz.__name__, + args=args + ) + + from ._legacy.commands import load_command_table + load_command_table(self, args) + return self.command_table + + def _load_new_command_table(self, args): + """Load commands from the current (refactored) implementation.""" + from azure.cli.command_modules.monitor.commands import load_command_table + from azure.cli.core.aaz import load_aaz_command_table_args_guided + try: from . import aaz except ImportError: aaz = None if aaz: - load_aaz_command_table( + load_aaz_command_table_args_guided( loader=self, aaz_pkg_name=aaz.__name__, args=args ) + + try: + from . import operations + except ImportError: + operations = None + if operations: + load_aaz_command_table_args_guided( + loader=self, + aaz_pkg_name=operations.__name__, + args=args + ) + load_command_table(self, args) return self.command_table def load_arguments(self, command): - from azure.cli.command_modules.monitor._params import load_arguments + if self._use_legacy: + from azure.cli.command_modules.monitor._legacy._params import load_arguments + else: + from azure.cli.command_modules.monitor._params import load_arguments load_arguments(self, command) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/__init__.py new file mode 100644 index 00000000000..e4487ad9f04 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/__init__.py @@ -0,0 +1,61 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core import AzCommandsLoader +from azure.cli.core.commands import AzArgumentContext, CliCommandType + +from azure.cli.command_modules.monitor._legacy._help import helps # pylint: disable=unused-import + + +# pylint: disable=line-too-long +class MonitorArgumentContext(AzArgumentContext): + + def resource_parameter(self, dest, arg_group=None, required=True, skip_validator=False, alias='resource', + preserve_resource_group_parameter=False): + from azure.cli.command_modules.monitor._legacy.validators import get_target_resource_validator + self.argument(dest, options_list='--{}'.format(alias), arg_group=arg_group, required=required, + validator=get_target_resource_validator( + dest, required, alias=alias, + preserve_resource_group_parameter=preserve_resource_group_parameter) if not skip_validator else None, + help="Name or ID of the target resource.") + self.extra('namespace', options_list='--{}-namespace'.format(alias), arg_group=arg_group, + help="Target resource provider namespace.") + self.extra('parent', options_list='--{}-parent'.format(alias), arg_group=arg_group, + help="Target resource parent path, if applicable.") + self.extra('resource_type', options_list='--{}-type'.format(alias), arg_group=arg_group, + help="Target resource type. Can also accept namespace/type format (Ex: 'Microsoft.Compute/virtualMachines')") + self.extra('resource_group_name', options_list=['--resource-group', '-g'], arg_group=arg_group) + + +class MonitorCommandsLoader(AzCommandsLoader): + + def __init__(self, cli_ctx=None): + from azure.cli.core.profiles import ResourceType + monitor_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.custom#{}') + super().__init__(cli_ctx=cli_ctx, + resource_type=ResourceType.MGMT_MONITOR, + argument_context_cls=MonitorArgumentContext, + custom_command_type=monitor_custom) + + def load_command_table(self, args): + from azure.cli.command_modules.monitor._legacy.commands import load_command_table + from azure.cli.core.aaz import load_aaz_command_table + try: + from . import aaz + except ImportError: + aaz = None + if aaz: + load_aaz_command_table( + loader=self, + aaz_pkg_name=aaz.__name__, + args=args + ) + load_command_table(self, args) + return self.command_table + + def load_arguments(self, command): + from azure.cli.command_modules.monitor._legacy._params import load_arguments + load_arguments(self, command) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_autoscale_util.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_autoscale_util.py new file mode 100644 index 00000000000..6f6d18d69aa --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_autoscale_util.py @@ -0,0 +1,785 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.log import get_logger +from azure.cli.core.aaz import has_value +logger = get_logger(__name__) + + +# Workaround for REST API issue: https://github.com/Azure/azure-rest-api-specs/issues/2530 +AUTOSCALE_TIMEZONES = [ + { + "name": "Dateline Standard Time", + "offset": "-12:00" + }, + { + "name": "UTC-11", + "offset": "-11:00" + }, + { + "name": "Aleutian Standard Time", + "offset": "-10:00" + }, + { + "name": "Hawaiian Standard Time", + "offset": "-10:00" + }, + { + "name": "Marquesas Standard Time", + "offset": "-09:30" + }, + { + "name": "Alaskan Standard Time", + "offset": "-09:00" + }, + { + "name": "UTC-09", + "offset": "-09:00" + }, + { + "name": "Pacific Standard Time (Mexico)", + "offset": "-08:00" + }, + { + "name": "UTC-08", + "offset": "-08:00" + }, + { + "name": "Pacific Standard Time", + "offset": "-08:00" + }, + { + "name": "US Mountain Standard Time", + "offset": "-07:00" + }, + { + "name": "Mountain Standard Time (Mexico)", + "offset": "-07:00" + }, + { + "name": "Mountain Standard Time", + "offset": "-07:00" + }, + { + "name": "Central America Standard Time", + "offset": "-06:00" + }, + { + "name": "Central Standard Time", + "offset": "-06:00" + }, + { + "name": "Easter Island Standard Time", + "offset": "-06:00" + }, + { + "name": "Central Standard Time (Mexico)", + "offset": "-06:00" + }, + { + "name": "Canada Central Standard Time", + "offset": "-06:00" + }, + { + "name": "SA Pacific Standard Time", + "offset": "-05:00" + }, + { + "name": "Eastern Standard Time (Mexico)", + "offset": "-05:00" + }, + { + "name": "Eastern Standard Time", + "offset": "-05:00" + }, + { + "name": "Haiti Standard Time", + "offset": "-05:00" + }, + { + "name": "Cuba Standard Time", + "offset": "-05:00" + }, + { + "name": "US Eastern Standard Time", + "offset": "-05:00" + }, + { + "name": "Turks and Caicos Standard Time", + "offset": "-05:00" + }, + { + "name": "Paraguay Standard Time", + "offset": "-04:00" + }, + { + "name": "Atlantic Standard Time", + "offset": "-04:00" + }, + { + "name": "Venezuela Standard Time", + "offset": "-04:00" + }, + { + "name": "Central Brazilian Standard Time", + "offset": "-04:00" + }, + { + "name": "SA Western Standard Time", + "offset": "-04:00" + }, + { + "name": "Pacific SA Standard Time", + "offset": "-04:00" + }, + { + "name": "Newfoundland Standard Time", + "offset": "-03:30" + }, + { + "name": "Tocantins Standard Time", + "offset": "-03:00" + }, + { + "name": "E. South America Standard Time", + "offset": "-03:00" + }, + { + "name": "SA Eastern Standard Time", + "offset": "-03:00" + }, + { + "name": "Argentina Standard Time", + "offset": "-03:00" + }, + { + "name": "Greenland Standard Time", + "offset": "-03:00" + }, + { + "name": "Montevideo Standard Time", + "offset": "-03:00" + }, + { + "name": "Magallanes Standard Time", + "offset": "-03:00" + }, + { + "name": "Saint Pierre Standard Time", + "offset": "-03:00" + }, + { + "name": "Bahia Standard Time", + "offset": "-03:00" + }, + { + "name": "UTC-02", + "offset": "-02:00" + }, + { + "name": "Mid-Atlantic Standard Time", + "offset": "-02:00" + }, + { + "name": "Azores Standard Time", + "offset": "-01:00" + }, + { + "name": "Cabo Verde Standard Time", + "offset": "-01:00" + }, + { + "name": "Coordinated Universal Time", + "offset": "+00:00" + }, + { + "name": "Morocco Standard Time", + "offset": "+00:00" + }, + { + "name": "GMT Standard Time", + "offset": "+00:00" + }, + { + "name": "Greenwich Standard Time", + "offset": "+00:00" + }, + { + "name": "W. Europe Standard Time", + "offset": "+01:00" + }, + { + "name": "Central Europe Standard Time", + "offset": "+01:00" + }, + { + "name": "Romance Standard Time", + "offset": "+01:00" + }, + { + "name": "Central European Standard Time", + "offset": "+01:00" + }, + { + "name": "W. Central Africa Standard Time", + "offset": "+01:00" + }, + { + "name": "Jordan Standard Time", + "offset": "+02:00" + }, + { + "name": "GTB Standard Time", + "offset": "+02:00" + }, + { + "name": "Middle East Standard Time", + "offset": "+02:00" + }, + { + "name": "Egypt Standard Time", + "offset": "+02:00" + }, + { + "name": "E. Europe Standard Time", + "offset": "+02:00" + }, + { + "name": "Syria Standard Time", + "offset": "+02:00" + }, + { + "name": "West Bank Gaza Standard Time", + "offset": "+02:00" + }, + { + "name": "South Africa Standard Time", + "offset": "+02:00" + }, + { + "name": "FLE Standard Time", + "offset": "+02:00" + }, + { + "name": "Jerusalem Standard Time", + "offset": "+02:00" + }, + { + "name": "Russia TZ 1 Standard Time", + "offset": "+02:00" + }, + { + "name": "Sudan Standard Time", + "offset": "+02:00" + }, + { + "name": "Libya Standard Time", + "offset": "+02:00" + }, + { + "name": "Namibia Standard Time", + "offset": "+02:00" + }, + { + "name": "Arabic Standard Time", + "offset": "+03:00" + }, + { + "name": "Turkey Standard Time", + "offset": "+03:00" + }, + { + "name": "Arab Standard Time", + "offset": "+03:00" + }, + { + "name": "Belarus Standard Time", + "offset": "+03:00" + }, + { + "name": "Russia TZ 2 Standard Time", + "offset": "+03:00" + }, + { + "name": "E. Africa Standard Time", + "offset": "+03:00" + }, + { + "name": "Iran Standard Time", + "offset": "+03:30" + }, + { + "name": "Arabian Standard Time", + "offset": "+04:00" + }, + { + "name": "Astrakhan Standard Time", + "offset": "+04:00" + }, + { + "name": "Azerbaijan Standard Time", + "offset": "+04:00" + }, + { + "name": "Russia TZ 3 Standard Time", + "offset": "+04:00" + }, + { + "name": "Mauritius Standard Time", + "offset": "+04:00" + }, + { + "name": "Saratov Standard Time", + "offset": "+04:00" + }, + { + "name": "Georgian Standard Time", + "offset": "+04:00" + }, + { + "name": "Caucasus Standard Time", + "offset": "+04:00" + }, + { + "name": "Afghanistan Standard Time", + "offset": "+04:30" + }, + { + "name": "West Asia Standard Time", + "offset": "+05:00" + }, + { + "name": "Russia TZ 4 Standard Time", + "offset": "+05:00" + }, + { + "name": "Pakistan Standard Time", + "offset": "+05:00" + }, + { + "name": "India Standard Time", + "offset": "+05:30" + }, + { + "name": "Sri Lanka Standard Time", + "offset": "+05:30" + }, + { + "name": "Nepal Standard Time", + "offset": "+05:45" + }, + { + "name": "Central Asia Standard Time", + "offset": "+06:00" + }, + { + "name": "Bangladesh Standard Time", + "offset": "+06:00" + }, + { + "name": "Omsk Standard Time", + "offset": "+06:00" + }, + { + "name": "Myanmar Standard Time", + "offset": "+06:30" + }, + { + "name": "SE Asia Standard Time", + "offset": "+07:00" + }, + { + "name": "Altai Standard Time", + "offset": "+07:00" + }, + { + "name": "W. Mongolia Standard Time", + "offset": "+07:00" + }, + { + "name": "Russia TZ 6 Standard Time", + "offset": "+07:00" + }, + { + "name": "Novosibirsk Standard Time", + "offset": "+07:00" + }, + { + "name": "Tomsk Standard Time", + "offset": "+07:00" + }, + { + "name": "China Standard Time", + "offset": "+08:00" + }, + { + "name": "Russia TZ 7 Standard Time", + "offset": "+08:00" + }, + { + "name": "Malay Peninsula Standard Time", + "offset": "+08:00" + }, + { + "name": "W. Australia Standard Time", + "offset": "+08:00" + }, + { + "name": "Taipei Standard Time", + "offset": "+08:00" + }, + { + "name": "Ulaanbaatar Standard Time", + "offset": "+08:00" + }, + { + "name": "North Korea Standard Time", + "offset": "+08:30" + }, + { + "name": "Aus Central W. Standard Time", + "offset": "+08:45" + }, + { + "name": "Transbaikal Standard Time", + "offset": "+09:00" + }, + { + "name": "Tokyo Standard Time", + "offset": "+09:00" + }, + { + "name": "Korea Standard Time", + "offset": "+09:00" + }, + { + "name": "Russia TZ 8 Standard Time", + "offset": "+09:00" + }, + { + "name": "Cen. Australia Standard Time", + "offset": "+09:30" + }, + { + "name": "AUS Central Standard Time", + "offset": "+09:30" + }, + { + "name": "E. Australia Standard Time", + "offset": "+10:00" + }, + { + "name": "AUS Eastern Standard Time", + "offset": "+10:00" + }, + { + "name": "West Pacific Standard Time", + "offset": "+10:00" + }, + { + "name": "Tasmania Standard Time", + "offset": "+10:00" + }, + { + "name": "Russia TZ 9 Standard Time", + "offset": "+10:00" + }, + { + "name": "Lord Howe Standard Time", + "offset": "+10:30" + }, + { + "name": "Bougainville Standard Time", + "offset": "+11:00" + }, + { + "name": "Russia TZ 10 Standard Time", + "offset": "+11:00" + }, + { + "name": "Magadan Standard Time", + "offset": "+11:00" + }, + { + "name": "Norfolk Standard Time", + "offset": "+11:00" + }, + { + "name": "Sakhalin Standard Time", + "offset": "+11:00" + }, + { + "name": "Central Pacific Standard Time", + "offset": "+11:00" + }, + { + "name": "Russia TZ 11 Standard Time", + "offset": "+12:00" + }, + { + "name": "New Zealand Standard Time", + "offset": "+12:00" + }, + { + "name": "UTC+12", + "offset": "+12:00" + }, + { + "name": "Fiji Standard Time", + "offset": "+12:00" + }, + { + "name": "Kamchatka Standard Time", + "offset": "+12:00" + }, + { + "name": "Chatham Islands Standard Time", + "offset": "+12:45" + }, + { + "name": "UTC+13", + "offset": "+13:00" + }, + { + "name": "Tonga Standard Time", + "offset": "+13:00" + }, + { + "name": "Samoa Standard Time", + "offset": "+13:00" + }, + { + "name": "Line Islands Standard Time", + "offset": "+14:00" + } +] + + +def get_autoscale_default_profile(autoscale_settings): + import json + + def _validate_default_profile(default_profile, profile): + if profile["capacity"]["default"] != default_profile["capacity"]["default"] or \ + profile["capacity"]["minimum"] != default_profile["capacity"]["minimum"] \ + or profile["capacity"]["maximum"] != default_profile["capacity"]["maximum"]: + from knack.util import CLIError + raise CLIError('unable to resolve default profile.') + + recurring_profiles = [x for x in autoscale_settings.properties.profiles if has_value(x.recurrence)] + default_profiles = [x for x in autoscale_settings.properties.profiles + if not has_value(x.recurrence) and not has_value(x.fixed_date)] + + # find the default profile and ensure that if there are multiple, they are consistent + default_profile = default_profiles[0].to_serialized_data() if default_profiles else None + + for p in default_profiles: + p_serialized = p.to_serialized_data() + _validate_default_profile(default_profile, p_serialized) + + for profile in recurring_profiles: + # portal creates extra default profiles with JSON names... + # trying to stay compatible with that + try: + # portal-created "default" or end time + json_name = json.loads(profile.name.to_serialized_data()) + _ = json_name['for'] + profile_serialized = profile.to_serialized_data() + if not default_profile: + # choose this as default if it is the first + + default_profile = { + "name": 'default', + "capacity": profile_serialized["capacity"], + "rules": profile_serialized["rules"] + } + else: + # otherwise ensure it is consistent with the one chosen earlier + _validate_default_profile(default_profile, profile_serialized) + except ValueError: + pass + + return default_profile + + +def build_autoscale_profile(autoscale_settings): + """ Builds up a logical model of the autoscale weekly schedule. This then has to later be + translated into objects that work with the Monitor autoscale API. """ + from datetime import time + import json + from azure.mgmt.monitor.models import AutoscaleProfile + + def _validate_default_profile(default_profile, profile): + if profile.capacity.default != default_profile.capacity.default or \ + profile.capacity.minimum != default_profile.capacity.minimum or \ + profile.capacity.maximum != default_profile.capacity.maximum: + from knack.util import CLIError + raise CLIError('unable to resolve default profile.') + + recurring_profiles = [x for x in autoscale_settings.profiles if x.recurrence] + default_profiles = [x for x in autoscale_settings.profiles if not x.recurrence and not x.fixed_date] + + profile_schedule = { + } + + # find the default profile and ensure that if there are multiple, they are consistent + default_profile = default_profiles[0] if default_profiles else None + for p in default_profiles: + _validate_default_profile(default_profile, p) + + for profile in recurring_profiles: + # portal creates extra default profiles with JSON names... + # trying to stay compatible with that + try: + # portal-created "default" or end time + json_name = json.loads(profile.name) + sched_name = json_name['for'] + end_time = time(hour=profile.recurrence.schedule.hours[0], minute=profile.recurrence.schedule.minutes[0]) + + if not default_profile: + # choose this as default if it is the first + default_profile = AutoscaleProfile( + name='default', + capacity=profile.capacity, + rules=profile.rules + ) + else: + # otherwise ensure it is consistent with the one chosen earlier + _validate_default_profile(default_profile, profile) + + for day in profile.recurrence.schedule.days: + if day not in profile_schedule: + profile_schedule[day] = {} + if sched_name in profile_schedule[day]: + profile_schedule[day][sched_name]['end'] = end_time + else: + profile_schedule[day][sched_name] = {'end': end_time} + except ValueError: + # start time + sched_name = profile.name + start_time = time(hour=profile.recurrence.schedule.hours[0], minute=profile.recurrence.schedule.minutes[0]) + for day in profile.recurrence.schedule.days: + if day not in profile_schedule: + profile_schedule[day] = {} + if sched_name in profile_schedule[day]: + profile_schedule[day][sched_name]['start'] = start_time + profile_schedule[day][sched_name]['capacity'] = profile.capacity + profile_schedule[day][sched_name]['rules'] = profile.rules + else: + profile_schedule[day][sched_name] = { + 'start': start_time, + 'capacity': profile.capacity, + 'rules': profile.rules + } + + return default_profile, profile_schedule + + +def build_autoscale_profile_dict(autoscale_settings): + """ Builds up a logical model of the autoscale weekly schedule. This then has to later be + translated into objects that work with the Monitor autoscale API. """ + from datetime import time + import json + + def _validate_default_profile(default_profile, profile): + if profile["capacity"]["default"] != default_profile["capacity"]["default"] or \ + profile["capacity"]["minimum"] != default_profile["capacity"]["minimum"] or \ + profile["capacity"]["maximum"] != default_profile["capacity"]["maximum"]: + from knack.util import CLIError + raise CLIError('unable to resolve default profile.') + + recurring_profiles = [x for x in autoscale_settings["profiles"] if x.get("recurrence", None)] + default_profiles = [x for x in autoscale_settings["profiles"] if not x.get("recurrence", + None) and not x.get("fixed_date", None)] + + profile_schedule = { + } + + # find the default profile and ensure that if there are multiple, they are consistent + default_profile = default_profiles[0] if default_profiles else None + for p in default_profiles: + _validate_default_profile(default_profile, p) + + for profile in recurring_profiles: + # portal creates extra default profiles with JSON names... + # trying to stay compatible with that + try: + # portal-created "default" or end time + json_name = json.loads(profile["name"]) + sched_name = json_name['for'] + end_time = time(hour=profile["recurrence"]["schedule"]["hours"][0], + minute=profile["recurrence"]["schedule"]["minutes"][0]) + + if not default_profile: + # choose this as default if it is the first + default_profile = { + "name": 'default', + "capacity": profile["capacity"], + "rules": profile["rules"] + } + else: + # otherwise ensure it is consistent with the one chosen earlier + _validate_default_profile(default_profile, profile) + + for day in profile["recurrence"]["schedule"]["days"]: + if day not in profile_schedule: + profile_schedule[day] = {} + if sched_name in profile_schedule[day]: + profile_schedule[day][sched_name]['end'] = end_time + else: + profile_schedule[day][sched_name] = {'end': end_time} + except ValueError: + # start time + sched_name = profile["name"] + start_time = time(hour=profile["recurrence"]["schedule"]["hours"][0], + minute=profile["recurrence"]["schedule"]["minutes"][0]) + for day in profile["recurrence"]["schedule"]["days"]: + if day not in profile_schedule: + profile_schedule[day] = {} + if sched_name in profile_schedule[day]: + profile_schedule[day][sched_name]['start'] = start_time + profile_schedule[day][sched_name]['capacity'] = profile["capacity"] + profile_schedule[day][sched_name]['rules'] = profile["rules"] + else: + profile_schedule[day][sched_name] = { + 'start': start_time, + 'capacity': profile["capacity"], + 'rules': profile["rules"] + } + + return default_profile, profile_schedule + + +def validate_autoscale_profile_dict(schedule, start, end, recurrence): + """ Check whether the proposed schedule conflicts with existing schedules. If so, + issue a warning. """ + # pylint: disable=cell-var-from-loop + for day in recurrence["schedule"]["days"]: + if day not in schedule: + schedule[day] = {} + + def _find_conflicting_profile(time): + conflict_sched = None + for sched_name, sched_values in schedule[day].items(): + if sched_values['start'] <= time <= sched_values['end']: + conflict_sched = sched_name + return conflict_sched + + def _profile_is_subset(profile, start, end): + return profile['start'] >= start and profile['end'] <= end + + # check if start or end dates fall within an existing schedule + # check is proposed schedule engulfs any existing schedules + profile_conflicts = [k for k, v in schedule[day].items() if _profile_is_subset(v, start, end)] + start_conflict = _find_conflicting_profile(start) + if start_conflict: + profile_conflicts.append(start_conflict) + end_conflict = _find_conflicting_profile(end) + if end_conflict: + profile_conflicts.append(end_conflict) + + if profile_conflicts: + logger.warning("Proposed schedule '%s %s-%s' has a full or partial overlap with the following existing " + "schedules: %s. Unexpected behavior may occur.", + day, start, end, ', '.join(profile_conflicts)) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_client_factory.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_client_factory.py new file mode 100644 index 00000000000..e27f7f1bae3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_client_factory.py @@ -0,0 +1,125 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +# MANAGEMENT CLIENT FACTORIES +def cf_monitor(cli_ctx, **kwargs): + from azure.cli.core.profiles import ResourceType + from azure.cli.core.commands.client_factory import get_mgmt_service_client + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_MONITOR, **kwargs) + + +def cf_alert_rule_incidents(cli_ctx, _): + return cf_monitor(cli_ctx).alert_rule_incidents + + +def cf_autoscale(cli_ctx, _): + return cf_monitor(cli_ctx).autoscale_settings + + +def cf_diagnostics(cli_ctx, _): + return cf_monitor(cli_ctx).diagnostic_settings + + +def cf_diagnostics_category(cli_ctx, _): + return cf_monitor(cli_ctx).diagnostic_settings_category + + +def cf_subscription_diagnostics(cli_ctx, _): + return cf_monitor(cli_ctx).subscription_diagnostic_settings + + +def cf_log_profiles(cli_ctx, _): + return cf_monitor(cli_ctx).log_profiles + + +def cf_action_groups(cli_ctx, _): + return cf_monitor(cli_ctx).action_groups + + +def cf_activity_log_alerts(cli_ctx, _): + return cf_monitor(cli_ctx).activity_log_alerts + + +def cf_metrics(cli_ctx, _): + return cf_monitor(cli_ctx).metrics + + +def cf_metric_def(cli_ctx, _): + return cf_monitor(cli_ctx).metric_definitions + + +def cf_metric_ns(cli_ctx, _): + return cf_monitor(cli_ctx).metric_namespaces + + +def cf_activity_log(cli_ctx, _): + return cf_monitor(cli_ctx).activity_logs + + +def cf_event_categories(cli_ctx, _): + return cf_monitor(cli_ctx).event_categories + + +def cf_metric_alerts(cli_ctx, _): + return cf_monitor(cli_ctx).metric_alerts + + +def _log_analytics_client_factory(cli_ctx, **kwargs): + from azure.mgmt.loganalytics import LogAnalyticsManagementClient + from azure.cli.core.commands.client_factory import get_mgmt_service_client + return get_mgmt_service_client(cli_ctx, LogAnalyticsManagementClient, **kwargs) + + +def cf_log_analytics_workspace(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).workspaces + + +def cf_log_analytics_deleted_workspaces(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).deleted_workspaces + + +def cf_log_analytics_workspace_tables(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).tables + + +def cf_log_analytics_workspace_data_exports(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).data_exports + + +def cf_log_analytics_workspace_management_groups(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).management_groups + + +def cf_log_analytics_workspace_usage(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).usages + + +def cf_log_analytics_workspace_schema(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).schema + + +def cf_log_analytics_workspace_shared_keys(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).shared_keys + + +def cf_log_analytics_workspace_intelligence_packs(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).intelligence_packs + + +def cf_log_analytics_workspace_saved_searches(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).saved_searches + + +def cf_log_analytics_workspace_linked_service(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).linked_services + + +def cf_log_analytics_cluster(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).clusters + + +def cf_log_analytics_linked_storage(cli_ctx, _): + return _log_analytics_client_factory(cli_ctx).linked_storage_accounts diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_exception_handler.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_exception_handler.py new file mode 100644 index 00000000000..785040f31e3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_exception_handler.py @@ -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. +# -------------------------------------------------------------------------------------------- + + +def exception_handler(ex): + from azure.core.exceptions import HttpResponseError, ODataV4Format + if isinstance(ex, HttpResponseError): + # Workaround for issue: https://github.com/Azure/azure-sdk-for-python/issues/1556 in track2 + if hasattr(ex, 'model'): + additional_properties = getattr(ex.model, 'additional_properties', {}) + if 'Code' in additional_properties and 'Message' in additional_properties: + ex.error = ODataV4Format({'code': additional_properties['Code'], + 'message': additional_properties['Message']}) + raise HttpResponseError(message=additional_properties['Message'], error=ex.error, response=ex.response) + elif hasattr(ex, 'error'): + additional_properties = getattr(ex.error, 'additional_properties', {}) + if 'Code' in additional_properties and 'Message' in additional_properties: + ex.error.code = additional_properties['Code'] + ex.error.message = additional_properties['Message'] + ex.message = additional_properties['Message'] + raise ex diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_help.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_help.py new file mode 100644 index 00000000000..f4d9cab1956 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_help.py @@ -0,0 +1,627 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.help_files import helps # pylint: disable=unused-import +# pylint: disable=line-too-long, too-many-lines + +helps['monitor'] = """ +type: group +short-summary: Manage the Azure Monitor Service. +""" + +helps['monitor action-group'] = """ +type: group +short-summary: Manage action groups +""" + +helps['monitor action-group wait'] = """ +type: command +short-summary: Place the CLI in a waiting state. +""" + +helps['monitor activity-log'] = """ +type: group +short-summary: Manage activity logs. +""" + +helps['monitor activity-log alert'] = """ +type: group +short-summary: Manage activity log alert rules. +""" + +helps['monitor activity-log alert list'] = """ +type: command +short-summary: List activity log alert rules under a resource group or the current subscription. +parameters: + - name: --resource-group -g + short-summary: Name of the resource group under which the activity log alert rules are being listed. If it is omitted, all the activity log alert rules under the current subscription are listed. +""" + +helps['monitor activity-log list'] = """ +type: command +short-summary: List and query activity log events. +parameters: + - name: --correlation-id + short-summary: Correlation ID to query. + - name: --resource-id + short-summary: ARM ID of a resource. + - name: --namespace + short-summary: Resource provider namespace. + - name: --caller + short-summary: Caller to query for, such as an e-mail address or service principal ID. + - name: --status + short-summary: > + Status to query for (ex: Failed) + - name: --max-events + short-summary: Maximum number of records to return. + - name: --select + short-summary: Space-separated list of properties to return. + - 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. +examples: + - name: List all events from July 1st, looking forward one week. + text: az monitor activity-log list --start-time 2018-07-01 --offset 7d + - name: List events within the past six hours based on a correlation ID. + text: az monitor activity-log list --correlation-id b5eac9d2-e829-4c9a-9efb-586d19417c5f + - name: List events within the past hour based on resource group. + text: az monitor activity-log list -g {ResourceGroup} --offset 1h +""" + +helps['monitor autoscale'] = """ +type: group +short-summary: Manage autoscale settings. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +""" + +helps['monitor autoscale create'] = """ +type: command +short-summary: Create new autoscale settings. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +parameters: + - name: --action -a + short-summary: Add an action to fire when a scaling event occurs. + long-summary: | + Usage: --action TYPE KEY [ARG ...] + Email: --action email bob@contoso.com ann@contoso.com + Webhook: --action webhook https://www.contoso.com/alert apiKey=value + Webhook: --action webhook https://www.contoso.com/alert?apiKey=value + Multiple actions can be specified by using more than one `--action` argument. +examples: + - name: Create autoscale settings to scale between 2 and 5 instances (3 as default). Email the administrator when scaling occurs. + text: | + az monitor autoscale create -g {myrg} --resource {resource-id} --min-count 2 --max-count 5 \\ + --count 3 --email-administrator + + az monitor autoscale rule create -g {myrg} --autoscale-name {resource-name} --scale out 1 \\ + --condition "Percentage CPU > 75 avg 5m" + + az monitor autoscale rule create -g {myrg} --autoscale-name {resource-name} --scale in 1 \\ + --condition "Percentage CPU < 25 avg 5m" + - name: Create autoscale settings for exactly 4 instances. + text: > + az monitor autoscale create -g {myrg} --resource {resource-id} --count 4 + - name: Create new autoscale settings. (autogenerated) + text: | + az monitor autoscale create --count 3 --max-count 5 --min-count 2 --name MyAutoscaleSettings --resource myScaleSet --resource-group MyResourceGroup --resource-type Microsoft.Compute/virtualMachineScaleSets + crafted: true +""" + +helps['monitor autoscale profile'] = """ +type: group +short-summary: Manage autoscaling profiles. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +""" + +helps['monitor autoscale profile create'] = """ +type: command +short-summary: Create a fixed or recurring autoscale profile. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +parameters: + - name: --timezone + short-summary: Timezone name. + populator-commands: + - az monitor autoscale profile list-timezones + - name: --recurrence -r + short-summary: When the profile recurs. If omitted, a fixed (non-recurring) profile is created. + long-summary: | + Usage: --recurrence {week} [ARG ARG ...] + Weekly: --recurrence week Sat Sun + - name: --start + short-summary: When the autoscale profile begins. Format depends on the type of profile. + long-summary: | + Fixed: --start yyyy-mm-dd [hh:mm:ss] + Weekly: [--start hh:mm] + - name: --end + short-summary: When the autoscale profile ends. Format depends on the type of profile. + long-summary: | + Fixed: --end yyyy-mm-dd [hh:mm:ss] + Weekly: [--end hh:mm] +examples: + - name: Create a fixed date profile, inheriting the default scaling rules but changing the capacity. + text: | + az monitor autoscale create -g {myrg} --resource {resource-id} --min-count 2 --count 3 \\ + --max-count 5 + + az monitor autoscale rule create -g {myrg} --autoscale-name {name} --scale out 1 \\ + --condition "Percentage CPU > 75 avg 5m" + + az monitor autoscale rule create -g {myrg} --autoscale-name {name} --scale in 1 \\ + --condition "Percentage CPU < 25 avg 5m" + + az monitor autoscale profile create -g {myrg} --autoscale-name {name} -n Christmas \\ + --copy-rules default --min-count 3 --count 6 --max-count 10 --start 2018-12-24 \\ + --end 2018-12-26 --timezone "Pacific Standard Time" + - name: Create a recurring weekend profile, inheriting the default scaling rules but changing the capacity. + text: | + az monitor autoscale create -g {myrg} --resource {resource-id} --min-count 2 --count 3 \\ + --max-count 5 + + az monitor autoscale rule create -g {myrg} --autoscale-name {name} --scale out 1 \\ + --condition "Percentage CPU > 75 avg 5m" + + az monitor autoscale rule create -g {myrg} --autoscale-name {name} --scale in 1 \\ + --condition "Percentage CPU < 25 avg 5m" + + az monitor autoscale profile create -g {myrg} --autoscale-name {name} -n weeekend \\ + --copy-rules default --min-count 1 --count 2 --max-count 2 \\ + --recurrence week sat sun --timezone "Pacific Standard Time" + - name: Create a fixed or recurring autoscale profile. (autogenerated) + text: | + az monitor autoscale profile create --autoscale-name MyAutoscale --copy-rules default --count 2 --end 2018-12-26 --max-count 10 --min-count 1 --name Christmas --recurrence week sat sun --resource-group MyResourceGroup --start 2018-12-24 --timezone "Pacific Standard Time" + crafted: true + - name: Create a fixed or recurring autoscale profile. (autogenerated) + text: | + az monitor autoscale profile create --autoscale-name MyAutoscale --count 2 --max-count 10 --min-count 1 --name Christmas --recurrence week sat sun --resource-group MyResourceGroup --start 2018-12-24 --subscription MySubscription --timezone "Pacific Standard Time" + crafted: true +""" + +helps['monitor autoscale profile delete'] = """ +type: command +short-summary: Delete an autoscale profile. +examples: + - name: Delete an autoscale profile. (autogenerated) + text: | + az monitor autoscale profile delete --autoscale-name MyAutoscale --name MyAutoscaleProfile --resource-group MyResourceGroup + crafted: true +""" + +helps['monitor autoscale profile list'] = """ +type: command +short-summary: List autoscale profiles. +examples: + - name: List autoscale profiles. (autogenerated) + text: | + az monitor autoscale profile list --autoscale-name MyAutoscale --resource-group MyResourceGroup + crafted: true +""" + +helps['monitor autoscale profile list-timezones'] = """ +type: command +short-summary: Look up time zone information. +""" + +helps['monitor autoscale profile show'] = """ +type: command +short-summary: Show details of an autoscale profile. +""" + +helps['monitor autoscale rule'] = """ +type: group +short-summary: Manage autoscale scaling rules. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +""" + +helps['monitor autoscale rule copy'] = """ +type: command +short-summary: Copy autoscale rules from one profile to another. +""" + +helps['monitor autoscale rule create'] = """ +type: command +short-summary: Add a new autoscale rule. +long-summary: > + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings +parameters: + - name: --condition + short-summary: The condition which triggers the scaling action. + long-summary: > + Usage: --condition ["NAMESPACE"] METRIC {==,!=,>,>=,<,<=} THRESHOLD + {avg,min,max,total,count} PERIOD + [where DIMENSION {==,!=} VALUE [or VALUE ...] + [and DIMENSION {==,!=} VALUE [or VALUE ...] ...]] + + Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be queried by combining them with the 'and' keyword. + Values for METRIC and appropriate THRESHOLD values can be obtained from the `az monitor metric` command. + Format of PERIOD is "##h##m##s". + - name: --scale + short-summary: The direction and amount to scale. + long-summary: | + Usage: --scale {to,in,out} VAL[%] + Fixed Count: --scale to 5 + In by Count: --scale in 2 + Out by Percent: --scale out 10% + - name: --timegrain + short-summary: > + The way metrics are polled across instances. + long-summary: > + The form of the timegrain is {avg,min,max,sum} VALUE. Values can be obtained from the `az monitor metric` command. + Format of VALUE is "##h##m##s". +examples: + - name: Scale to 5 instances when the CPU Percentage across instances is greater than 75 averaged over 10 minutes. + text: | + az monitor autoscale rule create -g {myrg} --autoscale-name {myvmss} \\ + --scale to 5 --condition "Percentage CPU > 75 avg 10m" + - name: Scale up 2 instances when the CPU Percentage across instances is greater than 75 averaged over 5 minutes. + text: | + az monitor autoscale rule create -g {myrg} --autoscale-name {myvmss} \\ + --scale out 2 --condition "Percentage CPU > 75 avg 5m" + - name: Scale down 50% when the CPU Percentage across instances is less than 25 averaged over 15 minutes. + text: | + az monitor autoscale rule create -g {myrg} --autoscale-name {myvmss} \\ + --scale in 50% --condition "Percentage CPU < 25 avg 15m" + - name: Create autoscale settings via a guest vm metric enabled from diagnostic extensions. + You can use counterSpecifier field retrieved from 'az vmss diagnostics get-default-config' in the `--condition`. + text: | + az monitor autoscale rule create -g {myrg} --autoscale-name test --scale out 1 --condition "/builtin/memory/percentavailablememory > 80 total 5m" + +""" + +helps['monitor autoscale rule delete'] = """ +type: command +short-summary: Remove autoscale rules from a profile. +""" + +helps['monitor autoscale rule list'] = """ +type: command +short-summary: List autoscale rules for a profile. +examples: + - name: List autoscale rules for a profile. (autogenerated) + text: | + az monitor autoscale rule list --autoscale-name MyAutoscale --profile-name MyProfile --resource-group MyResourceGroup + crafted: true +""" + +helps['monitor log-analytics workspace recover'] = """ +type: command +short-summary: Recover a workspace in a soft-delete state within 14 days. +examples: + - name: Recover a workspace in a soft-delete state within 14 days + text: | + az monitor log-analytics workspace recover --resource-group MyResourceGroup -n MyWorkspace +""" + +helps['monitor log-analytics workspace table'] = """ +type: group +short-summary: Manage tables for log analytics workspace. +""" + +helps['monitor log-analytics workspace table create'] = """ +type: command +short-summary: Create a Log Analytics workspace microsoft/custom log table. The table name needs to end with '_CL'. +examples: + - name: Create a Log Analytics workspace custom log table. + text: | + az monitor log-analytics workspace table create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_CL --retention-time 45 --columns MyColumn1=string TimeGenerated=datetime +""" + +helps['monitor log-analytics workspace table search-job'] = """ +type: group +short-summary: Manage tables for log analytics workspace search results table. +""" + +helps['monitor log-analytics workspace table search-job create'] = """ +type: command +short-summary: Create a Log Analytics workspace search results table. The table name needs to end with '_SRCH'. +examples: + - name: Create a Log Analytics workspace search result table. + text: | + az monitor log-analytics workspace table search-job create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_SRCH --retention-time 45 --search-query "Heartbeat | where SourceSystem != '' | project SourceSystem" --limit 1000 --start-search-time "Sat, 28 Aug 2021 05:29:18 GMT" --end-search-time "Sat, 28 Aug 2021 08:29:18 GMT" +""" + +helps['monitor log-analytics workspace table restore'] = """ +type: group +short-summary: Manage tables for log analytics workspace restore logs table. +""" + +helps['monitor log-analytics workspace table restore create'] = """ +type: command +short-summary: Create a Log Analytics workspace restore logs table. The table name needs to end with '_RST'. +examples: + - name: Create a Log Analytics workspace restore logs table. + text: | + az monitor log-analytics workspace table restore create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_RST --start-restore-time "Sat, 28 Aug 2021 05:29:18 GMT" --end-restore-time "Sat, 28 Aug 2021 08:29:18 GMT" --restore-source-table MyTable +""" + +helps['monitor log-analytics workspace table update'] = """ +type: command +short-summary: Update the properties of a Log Analytics workspace table. +examples: + - name: Update the properties of a Log Analytics workspace table. + text: | + az monitor log-analytics workspace table update --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable --retention-time 30 +""" + +helps['monitor log-analytics workspace saved-search create'] = """ +type: command +short-summary: Create a saved search for a given workspace. +examples: + - name: Create a saved search for a given workspace. + text: az monitor log-analytics workspace saved-search create -g MyRG --workspace-name MyWS -n MySavedSearch --category Test1 --display-name TestSavedSearch -q "AzureActivity | summarize count() by bin(TimeGenerated, 1h)" --fa myfun --fp "a:string = value" +""" + +helps['monitor log-analytics workspace saved-search update'] = """ +type: command +short-summary: Update a saved search for a given workspace. +examples: + - name: Update a saved search for a given workspace. + text: az monitor log-analytics workspace saved-search update -g MyRG --workspace-name MyWS -n MySavedSearch --category Test1 --display-name TestSavedSearch -q "AzureActivity | summarize count() by bin(TimeGenerated, 1h)" --fa myfun --fp "a:string = value" +""" + +helps['monitor log-analytics workspace linked-storage add'] = """ +type: command +short-summary: Add some linked storage accounts with specific data source type for log analytics workspace. +examples: + - name: Add two linked storage accounts for a log analytics workspace using the name of the storage account. + text: az monitor log-analytics workspace linked-storage add --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts StorageAccount1 StorageAccount2 + - name: Add one linked storage accounts for a log analytics workspace using the resource id of the storage account. + text: az monitor log-analytics workspace linked-storage add --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.Storage/storageAccounts/cli000001 +""" + +helps['monitor log-analytics workspace linked-storage remove'] = """ +type: command +short-summary: Remove some linked storage accounts with specific data source type for log analytics workspace +examples: + - name: Remove two linked storage accounts for a log analytics workspace using the name of the storage account. + text: az monitor log-analytics workspace linked-storage remove --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts StorageAccount1 StorageAccount2 + - name: Remove one linked storage accounts for a log analytics workspace using the resource id of the storage account. + text: az monitor log-analytics workspace linked-storage remove --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.Storage/storageAccounts/cli000001 +""" + +helps['monitor metrics'] = """ +type: group +short-summary: View Azure resource metrics. +""" + +helps['monitor metrics alert'] = """ +type: group +short-summary: Manage near-realtime metric alert rules. +""" + +helps['monitor metrics alert create'] = """ +type: command +short-summary: Create a metric-based alert rule. +parameters: + - name: --action -a + short-summary: Add an action group and optional webhook properties to fire when the alert is triggered. + long-summary: | + Usage: --action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]] + + Multiple action groups can be specified by using more than one `--action` argument. + - name: --disabled + short-summary: Create the rule in a disabled state. + - name: --condition + short-summary: The condition which triggers the rule. + It can be created by 'az monitor metrics alert condition create' command. + long-summary: | + Usage: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC + [{=,!=,>,>=,<,<=} THRESHOLD] + [{>,><,<} dynamic SENSITIVITY VIOLATIONS of EVALUATIONS [since DATETIME]] + [where DIMENSION {includes,excludes} VALUE [or VALUE ...] + [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]] + [with skipmetricvalidation] + + Sensitivity can be 'low', 'medium', 'high'. + + Violations can be the number of violations to trigger an alert. It should be smaller or equal to evaluation. + + Evaluations can be the number of evaluation periods for dynamic threshold. + + Datetime can be the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format). + + Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be queried by combining them with the 'and' keyword. + + Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az monitor metrics list-definitions` command. + + Due to server limitation, when an alert rule contains multiple criterias, the use of dimensions is limited to one value per dimension within each criterion. + + Multiple conditions can be specified by using more than one `--condition` argument. +examples: + - name: Create a high CPU usage alert on a VM with no action. + text: > + az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID} --condition "avg Percentage CPU > 90" --description "High CPU" + - name: Create a high CPU usage alert on a VM with email and webhook actions. + text: | + az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID} \\ + --condition "avg Percentage CPU > 90" --window-size 5m --evaluation-frequency 1m \\ + --action "/subscriptions//resourceGroups//providers/Microsoft.Insights/actionGroups/" apiKey={APIKey} type=HighCPU \\ + --description "High CPU" + - name: Create an alert when a storage account shows a high number of slow transactions, using multi-dimensional filters. + text: | + az monitor metrics alert create -g {ResourceGroup} -n alert1 --scopes {StorageAccountId} \\ + --description "Storage Slow Transactions" \\ + --condition "total transactions > 5 where ResponseType includes Success" \\ + --condition "avg SuccessE2ELatency > 250 where ApiName includes GetBlob" + - name: Create a metric-based alert rule that monitors a custom metric. + text: | + az monitor metrics alert create -n "metric alert rule on a custom metric" -g "Demos" --scopes {VirtualMachineID} \\ + --condition "max Azure.VM.Windows.GuestMetrics.Memory\\Available Bytes > 90" \\ + --window-size 5m --evaluation-frequency 1m + - name: Create a high CPU usage alert on several VMs with no actions. + text: | + az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID1} {VirtualMachineID2} {VirtualMachineID3} \\ + --condition "avg Percentage CPU > 90" --description "High CPU" --region westus + - name: Create a dynamic CPU usage alert on several VMs with no actions. + text: | + az monitor metrics alert create -n alert1 -g {ResourceGroup} --scopes {VirtualMachineID1} {VirtualMachineID2} {VirtualMachineID3} \\ + --condition "avg Percentage CPU > dynamic medium 2 of 4 since 2020-10-01T10:23:00.000Z" + --description "Dynamic CPU" + --window-size 5m + --region westus + +""" + +helps['monitor metrics alert dimension'] = """ +type: group +short-summary: Manage near-realtime metric alert rule dimensions. +""" + +helps['monitor metrics alert dimension create'] = """ +type: command +short-summary: Build a metric alert rule dimension. +examples: + - name: Build a metric alert rule dimension. + text: | + $dim = az monitor metrics alert dimension create -n dimName --op Include -v GetBlob PutBlob +""" + +helps['monitor metrics alert condition'] = """ +type: group +short-summary: Manage near-realtime metric alert rule conditions. +""" + +helps['monitor metrics alert condition create'] = """ +type: command +short-summary: Build a metric alert rule condition. +parameters: + - name: --metric + short-summary: Name of the metric to base the rule on. + populator-commands: + - az monitor metrics list-definitions +examples: + - name: Build a static condition. + text: | + $dim1 = az monitor metrics alert dimension create -n dimName --op Include -v GetBlob PutBlob + $dim2 = az monitor metrics alert dimension create -n Instance --op Exclude -v Get Put + $condition = az monitor metrics alert condition create -t static \n + --aggregation Count \n + --metric "CPU Percentage" \n + --op GreaterThan \n + --threshold 95 \n + --dimension "$dim1" "$dim2" + - name: Build a dynamic condition. + text: | + $condition = az monitor metrics alert condition create -t dynamic \n + --aggregation Average \n + --metric "CPU Percentage" \n + --op GreaterOrLessThan \n + --num-violations 4 \n + --num-periods 4 \n + --since 2020-11-02T12:11 +""" + +helps['monitor metrics list'] = """ +type: command +short-summary: List the metric values for a resource. +parameters: + - name: --aggregation + short-summary: The list of aggregation types (space-separated) to retrieve. + populator-commands: + - az monitor metrics list-definitions + - 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. "BlobType eq '*'" + long-summary: 'For a full list of filters, see the filter string reference at https://learn.microsoft.com/rest/api/monitor/metrics/list' + - name: --metadata + short-summary: Returns 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 monitor metrics list-definitions + - name: --namespace + short-summary: Namespace to query metric definitions for. + populator-commands: + - az monitor metrics list-namespaces + - 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 monitor metrics list-definitions + +examples: + - name: List a VM's CPU usage for the past hour + text: > + az monitor metrics list --resource {ResourceName} --metric "Percentage CPU" + - name: List success E2E latency of a storage account and split the data series based on API name + text: > + az monitor metrics list --resource {ResourceName} --metric SuccessE2ELatency \\ + --dimension ApiName + - name: List success E2E latency of a storage account and split the data series based on both API name and geo type + text: > + az monitor metrics list --resource {ResourceName} --metric SuccessE2ELatency \\ + --dimension ApiName GeoType + - name: List success E2E latency of a storage account and split the data series based on both API name and geo type using "--filter" parameter + text: > + az monitor metrics list --resource {ResourceName} --metric SuccessE2ELatency \\ + --filter "ApiName eq '*' and GeoType eq '*'" + - name: List success E2E latency of a storage account and split the data series based on both API name and geo type. Limits the api name to 'DeleteContainer' + text: > + az monitor metrics list --resource {ResourceName} --metric SuccessE2ELatency \\ + --filter "ApiName eq 'DeleteContainer' and GeoType eq '*'" + - name: List transactions of a storage account per day since 2017-01-01 + text: > + az monitor metrics list --resource {ResourceName} --metric Transactions \\ + --start-time 2017-01-01T00:00:00Z \\ + --interval PT24H + - name: List the metadata values for a storage account under transaction metric's api name dimension since 2017 + text: > + az monitor metrics list --resource {ResourceName} --metric Transactions \\ + --filter "ApiName eq '*'" \\ + --start-time 2017-01-01T00:00:00Z +""" + +helps['monitor metrics list-definitions'] = """ +type: command +short-summary: List the metric definitions for the resource. +parameters: + - name: --namespace + short-summary: Namespace to query metric definitions for. + populator-commands: + - az monitor metrics list-namespaces +examples: + - name: List the metric definitions for the resource. (autogenerated) + text: | + az monitor metrics list-definitions --resource /subscriptions/{subscriptionID}/resourceGroups/{resourceGroup}/Microsoft.Network/networkSecurityGroups/{resourceName} + crafted: true +""" + +helps['monitor metrics list-namespaces'] = """ +type: command +short-summary: List the metric namespaces for the resource. +examples: + - name: List the metric namespaces for the resource. + text: | + az monitor metrics list-namespaces --resource /subscriptions/{subscriptionID}/resourceGroups/{resourceGroup}/Microsoft.Network/networkSecurityGroups/{resourceName} --start-time 2021-03-01T00:00:00Z +""" + +helps['monitor clone'] = """ +type: command +short-summary: Clone metrics alert rules from one resource to another resource. +examples: + - name: Clone the metric alert settings from one VM to another + text: | + az monitor clone --source-resource /subscriptions/{subscriptionID}/resourceGroups/Space1999/providers/Microsoft.Compute/virtualMachines/vm1 --target-resource /subscriptions/{subscriptionID}/resourceGroups/Space1999/providers/Microsoft.Compute/virtualMachines/vm2 +""" diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_params.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_params.py new file mode 100644 index 00000000000..9c3141b819a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/_params.py @@ -0,0 +1,337 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.util import get_json_object + +from azure.cli.core.commands.parameters import ( + get_location_type, tags_type, get_three_state_flag, get_enum_type, get_datetime_type, resource_group_name_type) +from azure.cli.core.commands.validators import get_default_location_from_resource_group + +from azure.cli.command_modules.monitor._legacy.actions import ( + AutoscaleScaleAction, AutoscaleConditionAction, get_period_type, AutoscaleCreateAction, + timezone_offset_type, timezone_name_type, MetricAlertConditionAction, MetricAlertAddAction) +from azure.cli.command_modules.monitor._legacy.validators import ( + validate_loganalytics_workspace_search_table_name, validate_loganalytics_workspace_restore_table_name, + validate_autoscale_recurrence, validate_autoscale_timegrain, get_action_group_validator, + get_action_group_id_validator, validate_metric_dimension, validate_storage_accounts_name_or_id) +from azure.cli.command_modules.monitor._legacy.actions import get_date_midnight_type + +from knack.arguments import CLIArgumentType + + +# pylint: disable=line-too-long, too-many-statements +def load_arguments(self, _): + from azure.mgmt.monitor.models import 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') + + autoscale_name_type = CLIArgumentType(options_list=['--autoscale-name'], help='Name of the autoscale settings.', id_part='name') + autoscale_profile_name_type = CLIArgumentType(options_list=['--profile-name'], help='Name of the autoscale profile.') + autoscale_rule_name_type = CLIArgumentType(options_list=['--rule-name'], help='Name of the autoscale rule.') + + with self.argument_context('monitor') as c: + c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group) + c.argument('tags', tags_type) + + # region Metrics + with self.argument_context('monitor metrics') as c: + c.argument('metricnamespace', options_list=['--namespace'], help='Namespace to query metric definitions for.') + + with self.argument_context('monitor metrics list-definitions') as c: + c.resource_parameter('resource_uri', arg_group='Target Resource') + + with self.argument_context('monitor metrics list') as c: + from azure.mgmt.monitor.models import AggregationType + c.resource_parameter('resource', arg_group='Target Resource') + 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', type=int, help='Max number of records to retrieve.') + c.argument('filters', options_list='--filter') + c.argument('metric_namespace', options_list='--namespace') + + with self.argument_context('monitor metrics list', 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('monitor metrics list-namespaces') as c: + c.argument("resource_uri", help="The identifier of the resource.") + c.argument('start_time', arg_type=get_datetime_type(help='Start time of the query.'), arg_group='Time') + # endregion + + # region MetricAlerts + with self.argument_context('monitor metrics alert') as c: + c.argument('rule_name', name_arg_type, id_part='name', help='Name of the alert rule.') + c.argument('severity', type=int, help='Severity of the alert from 0 (critical) to 4 (verbose).') + c.argument('window_size', help='Time over which to aggregate metrics in "##h##m##s" format.') + c.argument('evaluation_frequency', help='Frequency with which to evaluate the rule in "##h##m##s" format.') + c.argument('auto_mitigate', arg_type=get_three_state_flag(), help='Automatically resolve the alert.') + c.argument('condition', options_list=['--condition'], action=MetricAlertConditionAction, nargs='+') + c.argument('description', help='Free-text description of the rule.') + c.argument('scopes', nargs='+', help='Space-separated list of scopes the rule applies to. ' + 'The resources specified in this parameter must be of the same type and exist in the same location.') + c.argument('disabled', arg_type=get_three_state_flag()) + c.argument('enabled', arg_type=get_three_state_flag(), help='Whether the metric alert rule is enabled.') + c.argument('target_resource_type', options_list=['--target-resource-type', '--type'], + help='The resource type of the target resource(s) in scopes. ' + 'This must be provided when scopes is resource group or subscription.') + c.argument('target_resource_region', options_list=['--target-resource-region', '--region'], + help='The region of the target resource(s) in scopes. ' + 'This must be provided when scopes is resource group or subscription.') + + with self.argument_context('monitor metrics alert create', arg_group=None) as c: + c.argument('actions', options_list=['--action', '-a'], action=MetricAlertAddAction, nargs='+', validator=get_action_group_validator('actions')) + + # monitor metrics alert update args are defined by MetricsAlertUpdate._build_arguments_schema + + with self.argument_context('monitor metrics alert dimension create', arg_group=None) as c: + c.argument('dimension_name', options_list=['--name', '-n'], + help='Name of the dimension.') + c.argument('operator', options_list=['--operator', '--op'], + arg_type=get_enum_type(dim_op_conversion.values(), default=dim_op_conversion['includes']), + help="Dimension operator.") + c.argument('value_list', options_list=['--value', '-v'], nargs='+', + help='The values to apply on the operation.') + + with self.argument_context('monitor metrics alert condition create', arg_group=None) as c: + c.argument('condition_type', options_list=['--type', '-t'], arg_type=get_enum_type(['static', 'dynamic']), + help='Type of condition threshold.') + c.argument('metric_name', options_list=['--metric'], + help='Name of metric.') + c.argument('metric_namespace', options_list=['--namespace'], + help='Namespace of metric.') + c.argument('dimension_list', options_list=['--dimension'], nargs='+', + help='Dimension created by \'az monitor metrics alert dimension create\'.') + c.argument('aggregation', arg_type=get_enum_type(agg_conversion.values()), + help='Time aggregation.') + c.argument('operator', options_list=['--operator', '--op'], arg_type=get_enum_type(op_conversion.values()), + help="Operator for static threshold can be 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan' or 'LessThanOrEqual'. " + "Operator for dynamic threshold can be 'GreaterThan', 'LessThan', 'GreaterOrLessThan'.") + c.argument('threshold', type=float, + help='Static threshold value.') + c.argument('alert_sensitivity', options_list=['--sensitivity'], + arg_type=get_enum_type(sens_conversion.values(), default='Medium'), + help="Alert sensitivity for dynamic threshold.") + c.argument('number_of_evaluation_periods', options_list=['--num-periods'], type=int, + help='The number of evaluation periods for dynamic threshold. ' + 'Range: 1-6.') + c.argument('min_failing_periods_to_alert', options_list=['--num-violations'], type=int, + help='The number of violations to trigger an dynamic alert. ' + 'Range: 1-6. It should be less than or equal to --num-periods.') + c.argument('ignore_data_before', options_list=['--since'], + arg_type=get_datetime_type( + help='The date from which to start learning the metric historical data and calculate the dynamic thresholds.')) + c.argument('skip_metric_validation', options_list=['--skip-metric-validation'], + arg_type=get_three_state_flag(), + help='Cause the metric validation to be skipped. This allows to use a metric that has not been emitted yet.') + + # endregion + + # region Autoscale + with self.argument_context('monitor autoscale') as c: + c.argument('autoscale_name', arg_type=autoscale_name_type, options_list=['--name', '-n']) + c.argument('autoscale_setting_name', arg_type=autoscale_name_type, options_list=['--name', '-n']) + c.argument('profile_name', arg_type=autoscale_profile_name_type) + c.argument('rule_name', arg_type=autoscale_rule_name_type) + c.argument('enabled', arg_type=get_three_state_flag(), help='Autoscale settings enabled status.') + + with self.argument_context('monitor autoscale create', arg_group='Notification') as c: + c.argument('actions', options_list=['--action', '-a'], action=AutoscaleCreateAction, nargs='+') + + with self.argument_context('monitor autoscale', arg_group='Notification') as c: + c.argument('email_administrator', arg_type=get_three_state_flag(), help='Send email to subscription administrator on scaling.') + c.argument('email_coadministrators', arg_type=get_three_state_flag(), help='Send email to subscription co-administrators on scaling.') + + with self.argument_context('monitor autoscale create') as c: + c.resource_parameter('resource', arg_group='Target Resource') + c.argument('disabled', arg_type=get_three_state_flag(), help='Create the autoscale settings in a disabled state.') + + with self.argument_context('monitor autoscale', arg_group='Instance Limit') as c: + c.argument('count', type=int, help='The numer of instances to use. If used with --min/max-count, the default number of instances to use.') + 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']) + c.argument('copy_rules', help='Name of an existing schedule from which to copy the scaling rules for the new schedule.') + + with self.argument_context('monitor autoscale profile list-timezones') as c: + c.argument('search_query', options_list=['--search-query', '-q'], help='Query text to find.') + c.argument('offset', help='Filter results based on UTC hour offset.', type=timezone_offset_type) + + with self.argument_context('monitor autoscale profile', arg_group='Schedule') as c: + c.argument('timezone', type=timezone_name_type) + c.argument('start', arg_type=get_datetime_type(help='Start time.', timezone=False)) + c.argument('end', arg_type=get_datetime_type(help='End time.', timezone=False)) + c.argument('recurrence', options_list=['--recurrence', '-r'], nargs='+', validator=validate_autoscale_recurrence) + + with self.argument_context('monitor autoscale rule') as c: + c.argument('autoscale_name', arg_type=autoscale_name_type, id_part=None) + c.argument('rule_name', arg_type=autoscale_rule_name_type, options_list=['--name', '-n']) + c.argument('scale', help='The direction and amount to scale.', action=AutoscaleScaleAction, nargs='+') + c.argument('condition', help='Condition on which to scale.', action=AutoscaleConditionAction, nargs='+') + c.argument('timegrain', validator=validate_autoscale_timegrain, nargs='+') + c.argument('cooldown', type=int, help='The number of minutes that must elapse before another scaling event can occur.') + + with self.argument_context('monitor autoscale rule delete') as c: + c.argument('index', nargs='+', help="Space-separated list of rule indices to remove, or '*' to clear all rules.") + + with self.argument_context('monitor autoscale rule copy') as c: + c.argument('index', nargs='+', help="Space-separated list of rule indices to copy, or '*' to copy all rules.") + c.argument('source_profile', options_list=['--source-schedule'], help='Name of the profile to copy rules from.') + c.argument('dest_profile', options_list=['--dest-schedule'], help='Name of the profile to copy rules to.') + + with self.argument_context('monitor autoscale rule create') as c: + c.resource_parameter('source', arg_group='Source', required=False, preserve_resource_group_parameter=True) + # endregion + + # region Autoscale (OLD) + with self.argument_context('monitor autoscale-settings') as c: + c.argument('name', options_list=['--azure-resource-name']) + c.argument('autoscale_setting_name', options_list=['--name', '-n']) + + with self.argument_context('monitor autoscale-settings create') as c: + c.argument('parameters', type=get_json_object, help='JSON encoded parameters configuration. Use @{file} to load from a file. Use az autoscale-settings get-parameters-template to export json template.') + + for scope in ['monitor autoscale-settings show', 'monitor autoscale-settings delete']: + with self.argument_context(scope) as c: + c.argument('autoscale_setting_name', id_part='name') + + # https://github.com/Azure/azure-rest-api-specs/issues/1017 + with self.argument_context('monitor autoscale-settings list') as c: + c.ignore('filter') + # endregion + + # region ActivityLog + with self.argument_context('monitor activity-log list') as c: + activity_log_props = [x['key'] for x in EventData()._attribute_map.values()] # pylint: disable=protected-access + c.argument('select', nargs='+', arg_type=get_enum_type(activity_log_props)) + c.argument('max_events', type=int) + + with self.argument_context('monitor activity-log list', 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)) + + with self.argument_context('monitor activity-log list', arg_group='Filter') as c: + c.argument('correlation_id') + c.argument('resource_group', resource_group_name_type) + c.argument('resource_id') + c.argument('resource_provider', options_list=['--namespace']) + c.argument('caller') + c.argument('status') + # endregion + + # region ActionGroup + with self.argument_context('monitor action-group') as c: + c.argument('action_group_name', options_list=['--name', '-n'], id_part='name') + c.argument('location', get_location_type(self.cli_ctx), validator=None) + # endregion + + # region ActivityLog Alerts + with self.argument_context('monitor activity-log alert') as c: + c.argument('activity_log_alert_name', options_list=['--name', '-n'], id_part='name') + # endregion + + # region Log Analytics Workspace + with self.argument_context('monitor log-analytics workspace') as c: + c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group) + c.argument('workspace_name', options_list=['--workspace-name', '-n'], help="Name of the Log Analytics Workspace.") + c.argument('sku', help="The supported value: PerGB2018, CapacityReservation.") + c.argument('capacity_reservation_level', options_list=['--capacity-reservation-level', '--level'], help='The capacity reservation level for this workspace, when CapacityReservation sku is selected. The maximum value is 1000 and must be in multiples of 100. If you want to increase the limit, please contact LAIngestionRate@microsoft.com.') + c.argument('daily_quota_gb', options_list=['--quota'], help='The workspace daily quota for ingestion in gigabytes. The minimum value is 0.023 and default is -1 which means unlimited.') + c.argument('retention_time', help="The workspace data retention in days.", type=int, default=30) + c.argument('force', options_list=['--force', '-f'], arg_type=get_three_state_flag()) + + with self.argument_context('monitor log-analytics workspace saved-search') as c: + c.argument('saved_search_id', options_list=['--name', '-n'], help="Name of the saved search and it's unique in a given workspace.") + c.argument('workspace_name', options_list='--workspace-name') + c.argument('category', help='The category of the saved search. This helps the user to find a saved search faster.') + c.argument('display_name', help='Display name of the saved search.') + c.argument('saved_query', options_list=['--saved-query', '-q'], help='The query expression for the saved search.') + c.argument('function_alias', options_list=['--func-alias', '--fa'], + help='Function Aliases are short names given to Saved Searches so they can be easily referenced in query. They are required for Computer Groups.') + c.argument('function_parameters', options_list=['--func-param', '--fp'], + help="The optional function parameters if query serves as a function. " + "Value should be in the following format: 'param-name1:type1 = default_value1, param-name2:type2 = default_value2'. " + "For more examples and proper syntax please refer to " + "https://learn.microsoft.com/azure/kusto/query/functions/user-defined-functions.") + c.argument('tags', tags_type) + # endregion + + # region Log Analytics Workspace table + with self.argument_context('monitor log-analytics workspace table') as c: + c.argument('table_name', name_arg_type, help='Name of the table.') + c.argument('workspace_name', options_list='--workspace-name') + c.argument('retention_in_days', type=int, options_list='--retention-time', help='The table retention in days, between 4 and 730. Setting this property to -1 will default to the workspace retention.') + c.argument('total_retention_in_days', type=int, options_list='--total-retention-time', help='The table total retention in days, between 4 and 2556. Setting this property to -1 will default to table retention.') + + with self.argument_context('monitor log-analytics workspace table create') as c: + c.argument('columns', nargs='+', help='A list of table custom columns.Extracts multiple space-separated columns in column_name=column_type format') + c.argument('plan', arg_type=get_enum_type(["Basic", "Analytics"]), help='The table plan. Possible values include: "Basic", "Analytics".') + c.argument('description', help='Schema description.') + + with self.argument_context('monitor log-analytics workspace table search-job create') as c: + c.argument('table_name', name_arg_type, help='Name of the table. The table name needs to end with _SRCH', + validator=validate_loganalytics_workspace_search_table_name) + c.argument('search_query', options_list=['--search-query'], help='Search job query.') + c.argument('limit', type=int, help='Limit the search job to return up to specified number of rows.') + c.argument('start_search_time', arg_type=get_datetime_type(help='Datetime format.')) + c.argument('end_search_time', arg_type=get_datetime_type(help='Datetime format.')) + + with self.argument_context('monitor log-analytics workspace table restore create') as c: + c.argument('table_name', name_arg_type, help='Name of the table. The table name needs to end with _RST', + validator=validate_loganalytics_workspace_restore_table_name) + c.argument('start_restore_time', arg_type=get_date_midnight_type(help='Datetime format.')) + c.argument('end_restore_time', arg_type=get_date_midnight_type(help='Datetime format.')) + c.argument('restore_source_table', help='The table to restore data from.') + + with self.argument_context('monitor log-analytics workspace table update') as c: + c.argument('columns', nargs='+', help='A list of table custom columns.Extracts multiple space-separated columns in column_name=column_type format') + c.argument('plan', arg_type=get_enum_type(["Basic", "Analytics"]), help='The table plan. Possible values include: "Basic", "Analytics".') + c.argument('description', help='Table description.') + # endregion + + # region Log Analytics Workspace Linked Service + with self.argument_context('monitor log-analytics workspace linked-service') as c: + c.argument('linked_service_name', name_arg_type, help='Name of the linkedServices resource. Supported values: cluster, automation.') + c.argument('workspace_name', options_list='--workspace-name') + c.argument('resource_id', help='The resource id of the resource that will be linked to the workspace. This ' + 'should be used for linking resources which require read access.') + c.argument('write_access_resource_id', help='The resource id of the resource that will be linked to the ' + 'workspace. This should be used for linking resources which ' + 'require write access.') + # endregion + + # region Log Analytics Linked Storage Account + with self.argument_context('monitor log-analytics workspace linked-storage') as c: + c.argument('data_source_type', help='Data source type for the linked storage account.', + options_list=['--type'], arg_type=get_enum_type(["Alerts", "AzureWatson", "CustomLogs", "Ingestion", "Query"])) + c.argument('storage_account_ids', nargs='+', options_list=['--storage-accounts'], + help='List of Name or ID of Azure Storage Account.', + validator=validate_storage_accounts_name_or_id) + # endregion + + # region monitor clone + with self.argument_context('monitor clone') as c: + c.argument('source_resource', help="Resource ID of the source resource.") + c.argument('target_resource', help="Resource ID of the target resource.") + c.argument('always_clone', action='store_true', + help="If this argument is applied, " + "all monitor settings would be cloned instead of expanding its scope.") + c.argument('monitor_types', options_list=['--types', '-t'], arg_type=get_enum_type(['metricsAlert']), + nargs='+', help='List of types of monitor settings which would be cloned.', default=['metricsAlert']) + # endregion diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/__init__.py new file mode 100644 index 00000000000..5757aea3175 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# 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 +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/__init__.py new file mode 100644 index 00000000000..f6acc11aa4e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/__init__.py @@ -0,0 +1,10 @@ +# -------------------------------------------------------------------------------------------- +# 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 + diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__cmd_group.py new file mode 100644 index 00000000000..b7be6b843b5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__cmd_group.py @@ -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", +) +class __CMDGroup(AAZCommandGroup): + """Manage the Azure Monitor Service. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__init__.py new file mode 100644 index 00000000000..5a9d61963d6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/__init__.py @@ -0,0 +1,11 @@ +# -------------------------------------------------------------------------------------------- +# 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 * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__cmd_group.py new file mode 100644 index 00000000000..db873b78e4d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__cmd_group.py @@ -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 account", +) +class __CMDGroup(AAZCommandGroup): + """Manage monitor account + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__init__.py new file mode 100644 index 00000000000..db73033039b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_create.py new file mode 100644 index 00000000000..bca6134c3dd --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_create.py @@ -0,0 +1,375 @@ +# -------------------------------------------------------------------------------------------- +# 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 account create", +) +class Create(AAZCommand): + """Create a workspace + + :example: Create monitor account + az monitor account create -n account-name -g rg + """ + + _aaz_info = { + "version": "2023-04-03", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts/{}", "2023-04-03"], + ] + } + + 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.azure_monitor_workspace_name = AAZStrArg( + options=["-n", "--name", "--azure-monitor-workspace-name"], + help="The name of the Azure Monitor workspace. The name is case insensitive", + required=True, + fmt=AAZStrArgFormat( + pattern="^(?!-)[a-zA-Z0-9-]+[^-]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "AzureMonitorWorkspaceProperties" + + _args_schema = cls._args_schema + _args_schema.location = AAZResourceLocationArg( + arg_group="AzureMonitorWorkspaceProperties", + help="The geo-location where the resource lives", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="AzureMonitorWorkspaceProperties", + help="Resource tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AzureMonitorWorkspacesCreate(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 AzureMonitorWorkspacesCreate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.etag = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _CreateHelper._build_schema_system_data_read(_schema_on_200_201.system_data) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = cls._schema_on_200_201.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = cls._schema_on_200_201.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200_201.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _CreateHelper._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_delete.py new file mode 100644 index 00000000000..b015df0bec2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_delete.py @@ -0,0 +1,154 @@ +# -------------------------------------------------------------------------------------------- +# 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 account delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a workspace + + :example: Delete monitor account + az monitor account delete -n account-name -g rg + """ + + _aaz_info = { + "version": "2023-04-03", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts/{}", "2023-04-03"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.azure_monitor_workspace_name = AAZStrArg( + options=["-n", "--name", "--azure-monitor-workspace-name"], + help="The name of the Azure Monitor workspace. The name is case insensitive", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^(?!-)[a-zA-Z0-9-]+[^-]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.AzureMonitorWorkspacesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class AzureMonitorWorkspacesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + None, + self.on_error, + lro_options={"final-state-via": "location"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "location"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + required=True, + ), + } + return parameters + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_list.py new file mode 100644 index 00000000000..cbd304052e8 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_list.py @@ -0,0 +1,552 @@ +# -------------------------------------------------------------------------------------------- +# 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 account list", +) +class List(AAZCommand): + """List all workspaces in the specified subscription + + :example: List monitor account by resource group + az monitor account list -g rg + """ + + _aaz_info = { + "version": "2023-04-03", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.monitor/accounts", "2023-04-03"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts", "2023-04-03"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.AzureMonitorWorkspacesListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.AzureMonitorWorkspacesListBySubscription(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class AzureMonitorWorkspacesListByResourceGroup(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.Monitor/accounts", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2023-04-03", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.etag = AAZStrType( + flags={"read_only": True}, + ) + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ListHelper._build_schema_system_data_read(_element.system_data) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = cls._schema_on_200.value.Element.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = cls._schema_on_200.value.Element.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.value.Element.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ListHelper._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class AzureMonitorWorkspacesListBySubscription(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}/providers/Microsoft.Monitor/accounts", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2023-04-03", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.etag = AAZStrType( + flags={"read_only": True}, + ) + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ListHelper._build_schema_system_data_read(_element.system_data) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = cls._schema_on_200.value.Element.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = cls._schema_on_200.value.Element.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.value.Element.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ListHelper._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_show.py new file mode 100644 index 00000000000..9f7806f0e05 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_show.py @@ -0,0 +1,337 @@ +# -------------------------------------------------------------------------------------------- +# 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 account show", +) +class Show(AAZCommand): + """Show the specific azure monitor workspace + + :example: Show monitor account + az monitor account show -n account -g rg + """ + + _aaz_info = { + "version": "2023-04-03", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts/{}", "2023-04-03"], + ] + } + + 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.azure_monitor_workspace_name = AAZStrArg( + options=["-n", "--name", "--azure-monitor-workspace-name"], + help="The name of the Azure Monitor workspace. The name is case insensitive", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^(?!-)[a-zA-Z0-9-]+[^-]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AzureMonitorWorkspacesGet(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 AzureMonitorWorkspacesGet(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.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + 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.etag = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ShowHelper._build_schema_system_data_read(_schema_on_200.system_data) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = cls._schema_on_200.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = cls._schema_on_200.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ShowHelper._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_update.py new file mode 100644 index 00000000000..10f096226be --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_update.py @@ -0,0 +1,516 @@ +# -------------------------------------------------------------------------------------------- +# 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 account update", +) +class Update(AAZCommand): + """Update a workspace + + :example: Update monitor account tags + az monitor account update -n account-name -g rg --tags "{tag:test}" + """ + + _aaz_info = { + "version": "2023-04-03", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts/{}", "2023-04-03"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.azure_monitor_workspace_name = AAZStrArg( + options=["-n", "--name", "--azure-monitor-workspace-name"], + help="The name of the Azure Monitor workspace. The name is case insensitive", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^(?!-)[a-zA-Z0-9-]+[^-]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "AzureMonitorWorkspaceProperties" + + _args_schema = cls._args_schema + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="AzureMonitorWorkspaceProperties", + help="Resource tags.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AzureMonitorWorkspacesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.AzureMonitorWorkspacesCreate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class AzureMonitorWorkspacesGet(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.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + 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() + _UpdateHelper._build_schema_azure_monitor_workspace_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class AzureMonitorWorkspacesCreate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_azure_monitor_workspace_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_azure_monitor_workspace_resource_read = None + + @classmethod + def _build_schema_azure_monitor_workspace_resource_read(cls, _schema): + if cls._schema_azure_monitor_workspace_resource_read is not None: + _schema.etag = cls._schema_azure_monitor_workspace_resource_read.etag + _schema.id = cls._schema_azure_monitor_workspace_resource_read.id + _schema.location = cls._schema_azure_monitor_workspace_resource_read.location + _schema.name = cls._schema_azure_monitor_workspace_resource_read.name + _schema.properties = cls._schema_azure_monitor_workspace_resource_read.properties + _schema.system_data = cls._schema_azure_monitor_workspace_resource_read.system_data + _schema.tags = cls._schema_azure_monitor_workspace_resource_read.tags + _schema.type = cls._schema_azure_monitor_workspace_resource_read.type + return + + cls._schema_azure_monitor_workspace_resource_read = _schema_azure_monitor_workspace_resource_read = AAZObjectType() + + azure_monitor_workspace_resource_read = _schema_azure_monitor_workspace_resource_read + azure_monitor_workspace_resource_read.etag = AAZStrType( + flags={"read_only": True}, + ) + azure_monitor_workspace_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + azure_monitor_workspace_resource_read.location = AAZStrType( + flags={"required": True}, + ) + azure_monitor_workspace_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + azure_monitor_workspace_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + azure_monitor_workspace_resource_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + cls._build_schema_system_data_read(azure_monitor_workspace_resource_read.system_data) + azure_monitor_workspace_resource_read.tags = AAZDictType() + azure_monitor_workspace_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_azure_monitor_workspace_resource_read.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = _schema_azure_monitor_workspace_resource_read.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = _schema_azure_monitor_workspace_resource_read.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + cls._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = _schema_azure_monitor_workspace_resource_read.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = _schema_azure_monitor_workspace_resource_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_azure_monitor_workspace_resource_read.etag + _schema.id = cls._schema_azure_monitor_workspace_resource_read.id + _schema.location = cls._schema_azure_monitor_workspace_resource_read.location + _schema.name = cls._schema_azure_monitor_workspace_resource_read.name + _schema.properties = cls._schema_azure_monitor_workspace_resource_read.properties + _schema.system_data = cls._schema_azure_monitor_workspace_resource_read.system_data + _schema.tags = cls._schema_azure_monitor_workspace_resource_read.tags + _schema.type = cls._schema_azure_monitor_workspace_resource_read.type + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_wait.py new file mode 100644 index 00000000000..ef7447fcce0 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/account/_wait.py @@ -0,0 +1,333 @@ +# -------------------------------------------------------------------------------------------- +# 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 account wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.monitor/accounts/{}", "2023-04-03"], + ] + } + + 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.azure_monitor_workspace_name = AAZStrArg( + options=["-n", "--name", "--azure-monitor-workspace-name"], + help="The name of the Azure Monitor workspace. The name is case insensitive", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^(?!-)[a-zA-Z0-9-]+[^-]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AzureMonitorWorkspacesGet(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=False) + return result + + class AzureMonitorWorkspacesGet(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.Monitor/accounts/{azureMonitorWorkspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "azureMonitorWorkspaceName", self.ctx.args.azure_monitor_workspace_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( + "api-version", "2023-04-03", + 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.etag = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _WaitHelper._build_schema_system_data_read(_schema_on_200.system_data) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.account_id = AAZStrType( + serialized_name="accountId", + flags={"read_only": True}, + ) + properties.default_ingestion_settings = AAZObjectType( + serialized_name="defaultIngestionSettings", + flags={"read_only": True}, + ) + properties.metrics = AAZObjectType( + flags={"read_only": True}, + ) + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access = AAZStrType( + serialized_name="publicNetworkAccess", + flags={"read_only": True}, + ) + + default_ingestion_settings = cls._schema_on_200.properties.default_ingestion_settings + default_ingestion_settings.data_collection_endpoint_resource_id = AAZStrType( + serialized_name="dataCollectionEndpointResourceId", + flags={"read_only": True}, + ) + default_ingestion_settings.data_collection_rule_resource_id = AAZStrType( + serialized_name="dataCollectionRuleResourceId", + flags={"read_only": True}, + ) + + metrics = cls._schema_on_200.properties.metrics + metrics.internal_id = AAZStrType( + serialized_name="internalId", + flags={"read_only": True}, + ) + metrics.prometheus_query_endpoint = AAZStrType( + serialized_name="prometheusQueryEndpoint", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _WaitHelper._build_schema_system_data_read(_element.system_data) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties.private_endpoint_connections.Element.properties + properties.group_ids = AAZListType( + serialized_name="groupIds", + flags={"read_only": True}, + ) + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + flags={"required": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + group_ids = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.group_ids + group_ids.Element = AAZStrType() + + private_endpoint = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType( + flags={"read_only": True}, + ) + + private_link_service_connection_state = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + ) + private_link_service_connection_state.description = AAZStrType() + private_link_service_connection_state.status = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__cmd_group.py new file mode 100644 index 00000000000..4088c72ec1f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__cmd_group.py @@ -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 action-group", +) +class __CMDGroup(AAZCommandGroup): + """Manage action groups. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__init__.py new file mode 100644 index 00000000000..38254460a56 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._enable_receiver import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_create.py new file mode 100644 index 00000000000..bb8ac233320 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_create.py @@ -0,0 +1,1187 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group create", +) +class Create(AAZCommand): + """Create a new action group. + + :example: Create a new action group + az monitor action-group create --action webhook MyActionName https://alerts.contoso.com apiKey={APIKey} type=HighCPU --name MyActionGroup --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview"], + ] + } + + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.location = AAZResourceLocationArg( + help="Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=`.", + required=True, + default="Global", + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.group_short_name = AAZStrArg( + options=["--short-name", "--group-short-name"], + help="The short name of the action group. This will be used in SMS messages.", + fmt=AAZStrArgFormat( + max_length=12, + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="Identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="Identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.arm_role_receivers = AAZListArg( + options=["--arm-role-receivers"], + arg_group="Properties", + help="The list of ARM role receivers that are part of this action group. Roles are Azure RBAC roles and only built-in roles are supported.", + ) + _args_schema.automation_runbook_receivers = AAZListArg( + options=["--automation-runbook-receivers"], + arg_group="Properties", + help="The list of AutomationRunbook receivers that are part of this action group.", + ) + _args_schema.azure_app_push_receivers = AAZListArg( + options=["--azure-app-push-receivers"], + arg_group="Properties", + help="The list of AzureAppPush receivers that are part of this action group.", + ) + _args_schema.azure_function_receivers = AAZListArg( + options=["--azure-function-receivers"], + arg_group="Properties", + help="The list of azure function receivers that are part of this action group.", + ) + _args_schema.email_receivers = AAZListArg( + options=["--email-receivers"], + arg_group="Properties", + help="The list of email receivers that are part of this action group.", + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + arg_group="Properties", + help="Indicates whether this action group is enabled. If an action group is not enabled, then none of its receivers will receive communications.", + default=True, + ) + _args_schema.event_hub_receivers = AAZListArg( + options=["--event-hub-receivers"], + arg_group="Properties", + help="The list of event hub receivers that are part of this action group.", + ) + _args_schema.incident_receivers = AAZListArg( + options=["--incident-receivers"], + arg_group="Properties", + help="The list of incident receivers that are part of this action group.", + ) + _args_schema.itsm_receivers = AAZListArg( + options=["--itsm-receivers"], + arg_group="Properties", + help="The list of ITSM receivers that are part of this action group.", + ) + _args_schema.logic_app_receivers = AAZListArg( + options=["--logic-app-receivers"], + arg_group="Properties", + help="The list of logic app receivers that are part of this action group.", + ) + _args_schema.sms_receivers = AAZListArg( + options=["--sms-receivers"], + arg_group="Properties", + help="The list of SMS receivers that are part of this action group.", + ) + _args_schema.voice_receivers = AAZListArg( + options=["--voice-receivers"], + arg_group="Properties", + help="The list of voice receivers that are part of this action group.", + ) + _args_schema.webhook_receivers = AAZListArg( + options=["--webhook-receivers"], + arg_group="Properties", + help="The list of webhook receivers that are part of this action group.", + ) + + arm_role_receivers = cls._args_schema.arm_role_receivers + arm_role_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.arm_role_receivers.Element + _element.name = AAZStrArg( + options=["name"], + help="The name of the arm role receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.role_id = AAZStrArg( + options=["role-id"], + help="The arm role id.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + automation_runbook_receivers = cls._args_schema.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrArg( + options=["automation-account-id"], + help="The Azure automation account Id which holds this runbook and authenticate to Azure resource.", + required=True, + ) + _element.is_global_runbook = AAZBoolArg( + options=["is-global-runbook"], + help="Indicates whether this instance is global runbook.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="Indicates name of the webhook.", + ) + _element.runbook_name = AAZStrArg( + options=["runbook-name"], + help="The name for this runbook.", + required=True, + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + _element.webhook_resource_id = AAZStrArg( + options=["webhook-resource-id"], + help="The resource id for webhook linked to this runbook.", + required=True, + ) + + azure_app_push_receivers = cls._args_schema.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.azure_app_push_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address registered for the Azure mobile app.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + + azure_function_receivers = cls._args_schema.azure_function_receivers + azure_function_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrArg( + options=["function-app-resource-id"], + help="The azure resource id of the function app.", + required=True, + ) + _element.function_name = AAZStrArg( + options=["function-name"], + help="The function name in the function app.", + required=True, + ) + _element.http_trigger_url = AAZStrArg( + options=["http-trigger-url"], + help="The http trigger url where http request sent to.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the azure function receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + email_receivers = cls._args_schema.email_receivers + email_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.email_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address of this receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the email receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + event_hub_receivers = cls._args_schema.event_hub_receivers + event_hub_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.event_hub_receivers.Element + _element.event_hub_name = AAZStrArg( + options=["event-hub-name"], + help="The name of the specific Event Hub queue", + required=True, + ) + _element.event_hub_name_space = AAZStrArg( + options=["event-hub-name-space"], + help="The Event Hub namespace", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Event hub receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.subscription_id = AAZStrArg( + options=["subscription-id"], + help="The Id for the subscription containing this event hub", + required=True, + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="The tenant Id for the subscription containing this event hub", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + incident_receivers = cls._args_schema.incident_receivers + incident_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.incident_receivers.Element + _element.connection = AAZObjectArg( + options=["connection"], + help="The incident service connection", + required=True, + ) + _element.incident_management_service = AAZStrArg( + options=["incident-management-service"], + help="The incident management service type", + required=True, + enum={"Icm": "Icm"}, + ) + _element.mappings = AAZDictArg( + options=["mappings"], + help="Field mappings for the incident service", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Incident receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + + connection = cls._args_schema.incident_receivers.Element.connection + connection.id = AAZStrArg( + options=["id"], + help="GUID value representing the connection ID for the incident management service.", + required=True, + ) + connection.name = AAZStrArg( + options=["name"], + help="The name of the connection.", + required=True, + ) + + mappings = cls._args_schema.incident_receivers.Element.mappings + mappings.Element = AAZStrArg() + + itsm_receivers = cls._args_schema.itsm_receivers + itsm_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.itsm_receivers.Element + _element.connection_id = AAZStrArg( + options=["connection-id"], + help="Unique identification of ITSM connection among multiple defined in above workspace.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Itsm receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.region = AAZStrArg( + options=["region"], + help="Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'", + required=True, + ) + _element.ticket_configuration = AAZStrArg( + options=["ticket-configuration"], + help="JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well.", + required=True, + ) + _element.workspace_id = AAZStrArg( + options=["workspace-id"], + help="OMS LA instance identifier.", + required=True, + ) + + logic_app_receivers = cls._args_schema.logic_app_receivers + logic_app_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.logic_app_receivers.Element + _element.callback_url = AAZStrArg( + options=["callback-url"], + help="The callback url where http request sent to.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the logic app receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.resource_id = AAZStrArg( + options=["resource-id"], + help="The azure resource id of the logic app receiver.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + sms_receivers = cls._args_schema.sms_receivers + sms_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.sms_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the SMS receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the SMS receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the SMS receiver.", + required=True, + ) + + voice_receivers = cls._args_schema.voice_receivers + voice_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.voice_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the voice receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the voice receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the voice receiver.", + required=True, + ) + + webhook_receivers = cls._args_schema.webhook_receivers + webhook_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.webhook_receivers.Element + _element.identifier_uri = AAZStrArg( + options=["identifier-uri"], + help="Indicates the identifier uri for aad auth.", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the webhook receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.object_id = AAZStrArg( + options=["object-id"], + help="Indicates the webhook app object Id for aad auth.", + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + required=True, + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="Indicates the tenant id for aad auth.", + ) + _element.use_aad_auth = AAZBoolArg( + options=["use-aad-auth"], + help="Indicates whether or not use AAD authentication.", + default=False, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsCreateOrUpdate(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 ActionGroupsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + identity = _builder.get(".identity") + if identity is not None: + identity.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "create"}}) + identity.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "create"}}) + + user_assigned = _builder.get(".identity.userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("armRoleReceivers", AAZListType, ".arm_role_receivers") + properties.set_prop("automationRunbookReceivers", AAZListType, ".automation_runbook_receivers") + properties.set_prop("azureAppPushReceivers", AAZListType, ".azure_app_push_receivers") + properties.set_prop("azureFunctionReceivers", AAZListType, ".azure_function_receivers") + properties.set_prop("emailReceivers", AAZListType, ".email_receivers") + properties.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("eventHubReceivers", AAZListType, ".event_hub_receivers") + properties.set_prop("groupShortName", AAZStrType, ".group_short_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("incidentReceivers", AAZListType, ".incident_receivers") + properties.set_prop("itsmReceivers", AAZListType, ".itsm_receivers") + properties.set_prop("logicAppReceivers", AAZListType, ".logic_app_receivers") + properties.set_prop("smsReceivers", AAZListType, ".sms_receivers") + properties.set_prop("voiceReceivers", AAZListType, ".voice_receivers") + properties.set_prop("webhookReceivers", AAZListType, ".webhook_receivers") + + arm_role_receivers = _builder.get(".properties.armRoleReceivers") + if arm_role_receivers is not None: + arm_role_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.armRoleReceivers[]") + if _elements is not None: + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("roleId", AAZStrType, ".role_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + automation_runbook_receivers = _builder.get(".properties.automationRunbookReceivers") + if automation_runbook_receivers is not None: + automation_runbook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.automationRunbookReceivers[]") + if _elements is not None: + _elements.set_prop("automationAccountId", AAZStrType, ".automation_account_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("isGlobalRunbook", AAZBoolType, ".is_global_runbook", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name") + _elements.set_prop("runbookName", AAZStrType, ".runbook_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("serviceUri", AAZStrType, ".service_uri") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + _elements.set_prop("webhookResourceId", AAZStrType, ".webhook_resource_id", typ_kwargs={"flags": {"required": True}}) + + azure_app_push_receivers = _builder.get(".properties.azureAppPushReceivers") + if azure_app_push_receivers is not None: + azure_app_push_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.azureAppPushReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + azure_function_receivers = _builder.get(".properties.azureFunctionReceivers") + if azure_function_receivers is not None: + azure_function_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.azureFunctionReceivers[]") + if _elements is not None: + _elements.set_prop("functionAppResourceId", AAZStrType, ".function_app_resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("functionName", AAZStrType, ".function_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("httpTriggerUrl", AAZStrType, ".http_trigger_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + email_receivers = _builder.get(".properties.emailReceivers") + if email_receivers is not None: + email_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.emailReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + event_hub_receivers = _builder.get(".properties.eventHubReceivers") + if event_hub_receivers is not None: + event_hub_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.eventHubReceivers[]") + if _elements is not None: + _elements.set_prop("eventHubName", AAZStrType, ".event_hub_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("eventHubNameSpace", AAZStrType, ".event_hub_name_space", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("subscriptionId", AAZStrType, ".subscription_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + incident_receivers = _builder.get(".properties.incidentReceivers") + if incident_receivers is not None: + incident_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.incidentReceivers[]") + if _elements is not None: + _elements.set_prop("connection", AAZObjectType, ".connection", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("incidentManagementService", AAZStrType, ".incident_management_service", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("mappings", AAZDictType, ".mappings", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + connection = _builder.get(".properties.incidentReceivers[].connection") + if connection is not None: + connection.set_prop("id", AAZStrType, ".id", typ_kwargs={"flags": {"required": True}}) + connection.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + mappings = _builder.get(".properties.incidentReceivers[].mappings") + if mappings is not None: + mappings.set_elements(AAZStrType, ".") + + itsm_receivers = _builder.get(".properties.itsmReceivers") + if itsm_receivers is not None: + itsm_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.itsmReceivers[]") + if _elements is not None: + _elements.set_prop("connectionId", AAZStrType, ".connection_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("region", AAZStrType, ".region", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("ticketConfiguration", AAZStrType, ".ticket_configuration", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("workspaceId", AAZStrType, ".workspace_id", typ_kwargs={"flags": {"required": True}}) + + logic_app_receivers = _builder.get(".properties.logicAppReceivers") + if logic_app_receivers is not None: + logic_app_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logicAppReceivers[]") + if _elements is not None: + _elements.set_prop("callbackUrl", AAZStrType, ".callback_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("resourceId", AAZStrType, ".resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + sms_receivers = _builder.get(".properties.smsReceivers") + if sms_receivers is not None: + sms_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.smsReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + voice_receivers = _builder.get(".properties.voiceReceivers") + if voice_receivers is not None: + voice_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.voiceReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + webhook_receivers = _builder.get(".properties.webhookReceivers") + if webhook_receivers is not None: + webhook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.webhookReceivers[]") + if _elements is not None: + _elements.set_prop("identifierUri", AAZStrType, ".identifier_uri") + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("objectId", AAZStrType, ".object_id") + _elements.set_prop("serviceUri", AAZStrType, ".service_uri", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useAadAuth", AAZBoolType, ".use_aad_auth") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.identity = AAZIdentityObjectType() + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200_201.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200_201.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200_201.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = cls._schema_on_200_201.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = cls._schema_on_200_201.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = cls._schema_on_200_201.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = cls._schema_on_200_201.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = cls._schema_on_200_201.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = cls._schema_on_200_201.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = cls._schema_on_200_201.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = cls._schema_on_200_201.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = cls._schema_on_200_201.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = cls._schema_on_200_201.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = cls._schema_on_200_201.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = cls._schema_on_200_201.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = cls._schema_on_200_201.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = cls._schema_on_200_201.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_delete.py new file mode 100644 index 00000000000..b4560cc0949 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_delete.py @@ -0,0 +1,135 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group delete", +) +class Delete(AAZCommand): + """Delete an action group. + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class ActionGroupsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_enable_receiver.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_enable_receiver.py new file mode 100644 index 00000000000..01e59dea677 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_enable_receiver.py @@ -0,0 +1,157 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group enable-receiver", +) +class EnableReceiver(AAZCommand): + """Enable a receiver in an action group. + + This changes the receiver's status from Disabled to Enabled. This operation is only supported for Email or SMS receivers. + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}/subscribe", "2024-10-01-preview"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.action_group_name = AAZStrArg( + options=["--action-group", "--action-group-name"], + help="The name of the action group.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.receiver_name = AAZStrArg( + options=["-n", "--name", "--receiver-name"], + help="The name of the receiver to resubscribe.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsEnableReceiver(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class ActionGroupsEnableReceiver(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/actionGroups/{actionGroupName}/subscribe", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("receiverName", AAZStrType, ".receiver_name", typ_kwargs={"flags": {"required": True}}) + + return self.serialize_content(_content_value) + + def on_200(self, session): + pass + + +class _EnableReceiverHelper: + """Helper class for EnableReceiver""" + + +__all__ = ["EnableReceiver"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_list.py new file mode 100644 index 00000000000..9f0a3ccfcc9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_list.py @@ -0,0 +1,981 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group list", +) +class List(AAZCommand): + """List action groups under a resource group or the current subscription. + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/actiongroups", "2024-10-01-preview"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups", "2024-10-01-preview"], + ] + } + + 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + condition_1 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + if condition_0: + self.ActionGroupsListBySubscriptionId(ctx=self.ctx)() + if condition_1: + self.ActionGroupsListByResourceGroup(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.value, client_flatten=True) + return result + + class ActionGroupsListBySubscriptionId(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}/providers/Microsoft.Insights/actionGroups", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2024-10-01-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = cls._schema_on_200.value.Element.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = cls._schema_on_200.value.Element.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = cls._schema_on_200.value.Element.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = cls._schema_on_200.value.Element.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = cls._schema_on_200.value.Element.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = cls._schema_on_200.value.Element.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = cls._schema_on_200.value.Element.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = cls._schema_on_200.value.Element.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = cls._schema_on_200.value.Element.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = cls._schema_on_200.value.Element.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = cls._schema_on_200.value.Element.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = cls._schema_on_200.value.Element.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = cls._schema_on_200.value.Element.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = cls._schema_on_200.value.Element.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class ActionGroupsListByResourceGroup(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/actionGroups", + **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( + "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( + "api-version", "2024-10-01-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = cls._schema_on_200.value.Element.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = cls._schema_on_200.value.Element.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = cls._schema_on_200.value.Element.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = cls._schema_on_200.value.Element.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = cls._schema_on_200.value.Element.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = cls._schema_on_200.value.Element.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = cls._schema_on_200.value.Element.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = cls._schema_on_200.value.Element.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = cls._schema_on_200.value.Element.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = cls._schema_on_200.value.Element.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = cls._schema_on_200.value.Element.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = cls._schema_on_200.value.Element.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = cls._schema_on_200.value.Element.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = cls._schema_on_200.value.Element.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_show.py new file mode 100644 index 00000000000..759e492f291 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_show.py @@ -0,0 +1,530 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group show", +) +class Show(AAZCommand): + """Show the details of an action group. + + :example: Show the details of an action group (commonly used with --output and --query). + az monitor action-group show --name MyActionGroup --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview"], + ] + } + + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(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 ActionGroupsGet(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/actionGroups/{actionGroupName}", + **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( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = cls._schema_on_200.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = cls._schema_on_200.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = cls._schema_on_200.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = cls._schema_on_200.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = cls._schema_on_200.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = cls._schema_on_200.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = cls._schema_on_200.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = cls._schema_on_200.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = cls._schema_on_200.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = cls._schema_on_200.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = cls._schema_on_200.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = cls._schema_on_200.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = cls._schema_on_200.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = cls._schema_on_200.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_update.py new file mode 100644 index 00000000000..2569dad55a2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/_update.py @@ -0,0 +1,1308 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group update", +) +class Update(AAZCommand): + """Update an action group. + + :example: Update an action group + az monitor action-group update --name MyActionGroup --resource-group MyResourceGroup --set retentionPolicy.days=365 --subscription MySubscription + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.group_short_name = AAZStrArg( + options=["--short-name", "--group-short-name"], + help="The short name of the action group. This will be used in SMS messages.", + fmt=AAZStrArgFormat( + max_length=12, + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Identity" + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.arm_role_receivers = AAZListArg( + options=["--arm-role-receivers"], + arg_group="Properties", + help="The list of ARM role receivers that are part of this action group. Roles are Azure RBAC roles and only built-in roles are supported.", + nullable=True, + ) + _args_schema.automation_runbook_receivers = AAZListArg( + options=["--automation-runbook-receivers"], + arg_group="Properties", + help="The list of AutomationRunbook receivers that are part of this action group.", + nullable=True, + ) + _args_schema.azure_app_push_receivers = AAZListArg( + options=["--azure-app-push-receivers"], + arg_group="Properties", + help="The list of AzureAppPush receivers that are part of this action group.", + nullable=True, + ) + _args_schema.azure_function_receivers = AAZListArg( + options=["--azure-function-receivers"], + arg_group="Properties", + help="The list of azure function receivers that are part of this action group.", + nullable=True, + ) + _args_schema.email_receivers = AAZListArg( + options=["--email-receivers"], + arg_group="Properties", + help="The list of email receivers that are part of this action group.", + nullable=True, + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + arg_group="Properties", + help="Indicates whether this action group is enabled. If an action group is not enabled, then none of its receivers will receive communications.", + ) + _args_schema.event_hub_receivers = AAZListArg( + options=["--event-hub-receivers"], + arg_group="Properties", + help="The list of event hub receivers that are part of this action group.", + nullable=True, + ) + _args_schema.incident_receivers = AAZListArg( + options=["--incident-receivers"], + arg_group="Properties", + help="The list of incident receivers that are part of this action group.", + nullable=True, + ) + _args_schema.itsm_receivers = AAZListArg( + options=["--itsm-receivers"], + arg_group="Properties", + help="The list of ITSM receivers that are part of this action group.", + nullable=True, + ) + _args_schema.logic_app_receivers = AAZListArg( + options=["--logic-app-receivers"], + arg_group="Properties", + help="The list of logic app receivers that are part of this action group.", + nullable=True, + ) + _args_schema.sms_receivers = AAZListArg( + options=["--sms-receivers"], + arg_group="Properties", + help="The list of SMS receivers that are part of this action group.", + nullable=True, + ) + _args_schema.voice_receivers = AAZListArg( + options=["--voice-receivers"], + arg_group="Properties", + help="The list of voice receivers that are part of this action group.", + nullable=True, + ) + _args_schema.webhook_receivers = AAZListArg( + options=["--webhook-receivers"], + arg_group="Properties", + help="The list of webhook receivers that are part of this action group.", + nullable=True, + ) + + arm_role_receivers = cls._args_schema.arm_role_receivers + arm_role_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.arm_role_receivers.Element + _element.name = AAZStrArg( + options=["name"], + help="The name of the arm role receiver. Names must be unique across all receivers within an action group.", + ) + _element.role_id = AAZStrArg( + options=["role-id"], + help="The arm role id.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + + automation_runbook_receivers = cls._args_schema.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrArg( + options=["automation-account-id"], + help="The Azure automation account Id which holds this runbook and authenticate to Azure resource.", + ) + _element.is_global_runbook = AAZBoolArg( + options=["is-global-runbook"], + help="Indicates whether this instance is global runbook.", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="Indicates name of the webhook.", + nullable=True, + ) + _element.runbook_name = AAZStrArg( + options=["runbook-name"], + help="The name for this runbook.", + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + nullable=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + _element.webhook_resource_id = AAZStrArg( + options=["webhook-resource-id"], + help="The resource id for webhook linked to this runbook.", + ) + + azure_app_push_receivers = cls._args_schema.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.azure_app_push_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address registered for the Azure mobile app.", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group.", + ) + + azure_function_receivers = cls._args_schema.azure_function_receivers + azure_function_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrArg( + options=["function-app-resource-id"], + help="The azure resource id of the function app.", + ) + _element.function_name = AAZStrArg( + options=["function-name"], + help="The function name in the function app.", + ) + _element.http_trigger_url = AAZStrArg( + options=["http-trigger-url"], + help="The http trigger url where http request sent to.", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the azure function receiver. Names must be unique across all receivers within an action group.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + + email_receivers = cls._args_schema.email_receivers + email_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.email_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address of this receiver.", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the email receiver. Names must be unique across all receivers within an action group.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + + event_hub_receivers = cls._args_schema.event_hub_receivers + event_hub_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.event_hub_receivers.Element + _element.event_hub_name = AAZStrArg( + options=["event-hub-name"], + help="The name of the specific Event Hub queue", + ) + _element.event_hub_name_space = AAZStrArg( + options=["event-hub-name-space"], + help="The Event Hub namespace", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Event hub receiver. Names must be unique across all receivers within an action group.", + ) + _element.subscription_id = AAZStrArg( + options=["subscription-id"], + help="The Id for the subscription containing this event hub", + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="The tenant Id for the subscription containing this event hub", + nullable=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + + incident_receivers = cls._args_schema.incident_receivers + incident_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.incident_receivers.Element + _element.connection = AAZObjectArg( + options=["connection"], + help="The incident service connection", + ) + _element.incident_management_service = AAZStrArg( + options=["incident-management-service"], + help="The incident management service type", + enum={"Icm": "Icm"}, + ) + _element.mappings = AAZDictArg( + options=["mappings"], + help="Field mappings for the incident service", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Incident receiver. Names must be unique across all receivers within an action group.", + ) + + connection = cls._args_schema.incident_receivers.Element.connection + connection.id = AAZStrArg( + options=["id"], + help="GUID value representing the connection ID for the incident management service.", + ) + connection.name = AAZStrArg( + options=["name"], + help="The name of the connection.", + ) + + mappings = cls._args_schema.incident_receivers.Element.mappings + mappings.Element = AAZStrArg( + nullable=True, + ) + + itsm_receivers = cls._args_schema.itsm_receivers + itsm_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.itsm_receivers.Element + _element.connection_id = AAZStrArg( + options=["connection-id"], + help="Unique identification of ITSM connection among multiple defined in above workspace.", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Itsm receiver. Names must be unique across all receivers within an action group.", + ) + _element.region = AAZStrArg( + options=["region"], + help="Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'", + ) + _element.ticket_configuration = AAZStrArg( + options=["ticket-configuration"], + help="JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well.", + ) + _element.workspace_id = AAZStrArg( + options=["workspace-id"], + help="OMS LA instance identifier.", + ) + + logic_app_receivers = cls._args_schema.logic_app_receivers + logic_app_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.logic_app_receivers.Element + _element.callback_url = AAZStrArg( + options=["callback-url"], + help="The callback url where http request sent to.", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the logic app receiver. Names must be unique across all receivers within an action group.", + ) + _element.resource_id = AAZStrArg( + options=["resource-id"], + help="The azure resource id of the logic app receiver.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + + sms_receivers = cls._args_schema.sms_receivers + sms_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.sms_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the SMS receiver.", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the SMS receiver. Names must be unique across all receivers within an action group.", + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the SMS receiver.", + ) + + voice_receivers = cls._args_schema.voice_receivers + voice_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.voice_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the voice receiver.", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the voice receiver. Names must be unique across all receivers within an action group.", + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the voice receiver.", + ) + + webhook_receivers = cls._args_schema.webhook_receivers + webhook_receivers.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.webhook_receivers.Element + _element.identifier_uri = AAZStrArg( + options=["identifier-uri"], + help="Indicates the identifier uri for aad auth.", + nullable=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the webhook receiver. Names must be unique across all receivers within an action group.", + ) + _element.object_id = AAZStrArg( + options=["object-id"], + help="Indicates the webhook app object Id for aad auth.", + nullable=True, + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="Indicates the tenant id for aad auth.", + nullable=True, + ) + _element.use_aad_auth = AAZBoolArg( + options=["use-aad-auth"], + help="Indicates whether or not use AAD authentication.", + nullable=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.ActionGroupsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class ActionGroupsGet(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/actionGroups/{actionGroupName}", + **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( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + 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() + _UpdateHelper._build_schema_action_group_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ActionGroupsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_action_group_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("armRoleReceivers", AAZListType, ".arm_role_receivers") + properties.set_prop("automationRunbookReceivers", AAZListType, ".automation_runbook_receivers") + properties.set_prop("azureAppPushReceivers", AAZListType, ".azure_app_push_receivers") + properties.set_prop("azureFunctionReceivers", AAZListType, ".azure_function_receivers") + properties.set_prop("emailReceivers", AAZListType, ".email_receivers") + properties.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("eventHubReceivers", AAZListType, ".event_hub_receivers") + properties.set_prop("groupShortName", AAZStrType, ".group_short_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("incidentReceivers", AAZListType, ".incident_receivers") + properties.set_prop("itsmReceivers", AAZListType, ".itsm_receivers") + properties.set_prop("logicAppReceivers", AAZListType, ".logic_app_receivers") + properties.set_prop("smsReceivers", AAZListType, ".sms_receivers") + properties.set_prop("voiceReceivers", AAZListType, ".voice_receivers") + properties.set_prop("webhookReceivers", AAZListType, ".webhook_receivers") + + arm_role_receivers = _builder.get(".properties.armRoleReceivers") + if arm_role_receivers is not None: + arm_role_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.armRoleReceivers[]") + if _elements is not None: + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("roleId", AAZStrType, ".role_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + automation_runbook_receivers = _builder.get(".properties.automationRunbookReceivers") + if automation_runbook_receivers is not None: + automation_runbook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.automationRunbookReceivers[]") + if _elements is not None: + _elements.set_prop("automationAccountId", AAZStrType, ".automation_account_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("isGlobalRunbook", AAZBoolType, ".is_global_runbook", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name") + _elements.set_prop("runbookName", AAZStrType, ".runbook_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("serviceUri", AAZStrType, ".service_uri") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + _elements.set_prop("webhookResourceId", AAZStrType, ".webhook_resource_id", typ_kwargs={"flags": {"required": True}}) + + azure_app_push_receivers = _builder.get(".properties.azureAppPushReceivers") + if azure_app_push_receivers is not None: + azure_app_push_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.azureAppPushReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + azure_function_receivers = _builder.get(".properties.azureFunctionReceivers") + if azure_function_receivers is not None: + azure_function_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.azureFunctionReceivers[]") + if _elements is not None: + _elements.set_prop("functionAppResourceId", AAZStrType, ".function_app_resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("functionName", AAZStrType, ".function_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("httpTriggerUrl", AAZStrType, ".http_trigger_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + email_receivers = _builder.get(".properties.emailReceivers") + if email_receivers is not None: + email_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.emailReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + event_hub_receivers = _builder.get(".properties.eventHubReceivers") + if event_hub_receivers is not None: + event_hub_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.eventHubReceivers[]") + if _elements is not None: + _elements.set_prop("eventHubName", AAZStrType, ".event_hub_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("eventHubNameSpace", AAZStrType, ".event_hub_name_space", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("subscriptionId", AAZStrType, ".subscription_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + incident_receivers = _builder.get(".properties.incidentReceivers") + if incident_receivers is not None: + incident_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.incidentReceivers[]") + if _elements is not None: + _elements.set_prop("connection", AAZObjectType, ".connection", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("incidentManagementService", AAZStrType, ".incident_management_service", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("mappings", AAZDictType, ".mappings", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + connection = _builder.get(".properties.incidentReceivers[].connection") + if connection is not None: + connection.set_prop("id", AAZStrType, ".id", typ_kwargs={"flags": {"required": True}}) + connection.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + mappings = _builder.get(".properties.incidentReceivers[].mappings") + if mappings is not None: + mappings.set_elements(AAZStrType, ".") + + itsm_receivers = _builder.get(".properties.itsmReceivers") + if itsm_receivers is not None: + itsm_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.itsmReceivers[]") + if _elements is not None: + _elements.set_prop("connectionId", AAZStrType, ".connection_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("region", AAZStrType, ".region", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("ticketConfiguration", AAZStrType, ".ticket_configuration", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("workspaceId", AAZStrType, ".workspace_id", typ_kwargs={"flags": {"required": True}}) + + logic_app_receivers = _builder.get(".properties.logicAppReceivers") + if logic_app_receivers is not None: + logic_app_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logicAppReceivers[]") + if _elements is not None: + _elements.set_prop("callbackUrl", AAZStrType, ".callback_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("resourceId", AAZStrType, ".resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + sms_receivers = _builder.get(".properties.smsReceivers") + if sms_receivers is not None: + sms_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.smsReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + voice_receivers = _builder.get(".properties.voiceReceivers") + if voice_receivers is not None: + voice_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.voiceReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + webhook_receivers = _builder.get(".properties.webhookReceivers") + if webhook_receivers is not None: + webhook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.webhookReceivers[]") + if _elements is not None: + _elements.set_prop("identifierUri", AAZStrType, ".identifier_uri") + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("objectId", AAZStrType, ".object_id") + _elements.set_prop("serviceUri", AAZStrType, ".service_uri", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useAadAuth", AAZBoolType, ".use_aad_auth") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_action_group_resource_read = None + + @classmethod + def _build_schema_action_group_resource_read(cls, _schema): + if cls._schema_action_group_resource_read is not None: + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + return + + cls._schema_action_group_resource_read = _schema_action_group_resource_read = AAZObjectType() + + action_group_resource_read = _schema_action_group_resource_read + action_group_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.identity = AAZIdentityObjectType() + action_group_resource_read.location = AAZStrType( + flags={"required": True}, + ) + action_group_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + action_group_resource_read.tags = AAZDictType() + action_group_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_action_group_resource_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_action_group_resource_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_action_group_resource_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_action_group_resource_read.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = _schema_action_group_resource_read.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = _schema_action_group_resource_read.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = _schema_action_group_resource_read.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = _schema_action_group_resource_read.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = _schema_action_group_resource_read.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = _schema_action_group_resource_read.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = _schema_action_group_resource_read.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = _schema_action_group_resource_read.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = _schema_action_group_resource_read.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = _schema_action_group_resource_read.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = _schema_action_group_resource_read.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = _schema_action_group_resource_read.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = _schema_action_group_resource_read.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = _schema_action_group_resource_read.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = _schema_action_group_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__cmd_group.py new file mode 100644 index 00000000000..6d0f6b9d2ca --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__cmd_group.py @@ -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 action-group identity", +) +class __CMDGroup(AAZCommandGroup): + """Manage identities of the action-group. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__init__.py new file mode 100644 index 00000000000..6e361c3c498 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/__init__.py @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._assign import * +from ._remove import * +from ._show import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_assign.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_assign.py new file mode 100644 index 00000000000..5457f7361d9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_assign.py @@ -0,0 +1,718 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group identity assign", +) +class Assign(AAZCommand): + """Assign the user or system managed identities. + + :example: Add a system assigned managed identity to an existing action group. + az monitor action-group identity assign --name ag --resource-group rg --system-assigned + + :example: Add a user assigned managed identity to an existing action group. + az monitor action-group identity assign --name ag --resource-group rg --user-assigned MyAssignedId + + :example: Add system assigned identity and a user assigned managed identity to an existing action group. + az monitor action-group identity assign --name ag --resource-group rg --system-assigned --user-assigned MyAssignedId + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview", "identity"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "ActionGroup.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="ActionGroup.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="ActionGroup.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.required()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.required()) + self.ActionGroupsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.required(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ActionGroupsGet(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/actionGroups/{actionGroupName}", + **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( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + 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() + _AssignHelper._build_schema_action_group_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ActionGroupsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _AssignHelper._build_schema_action_group_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.required()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "assign"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "assign"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _AssignHelper: + """Helper class for Assign""" + + _schema_action_group_resource_read = None + + @classmethod + def _build_schema_action_group_resource_read(cls, _schema): + if cls._schema_action_group_resource_read is not None: + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + return + + cls._schema_action_group_resource_read = _schema_action_group_resource_read = AAZObjectType() + + action_group_resource_read = _schema_action_group_resource_read + action_group_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.identity = AAZIdentityObjectType() + action_group_resource_read.location = AAZStrType( + flags={"required": True}, + ) + action_group_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + action_group_resource_read.tags = AAZDictType() + action_group_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_action_group_resource_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_action_group_resource_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_action_group_resource_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_action_group_resource_read.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = _schema_action_group_resource_read.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = _schema_action_group_resource_read.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = _schema_action_group_resource_read.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = _schema_action_group_resource_read.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = _schema_action_group_resource_read.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = _schema_action_group_resource_read.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = _schema_action_group_resource_read.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = _schema_action_group_resource_read.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = _schema_action_group_resource_read.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = _schema_action_group_resource_read.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = _schema_action_group_resource_read.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = _schema_action_group_resource_read.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = _schema_action_group_resource_read.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = _schema_action_group_resource_read.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = _schema_action_group_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + + +__all__ = ["Assign"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_remove.py new file mode 100644 index 00000000000..30456e529b9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_remove.py @@ -0,0 +1,719 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group identity remove", + confirmation="Are you sure you want to perform this operation?", +) +class Remove(AAZCommand): + """Remove the user or system managed identities. + + :example: Remove a system assigned managed identity from an existing action group. + az monitor action-group identity remove --name ag --resource-group rg --system-assigned + + :example: Remove a user assigned managed identity from an existing action group. + az monitor action-group identity remove --name ag --resource-group rg --user-assigned MyAssignedId + + :example: Remove all user assigned managed identities from an existing action group. + az monitor action-group identity remove --name ag --resource-group rg --user-assigned + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview", "identity"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "ActionGroup.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="ActionGroup.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="ActionGroup.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.required()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.required()) + self.ActionGroupsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.required(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ActionGroupsGet(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/actionGroups/{actionGroupName}", + **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( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + 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() + _RemoveHelper._build_schema_action_group_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ActionGroupsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _RemoveHelper._build_schema_action_group_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.required()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "remove"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "remove"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _RemoveHelper: + """Helper class for Remove""" + + _schema_action_group_resource_read = None + + @classmethod + def _build_schema_action_group_resource_read(cls, _schema): + if cls._schema_action_group_resource_read is not None: + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + return + + cls._schema_action_group_resource_read = _schema_action_group_resource_read = AAZObjectType() + + action_group_resource_read = _schema_action_group_resource_read + action_group_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.identity = AAZIdentityObjectType() + action_group_resource_read.location = AAZStrType( + flags={"required": True}, + ) + action_group_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + action_group_resource_read.tags = AAZDictType() + action_group_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_action_group_resource_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_action_group_resource_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_action_group_resource_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_action_group_resource_read.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = _schema_action_group_resource_read.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = _schema_action_group_resource_read.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = _schema_action_group_resource_read.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = _schema_action_group_resource_read.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = _schema_action_group_resource_read.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = _schema_action_group_resource_read.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = _schema_action_group_resource_read.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = _schema_action_group_resource_read.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = _schema_action_group_resource_read.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = _schema_action_group_resource_read.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = _schema_action_group_resource_read.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = _schema_action_group_resource_read.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = _schema_action_group_resource_read.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = _schema_action_group_resource_read.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = _schema_action_group_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + + +__all__ = ["Remove"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_show.py new file mode 100644 index 00000000000..eb9bc28c749 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/identity/_show.py @@ -0,0 +1,566 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group identity show", +) +class Show(AAZCommand): + """Show the details of managed identities. + + :example: Show the managed identities of an existing action group. + az monitor action-group identity show --name ag --resource-group rg + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}", "2024-10-01-preview", "identity"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + 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.action_group_name = AAZStrArg( + options=["-n", "--name", "--action-group-name"], + help="The name of the action group.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(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.selectors.subresource.required(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ActionGroupsGet(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/actionGroups/{actionGroupName}", + **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( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + 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() + _ShowHelper._build_schema_action_group_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_action_group_resource_read = None + + @classmethod + def _build_schema_action_group_resource_read(cls, _schema): + if cls._schema_action_group_resource_read is not None: + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + return + + cls._schema_action_group_resource_read = _schema_action_group_resource_read = AAZObjectType() + + action_group_resource_read = _schema_action_group_resource_read + action_group_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.identity = AAZIdentityObjectType() + action_group_resource_read.location = AAZStrType( + flags={"required": True}, + ) + action_group_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + action_group_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + action_group_resource_read.tags = AAZDictType() + action_group_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_action_group_resource_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_action_group_resource_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_action_group_resource_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_action_group_resource_read.properties + properties.arm_role_receivers = AAZListType( + serialized_name="armRoleReceivers", + ) + properties.automation_runbook_receivers = AAZListType( + serialized_name="automationRunbookReceivers", + ) + properties.azure_app_push_receivers = AAZListType( + serialized_name="azureAppPushReceivers", + ) + properties.azure_function_receivers = AAZListType( + serialized_name="azureFunctionReceivers", + ) + properties.email_receivers = AAZListType( + serialized_name="emailReceivers", + ) + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.event_hub_receivers = AAZListType( + serialized_name="eventHubReceivers", + ) + properties.group_short_name = AAZStrType( + serialized_name="groupShortName", + flags={"required": True}, + ) + properties.incident_receivers = AAZListType( + serialized_name="incidentReceivers", + ) + properties.itsm_receivers = AAZListType( + serialized_name="itsmReceivers", + ) + properties.logic_app_receivers = AAZListType( + serialized_name="logicAppReceivers", + ) + properties.sms_receivers = AAZListType( + serialized_name="smsReceivers", + ) + properties.voice_receivers = AAZListType( + serialized_name="voiceReceivers", + ) + properties.webhook_receivers = AAZListType( + serialized_name="webhookReceivers", + ) + + arm_role_receivers = _schema_action_group_resource_read.properties.arm_role_receivers + arm_role_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.arm_role_receivers.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.role_id = AAZStrType( + serialized_name="roleId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + automation_runbook_receivers = _schema_action_group_resource_read.properties.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrType( + serialized_name="automationAccountId", + flags={"required": True}, + ) + _element.is_global_runbook = AAZBoolType( + serialized_name="isGlobalRunbook", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType() + _element.runbook_name = AAZStrType( + serialized_name="runbookName", + flags={"required": True}, + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + _element.webhook_resource_id = AAZStrType( + serialized_name="webhookResourceId", + flags={"required": True}, + ) + + azure_app_push_receivers = _schema_action_group_resource_read.properties.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_app_push_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + azure_function_receivers = _schema_action_group_resource_read.properties.azure_function_receivers + azure_function_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrType( + serialized_name="functionAppResourceId", + flags={"required": True}, + ) + _element.function_name = AAZStrType( + serialized_name="functionName", + flags={"required": True}, + ) + _element.http_trigger_url = AAZStrType( + serialized_name="httpTriggerUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + email_receivers = _schema_action_group_resource_read.properties.email_receivers + email_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.email_receivers.Element + _element.email_address = AAZStrType( + serialized_name="emailAddress", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + event_hub_receivers = _schema_action_group_resource_read.properties.event_hub_receivers + event_hub_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.event_hub_receivers.Element + _element.event_hub_name = AAZStrType( + serialized_name="eventHubName", + flags={"required": True}, + ) + _element.event_hub_name_space = AAZStrType( + serialized_name="eventHubNameSpace", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + incident_receivers = _schema_action_group_resource_read.properties.incident_receivers + incident_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.incident_receivers.Element + _element.connection = AAZObjectType( + flags={"required": True}, + ) + _element.incident_management_service = AAZStrType( + serialized_name="incidentManagementService", + flags={"required": True}, + ) + _element.mappings = AAZDictType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + + connection = _schema_action_group_resource_read.properties.incident_receivers.Element.connection + connection.id = AAZStrType( + flags={"required": True}, + ) + connection.name = AAZStrType( + flags={"required": True}, + ) + + mappings = _schema_action_group_resource_read.properties.incident_receivers.Element.mappings + mappings.Element = AAZStrType() + + itsm_receivers = _schema_action_group_resource_read.properties.itsm_receivers + itsm_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.itsm_receivers.Element + _element.connection_id = AAZStrType( + serialized_name="connectionId", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.region = AAZStrType( + flags={"required": True}, + ) + _element.ticket_configuration = AAZStrType( + serialized_name="ticketConfiguration", + flags={"required": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"required": True}, + ) + + logic_app_receivers = _schema_action_group_resource_read.properties.logic_app_receivers + logic_app_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.logic_app_receivers.Element + _element.callback_url = AAZStrType( + serialized_name="callbackUrl", + flags={"required": True}, + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + sms_receivers = _schema_action_group_resource_read.properties.sms_receivers + sms_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.sms_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + _element.status = AAZStrType( + flags={"read_only": True}, + ) + + voice_receivers = _schema_action_group_resource_read.properties.voice_receivers + voice_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.voice_receivers.Element + _element.country_code = AAZStrType( + serialized_name="countryCode", + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.phone_number = AAZStrType( + serialized_name="phoneNumber", + flags={"required": True}, + ) + + webhook_receivers = _schema_action_group_resource_read.properties.webhook_receivers + webhook_receivers.Element = AAZObjectType() + + _element = _schema_action_group_resource_read.properties.webhook_receivers.Element + _element.identifier_uri = AAZStrType( + serialized_name="identifierUri", + ) + _element.managed_identity = AAZStrType( + serialized_name="managedIdentity", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.object_id = AAZStrType( + serialized_name="objectId", + ) + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + flags={"required": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + ) + _element.use_aad_auth = AAZBoolType( + serialized_name="useAadAuth", + ) + _element.use_common_alert_schema = AAZBoolType( + serialized_name="useCommonAlertSchema", + ) + + tags = _schema_action_group_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_action_group_resource_read.id + _schema.identity = cls._schema_action_group_resource_read.identity + _schema.location = cls._schema_action_group_resource_read.location + _schema.name = cls._schema_action_group_resource_read.name + _schema.properties = cls._schema_action_group_resource_read.properties + _schema.tags = cls._schema_action_group_resource_read.tags + _schema.type = cls._schema_action_group_resource_read.type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__cmd_group.py new file mode 100644 index 00000000000..7b26dc21c21 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__cmd_group.py @@ -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 action-group test-notifications", +) +class __CMDGroup(AAZCommandGroup): + """Manage action groups test-notifications. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__init__.py new file mode 100644 index 00000000000..a6df9f5a835 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/__init__.py @@ -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 ._create import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/_create.py new file mode 100644 index 00000000000..5ac17ca1cbf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/action_group/test_notifications/_create.py @@ -0,0 +1,822 @@ +# -------------------------------------------------------------------------------------------- +# 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 action-group test-notifications create", +) +class Create(AAZCommand): + """Create an action group test-notifications. + + :example: Create an action group test-notifications with action group + az monitor action-group test-notifications create --action-group MyActionGroup --resource-group MyResourceGroup -a email alice alice@example.com usecommonalertsChema --alert-type budget + """ + + _aaz_info = { + "version": "2024-10-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/actiongroups/{}/createnotifications", "2024-10-01-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.action_group_name = AAZStrArg( + options=["--action-group", "--action-group-name"], + help="The name of the action group.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.alert_type = AAZStrArg( + options=["--alert-type"], + help="The value of the supported alert type. Supported alert type values are: servicehealth, metricstaticthreshold, metricsdynamicthreshold, logalertv2, smartalert, webtestalert, logalertv1numresult, logalertv1metricmeasurement, resourcehealth, activitylog, budget", + required=True, + fmt=AAZStrArgFormat( + max_length=30, + ), + ) + + # define Arg Group "NotificationRequest" + + _args_schema = cls._args_schema + _args_schema.arm_role_receivers = AAZListArg( + options=["--arm-role-receivers"], + arg_group="NotificationRequest", + help="The list of ARM role receivers that are part of this action group. Roles are Azure RBAC roles and only built-in roles are supported.", + ) + _args_schema.automation_runbook_receivers = AAZListArg( + options=["--automation-runbook-receivers"], + arg_group="NotificationRequest", + help="The list of AutomationRunbook receivers that are part of this action group.", + ) + _args_schema.azure_app_push_receivers = AAZListArg( + options=["--azure-app-push-receivers"], + arg_group="NotificationRequest", + help="The list of AzureAppPush receivers that are part of this action group.", + ) + _args_schema.azure_function_receivers = AAZListArg( + options=["--azure-function-receivers"], + arg_group="NotificationRequest", + help="The list of azure function receivers that are part of this action group.", + ) + _args_schema.email_receivers = AAZListArg( + options=["--email-receivers"], + arg_group="NotificationRequest", + help="The list of email receivers that are part of this action group.", + ) + _args_schema.event_hub_receivers = AAZListArg( + options=["--event-hub-receivers"], + arg_group="NotificationRequest", + help="The list of event hub receivers that are part of this action group.", + ) + _args_schema.incident_receivers = AAZListArg( + options=["--incident-receivers"], + arg_group="NotificationRequest", + help="The list of incident receivers that are part of this action group.", + ) + _args_schema.itsm_receivers = AAZListArg( + options=["--itsm-receivers"], + arg_group="NotificationRequest", + help="The list of ITSM receivers that are part of this action group.", + ) + _args_schema.logic_app_receivers = AAZListArg( + options=["--logic-app-receivers"], + arg_group="NotificationRequest", + help="The list of logic app receivers that are part of this action group.", + ) + _args_schema.sms_receivers = AAZListArg( + options=["--sms-receivers"], + arg_group="NotificationRequest", + help="The list of SMS receivers that are part of this action group.", + ) + _args_schema.voice_receivers = AAZListArg( + options=["--voice-receivers"], + arg_group="NotificationRequest", + help="The list of voice receivers that are part of this action group.", + ) + _args_schema.webhook_receivers = AAZListArg( + options=["--webhook-receivers"], + arg_group="NotificationRequest", + help="The list of webhook receivers that are part of this action group.", + ) + + arm_role_receivers = cls._args_schema.arm_role_receivers + arm_role_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.arm_role_receivers.Element + _element.name = AAZStrArg( + options=["name"], + help="The name of the arm role receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.role_id = AAZStrArg( + options=["role-id"], + help="The arm role id.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + automation_runbook_receivers = cls._args_schema.automation_runbook_receivers + automation_runbook_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.automation_runbook_receivers.Element + _element.automation_account_id = AAZStrArg( + options=["automation-account-id"], + help="The Azure automation account Id which holds this runbook and authenticate to Azure resource.", + required=True, + ) + _element.is_global_runbook = AAZBoolArg( + options=["is-global-runbook"], + help="Indicates whether this instance is global runbook.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="Indicates name of the webhook.", + ) + _element.runbook_name = AAZStrArg( + options=["runbook-name"], + help="The name for this runbook.", + required=True, + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + _element.webhook_resource_id = AAZStrArg( + options=["webhook-resource-id"], + help="The resource id for webhook linked to this runbook.", + required=True, + ) + + azure_app_push_receivers = cls._args_schema.azure_app_push_receivers + azure_app_push_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.azure_app_push_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address registered for the Azure mobile app.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Azure mobile app push receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + + azure_function_receivers = cls._args_schema.azure_function_receivers + azure_function_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.azure_function_receivers.Element + _element.function_app_resource_id = AAZStrArg( + options=["function-app-resource-id"], + help="The azure resource id of the function app.", + required=True, + ) + _element.function_name = AAZStrArg( + options=["function-name"], + help="The function name in the function app.", + required=True, + ) + _element.http_trigger_url = AAZStrArg( + options=["http-trigger-url"], + help="The http trigger url where http request sent to.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the azure function receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + email_receivers = cls._args_schema.email_receivers + email_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.email_receivers.Element + _element.email_address = AAZStrArg( + options=["email-address"], + help="The email address of this receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the email receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + event_hub_receivers = cls._args_schema.event_hub_receivers + event_hub_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.event_hub_receivers.Element + _element.event_hub_name = AAZStrArg( + options=["event-hub-name"], + help="The name of the specific Event Hub queue", + required=True, + ) + _element.event_hub_name_space = AAZStrArg( + options=["event-hub-name-space"], + help="The Event Hub namespace", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Event hub receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.subscription_id = AAZStrArg( + options=["subscription-id"], + help="The Id for the subscription containing this event hub", + required=True, + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="The tenant Id for the subscription containing this event hub", + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + incident_receivers = cls._args_schema.incident_receivers + incident_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.incident_receivers.Element + _element.connection = AAZObjectArg( + options=["connection"], + help="The incident service connection", + required=True, + ) + _element.incident_management_service = AAZStrArg( + options=["incident-management-service"], + help="The incident management service type", + required=True, + enum={"Icm": "Icm"}, + ) + _element.mappings = AAZDictArg( + options=["mappings"], + help="Field mappings for the incident service", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Incident receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + + connection = cls._args_schema.incident_receivers.Element.connection + connection.id = AAZStrArg( + options=["id"], + help="GUID value representing the connection ID for the incident management service.", + required=True, + ) + connection.name = AAZStrArg( + options=["name"], + help="The name of the connection.", + required=True, + ) + + mappings = cls._args_schema.incident_receivers.Element.mappings + mappings.Element = AAZStrArg() + + itsm_receivers = cls._args_schema.itsm_receivers + itsm_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.itsm_receivers.Element + _element.connection_id = AAZStrArg( + options=["connection-id"], + help="Unique identification of ITSM connection among multiple defined in above workspace.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the Itsm receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.region = AAZStrArg( + options=["region"], + help="Region in which workspace resides. Supported values:'centralindia','japaneast','southeastasia','australiasoutheast','uksouth','westcentralus','canadacentral','eastus','westeurope'", + required=True, + ) + _element.ticket_configuration = AAZStrArg( + options=["ticket-configuration"], + help="JSON blob for the configurations of the ITSM action. CreateMultipleWorkItems option will be part of this blob as well.", + required=True, + ) + _element.workspace_id = AAZStrArg( + options=["workspace-id"], + help="OMS LA instance identifier.", + required=True, + ) + + logic_app_receivers = cls._args_schema.logic_app_receivers + logic_app_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.logic_app_receivers.Element + _element.callback_url = AAZStrArg( + options=["callback-url"], + help="The callback url where http request sent to.", + required=True, + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the logic app receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.resource_id = AAZStrArg( + options=["resource-id"], + help="The azure resource id of the logic app receiver.", + required=True, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + + sms_receivers = cls._args_schema.sms_receivers + sms_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.sms_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the SMS receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the SMS receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the SMS receiver.", + required=True, + ) + + voice_receivers = cls._args_schema.voice_receivers + voice_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.voice_receivers.Element + _element.country_code = AAZStrArg( + options=["country-code"], + help="The country code of the voice receiver.", + required=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the voice receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.phone_number = AAZStrArg( + options=["phone-number"], + help="The phone number of the voice receiver.", + required=True, + ) + + webhook_receivers = cls._args_schema.webhook_receivers + webhook_receivers.Element = AAZObjectArg() + + _element = cls._args_schema.webhook_receivers.Element + _element.identifier_uri = AAZStrArg( + options=["identifier-uri"], + help="Indicates the identifier uri for aad auth.", + ) + _element.managed_identity = AAZStrArg( + options=["managed-identity"], + help="The principal id of the managed identity. The value can be \"None\", \"SystemAssigned\" ", + ) + _element.name = AAZStrArg( + options=["name"], + help="The name of the webhook receiver. Names must be unique across all receivers within an action group.", + required=True, + ) + _element.object_id = AAZStrArg( + options=["object-id"], + help="Indicates the webhook app object Id for aad auth.", + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="The URI where webhooks should be sent.", + required=True, + ) + _element.tenant_id = AAZStrArg( + options=["tenant-id"], + help="Indicates the tenant id for aad auth.", + ) + _element.use_aad_auth = AAZBoolArg( + options=["use-aad-auth"], + help="Indicates whether or not use AAD authentication.", + default=False, + ) + _element.use_common_alert_schema = AAZBoolArg( + options=["use-common-alert-schema"], + help="Indicates whether to use common alert schema.", + default=False, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.ActionGroupsCreateNotificationsAtActionGroupResourceLevel(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 ActionGroupsCreateNotificationsAtActionGroupResourceLevel(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "location"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "location"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/actionGroups/{actionGroupName}/createNotifications", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "actionGroupName", self.ctx.args.action_group_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( + "api-version", "2024-10-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("alertType", AAZStrType, ".alert_type", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("armRoleReceivers", AAZListType, ".arm_role_receivers") + _builder.set_prop("automationRunbookReceivers", AAZListType, ".automation_runbook_receivers") + _builder.set_prop("azureAppPushReceivers", AAZListType, ".azure_app_push_receivers") + _builder.set_prop("azureFunctionReceivers", AAZListType, ".azure_function_receivers") + _builder.set_prop("emailReceivers", AAZListType, ".email_receivers") + _builder.set_prop("eventHubReceivers", AAZListType, ".event_hub_receivers") + _builder.set_prop("incidentReceivers", AAZListType, ".incident_receivers") + _builder.set_prop("itsmReceivers", AAZListType, ".itsm_receivers") + _builder.set_prop("logicAppReceivers", AAZListType, ".logic_app_receivers") + _builder.set_prop("smsReceivers", AAZListType, ".sms_receivers") + _builder.set_prop("voiceReceivers", AAZListType, ".voice_receivers") + _builder.set_prop("webhookReceivers", AAZListType, ".webhook_receivers") + + arm_role_receivers = _builder.get(".armRoleReceivers") + if arm_role_receivers is not None: + arm_role_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".armRoleReceivers[]") + if _elements is not None: + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("roleId", AAZStrType, ".role_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + automation_runbook_receivers = _builder.get(".automationRunbookReceivers") + if automation_runbook_receivers is not None: + automation_runbook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".automationRunbookReceivers[]") + if _elements is not None: + _elements.set_prop("automationAccountId", AAZStrType, ".automation_account_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("isGlobalRunbook", AAZBoolType, ".is_global_runbook", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name") + _elements.set_prop("runbookName", AAZStrType, ".runbook_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("serviceUri", AAZStrType, ".service_uri") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + _elements.set_prop("webhookResourceId", AAZStrType, ".webhook_resource_id", typ_kwargs={"flags": {"required": True}}) + + azure_app_push_receivers = _builder.get(".azureAppPushReceivers") + if azure_app_push_receivers is not None: + azure_app_push_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".azureAppPushReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + azure_function_receivers = _builder.get(".azureFunctionReceivers") + if azure_function_receivers is not None: + azure_function_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".azureFunctionReceivers[]") + if _elements is not None: + _elements.set_prop("functionAppResourceId", AAZStrType, ".function_app_resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("functionName", AAZStrType, ".function_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("httpTriggerUrl", AAZStrType, ".http_trigger_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + email_receivers = _builder.get(".emailReceivers") + if email_receivers is not None: + email_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".emailReceivers[]") + if _elements is not None: + _elements.set_prop("emailAddress", AAZStrType, ".email_address", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + event_hub_receivers = _builder.get(".eventHubReceivers") + if event_hub_receivers is not None: + event_hub_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".eventHubReceivers[]") + if _elements is not None: + _elements.set_prop("eventHubName", AAZStrType, ".event_hub_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("eventHubNameSpace", AAZStrType, ".event_hub_name_space", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("subscriptionId", AAZStrType, ".subscription_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + incident_receivers = _builder.get(".incidentReceivers") + if incident_receivers is not None: + incident_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".incidentReceivers[]") + if _elements is not None: + _elements.set_prop("connection", AAZObjectType, ".connection", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("incidentManagementService", AAZStrType, ".incident_management_service", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("mappings", AAZDictType, ".mappings", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + connection = _builder.get(".incidentReceivers[].connection") + if connection is not None: + connection.set_prop("id", AAZStrType, ".id", typ_kwargs={"flags": {"required": True}}) + connection.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + + mappings = _builder.get(".incidentReceivers[].mappings") + if mappings is not None: + mappings.set_elements(AAZStrType, ".") + + itsm_receivers = _builder.get(".itsmReceivers") + if itsm_receivers is not None: + itsm_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".itsmReceivers[]") + if _elements is not None: + _elements.set_prop("connectionId", AAZStrType, ".connection_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("region", AAZStrType, ".region", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("ticketConfiguration", AAZStrType, ".ticket_configuration", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("workspaceId", AAZStrType, ".workspace_id", typ_kwargs={"flags": {"required": True}}) + + logic_app_receivers = _builder.get(".logicAppReceivers") + if logic_app_receivers is not None: + logic_app_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".logicAppReceivers[]") + if _elements is not None: + _elements.set_prop("callbackUrl", AAZStrType, ".callback_url", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("resourceId", AAZStrType, ".resource_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + sms_receivers = _builder.get(".smsReceivers") + if sms_receivers is not None: + sms_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".smsReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + voice_receivers = _builder.get(".voiceReceivers") + if voice_receivers is not None: + voice_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".voiceReceivers[]") + if _elements is not None: + _elements.set_prop("countryCode", AAZStrType, ".country_code", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("phoneNumber", AAZStrType, ".phone_number", typ_kwargs={"flags": {"required": True}}) + + webhook_receivers = _builder.get(".webhookReceivers") + if webhook_receivers is not None: + webhook_receivers.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".webhookReceivers[]") + if _elements is not None: + _elements.set_prop("identifierUri", AAZStrType, ".identifier_uri") + _elements.set_prop("managedIdentity", AAZStrType, ".managed_identity") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("objectId", AAZStrType, ".object_id") + _elements.set_prop("serviceUri", AAZStrType, ".service_uri", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("tenantId", AAZStrType, ".tenant_id") + _elements.set_prop("useAadAuth", AAZBoolType, ".use_aad_auth") + _elements.set_prop("useCommonAlertSchema", AAZBoolType, ".use_common_alert_schema") + + return self.serialize_content(_content_value) + + 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.action_details = AAZListType( + serialized_name="actionDetails", + ) + _schema_on_200.completed_time = AAZStrType( + serialized_name="completedTime", + ) + _schema_on_200.context = AAZObjectType() + _schema_on_200.created_time = AAZStrType( + serialized_name="createdTime", + ) + _schema_on_200.state = AAZStrType( + flags={"required": True}, + ) + + action_details = cls._schema_on_200.action_details + action_details.Element = AAZObjectType() + + _element = cls._schema_on_200.action_details.Element + _element.detail = AAZStrType( + serialized_name="Detail", + ) + _element.mechanism_type = AAZStrType( + serialized_name="MechanismType", + ) + _element.name = AAZStrType( + serialized_name="Name", + ) + _element.send_time = AAZStrType( + serialized_name="SendTime", + ) + _element.status = AAZStrType( + serialized_name="Status", + ) + _element.sub_state = AAZStrType( + serialized_name="SubState", + ) + + context = cls._schema_on_200.context + context.context_type = AAZStrType( + serialized_name="contextType", + ) + context.notification_source = AAZStrType( + serialized_name="notificationSource", + ) + + return cls._schema_on_200 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__cmd_group.py new file mode 100644 index 00000000000..8c4250398e1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__cmd_group.py @@ -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 activity-log", +) +class __CMDGroup(AAZCommandGroup): + """Manage activity logs. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__init__.py new file mode 100644 index 00000000000..fb13093004c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/__init__.py @@ -0,0 +1,13 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._list import * +from ._list_categories import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list.py new file mode 100644 index 00000000000..13598fba3d7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list.py @@ -0,0 +1,321 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log list", +) +class List(AAZCommand): + """List and query activity log events. + + :example: List all events from July 1st, looking forward one week. + az monitor activity-log list --start-time 2018-07-01 --offset 7d + + :example: List events within the past six hours based on a correlation ID. + az monitor activity-log list --correlation-id b5eac9d2-e829-4c9a-9efb-586d19417c5f + + :example: List events within the past hour based on resource group. + az monitor activity-log list -g ResourceGroup --offset 1h + """ + + _aaz_info = { + "version": "2015-04-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/eventtypes/management/values", "2015-04-01"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.filter = AAZStrArg( + options=["--filter"], + help="Reduces the set of data collected.
This argument is required and it also requires at least the start date/time.
The **$filter** argument is very restricted and allows only the following patterns.
- *List events for a resource group*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceGroupName eq 'resourceGroupName'.
- *List events for resource*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.
- *List events for a subscription in a time range*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z'.
- *List events for a resource provider*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.
- *List events for a correlation Id*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq 'correlationID'.

**NOTE**: No other syntax is allowed.", + required=True, + ) + _args_schema.select = AAZStrArg( + options=["--select"], + help="Used to fetch events with only the given properties.
The **$select** argument is a comma separated list of property names to be returned. Possible values are: *authorization*, *claims*, *correlationId*, *description*, *eventDataId*, *eventName*, *eventTimestamp*, *httpRequest*, *level*, *operationId*, *operationName*, *properties*, *resourceGroupName*, *resourceProviderName*, *resourceId*, *status*, *submissionTimestamp*, *subStatus*, *subscriptionId*", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActivityLogsList(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class ActivityLogsList(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}/providers/Microsoft.Insights/eventtypes/management/values", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "$filter", self.ctx.args.filter, + required=True, + ), + **self.serialize_query_param( + "$select", self.ctx.args.select, + ), + **self.serialize_query_param( + "api-version", "2015-04-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.authorization = AAZObjectType() + _element.caller = AAZStrType( + flags={"read_only": True}, + ) + _element.category = AAZObjectType() + _ListHelper._build_schema_localizable_string_read(_element.category) + _element.claims = AAZDictType( + flags={"read_only": True}, + ) + _element.correlation_id = AAZStrType( + serialized_name="correlationId", + flags={"read_only": True}, + ) + _element.description = AAZStrType( + flags={"read_only": True}, + ) + _element.event_data_id = AAZStrType( + serialized_name="eventDataId", + flags={"read_only": True}, + ) + _element.event_name = AAZObjectType( + serialized_name="eventName", + ) + _ListHelper._build_schema_localizable_string_read(_element.event_name) + _element.event_timestamp = AAZStrType( + serialized_name="eventTimestamp", + flags={"read_only": True}, + ) + _element.http_request = AAZObjectType( + serialized_name="httpRequest", + ) + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.level = AAZStrType( + flags={"read_only": True}, + ) + _element.operation_id = AAZStrType( + serialized_name="operationId", + flags={"read_only": True}, + ) + _element.operation_name = AAZObjectType( + serialized_name="operationName", + ) + _ListHelper._build_schema_localizable_string_read(_element.operation_name) + _element.properties = AAZDictType( + flags={"read_only": True}, + ) + _element.resource_group_name = AAZStrType( + serialized_name="resourceGroupName", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.resource_provider_name = AAZObjectType( + serialized_name="resourceProviderName", + ) + _element.resource_type = AAZObjectType( + serialized_name="resourceType", + ) + _element.status = AAZObjectType() + _ListHelper._build_schema_localizable_string_read(_element.status) + _element.sub_status = AAZObjectType( + serialized_name="subStatus", + ) + _ListHelper._build_schema_localizable_string_read(_element.sub_status) + _element.submission_timestamp = AAZStrType( + serialized_name="submissionTimestamp", + flags={"read_only": True}, + ) + _element.subscription_id = AAZStrType( + serialized_name="subscriptionId", + flags={"read_only": True}, + ) + _element.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + + authorization = cls._schema_on_200.value.Element.authorization + authorization.action = AAZStrType() + authorization.role = AAZStrType() + authorization.scope = AAZStrType() + + claims = cls._schema_on_200.value.Element.claims + claims.Element = AAZStrType() + + http_request = cls._schema_on_200.value.Element.http_request + http_request.client_ip_address = AAZStrType( + serialized_name="clientIpAddress", + ) + http_request.client_request_id = AAZStrType( + serialized_name="clientRequestId", + ) + http_request.method = AAZStrType() + http_request.uri = AAZStrType() + + properties = cls._schema_on_200.value.Element.properties + properties.Element = AAZStrType() + + resource_provider_name = cls._schema_on_200.value.Element.resource_provider_name + resource_provider_name.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + resource_provider_name.value = AAZStrType( + flags={"required": True}, + ) + + resource_type = cls._schema_on_200.value.Element.resource_type + resource_type.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + resource_type.value = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_localizable_string_read = None + + @classmethod + def _build_schema_localizable_string_read(cls, _schema): + if cls._schema_localizable_string_read is not None: + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + return + + cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType() + + localizable_string_read = _schema_localizable_string_read + localizable_string_read.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + localizable_string_read.value = AAZStrType( + flags={"required": True}, + ) + + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list_categories.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list_categories.py new file mode 100644 index 00000000000..151d3844076 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/_list_categories.py @@ -0,0 +1,137 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log list-categories", +) +class ListCategories(AAZCommand): + """List the list of available event categories supported in the Activity Logs Service. + + The current list includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy. + """ + + _aaz_info = { + "version": "2015-04-01", + "resources": [ + ["mgmt-plane", "/providers/microsoft.insights/eventcategories", "2015-04-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return self._output() + + def _execute_operations(self): + self.pre_operations() + self.EventCategoriesList(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.value, client_flatten=True) + return result + + class EventCategoriesList(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( + "/providers/Microsoft.Insights/eventcategories", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2015-04-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.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + _element.value = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +class _ListCategoriesHelper: + """Helper class for ListCategories""" + + +__all__ = ["ListCategories"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__cmd_group.py new file mode 100644 index 00000000000..4943570856b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__cmd_group.py @@ -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 activity-log alert", +) +class __CMDGroup(AAZCommandGroup): + """Manage activity log alert rules. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_create.py new file mode 100644 index 00000000000..4ca35697fe3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_create.py @@ -0,0 +1,443 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log alert create", +) +class Create(AAZCommand): + """Create a default activity log alert rule. + + This command will create a default activity log with one condition which compares if the activities logs 'category' field equals to 'ServiceHealth'. The newly created activity log alert does not have any action groups attached to it. + + :example: Create an alert rule with default settings. + az monitor activity-log alert create -n AlertName -g ResourceGroup + + :example: Create an alert rule with condition about error level service health log. + az monitor activity-log alert create -n AlertName -g ResourceGroup --condition category=ServiceHealth and level=Error + + :example: Create an alert rule with an action group and specify webhook properties. + az monitor activity-log alert create -n AlertName -g ResourceGroup -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/actionGroups/{ActionGroup} -w usage=test owner=jane + + :example: Create an alert rule which is initially disabled. + az monitor activity-log alert create -n AlertName -g ResourceGroup --disable + """ + + _aaz_info = { + "version": "2020-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts/{}", "2020-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.activity_log_alert_name = AAZStrArg( + options=["-n", "--name", "--activity-log-alert-name"], + help="The name of the activity log alert.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.location = AAZResourceLocationArg( + help="The location of the resource. Since Azure Activity Log Alerts is a global service, the location of the rules should always be 'global'.", + default="global", + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.action_groups = AAZListArg( + options=["--action-groups"], + help="The list of the Action Groups.", + ) + _args_schema.all_of = AAZListArg( + options=["--all-of"], + help="The list of Activity Log Alert rule conditions.", + ) + _args_schema.description = AAZStrArg( + options=["--description"], + help="A description of this Activity Log Alert rule.", + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + help="Indicates whether this Activity Log Alert rule is enabled. If an Activity Log Alert rule is not enabled, then none of its actions will be activated.", + default=True, + ) + _args_schema.scopes = AAZListArg( + options=["--scopes"], + help="A list of resource IDs that will be used as prefixes. The alert will only apply to Activity Log events with resource IDs that fall under one of these prefixes. This list must include at least one item.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="The tags of the resource.", + ) + + action_groups = cls._args_schema.action_groups + action_groups.Element = AAZObjectArg() + + _element = cls._args_schema.action_groups.Element + _element.action_group_id = AAZStrArg( + options=["action-group-id"], + help="The resource ID of the Action Group. This cannot be null or empty.", + required=True, + ) + _element.webhook_properties = AAZDictArg( + options=["webhook-properties"], + help="the dictionary of custom properties to include with the post operation. These data are appended to the webhook payload.", + ) + + webhook_properties = cls._args_schema.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrArg() + + all_of = cls._args_schema.all_of + all_of.Element = AAZObjectArg() + + _element = cls._args_schema.all_of.Element + _element.any_of = AAZListArg( + options=["any-of"], + help="An Activity Log Alert rule condition that is met when at least one of its member leaf conditions are met.", + ) + _element.contains_any = AAZListArg( + options=["contains-any"], + help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.", + ) + _element.equals = AAZStrArg( + options=["equals"], + help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.", + ) + _element.field = AAZStrArg( + options=["field"], + help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.", + ) + + any_of = cls._args_schema.all_of.Element.any_of + any_of.Element = AAZObjectArg() + + _element = cls._args_schema.all_of.Element.any_of.Element + _element.contains_any = AAZListArg( + options=["contains-any"], + help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.", + ) + _element.equals = AAZStrArg( + options=["equals"], + help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.", + ) + _element.field = AAZStrArg( + options=["field"], + help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.", + ) + + contains_any = cls._args_schema.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrArg() + + contains_any = cls._args_schema.all_of.Element.contains_any + contains_any.Element = AAZStrArg() + + scopes = cls._args_schema.scopes + scopes.Element = AAZStrArg() + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActivityLogAlertsCreateOrUpdate(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 ActivityLogAlertsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "activityLogAlertName", self.ctx.args.activity_log_alert_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( + "api-version", "2020-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location") + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("actions", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("condition", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("enabled", AAZBoolType, ".enabled") + properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}}) + + actions = _builder.get(".properties.actions") + if actions is not None: + actions.set_prop("actionGroups", AAZListType, ".action_groups") + + action_groups = _builder.get(".properties.actions.actionGroups") + if action_groups is not None: + action_groups.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.actions.actionGroups[]") + if _elements is not None: + _elements.set_prop("actionGroupId", AAZStrType, ".action_group_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("webhookProperties", AAZDictType, ".webhook_properties") + + webhook_properties = _builder.get(".properties.actions.actionGroups[].webhookProperties") + if webhook_properties is not None: + webhook_properties.set_elements(AAZStrType, ".") + + condition = _builder.get(".properties.condition") + if condition is not None: + condition.set_prop("allOf", AAZListType, ".all_of", typ_kwargs={"flags": {"required": True}}) + + all_of = _builder.get(".properties.condition.allOf") + if all_of is not None: + all_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.condition.allOf[]") + if _elements is not None: + _elements.set_prop("anyOf", AAZListType, ".any_of") + _elements.set_prop("containsAny", AAZListType, ".contains_any") + _elements.set_prop("equals", AAZStrType, ".equals") + _elements.set_prop("field", AAZStrType, ".field") + + any_of = _builder.get(".properties.condition.allOf[].anyOf") + if any_of is not None: + any_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.condition.allOf[].anyOf[]") + if _elements is not None: + _elements.set_prop("containsAny", AAZListType, ".contains_any") + _elements.set_prop("equals", AAZStrType, ".equals") + _elements.set_prop("field", AAZStrType, ".field") + + contains_any = _builder.get(".properties.condition.allOf[].anyOf[].containsAny") + if contains_any is not None: + contains_any.set_elements(AAZStrType, ".") + + contains_any = _builder.get(".properties.condition.allOf[].containsAny") + if contains_any is not None: + contains_any.set_elements(AAZStrType, ".") + + scopes = _builder.get(".properties.scopes") + if scopes is not None: + scopes.set_elements(AAZStrType, ".") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType() + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.actions = AAZObjectType( + flags={"required": True}, + ) + properties.condition = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType() + properties.scopes = AAZListType( + flags={"required": True}, + ) + + actions = cls._schema_on_200_201.properties.actions + actions.action_groups = AAZListType( + serialized_name="actionGroups", + ) + + action_groups = cls._schema_on_200_201.properties.actions.action_groups + action_groups.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.actions.action_groups.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + flags={"required": True}, + ) + _element.webhook_properties = AAZDictType( + serialized_name="webhookProperties", + ) + + webhook_properties = cls._schema_on_200_201.properties.actions.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrType() + + condition = cls._schema_on_200_201.properties.condition + condition.all_of = AAZListType( + serialized_name="allOf", + flags={"required": True}, + ) + + all_of = cls._schema_on_200_201.properties.condition.all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.condition.all_of.Element + _element.any_of = AAZListType( + serialized_name="anyOf", + ) + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + any_of = cls._schema_on_200_201.properties.condition.all_of.Element.any_of + any_of.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.condition.all_of.Element.any_of.Element + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + contains_any = cls._schema_on_200_201.properties.condition.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrType() + + contains_any = cls._schema_on_200_201.properties.condition.all_of.Element.contains_any + contains_any.Element = AAZStrType() + + scopes = cls._schema_on_200_201.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_delete.py new file mode 100644 index 00000000000..fe9579ad2af --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_delete.py @@ -0,0 +1,135 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log alert delete", +) +class Delete(AAZCommand): + """Delete an activity log alert. + """ + + _aaz_info = { + "version": "2020-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts/{}", "2020-10-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.activity_log_alert_name = AAZStrArg( + options=["-n", "--name", "--activity-log-alert-name"], + help="The name of the activity log alert.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActivityLogAlertsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class ActivityLogAlertsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "activityLogAlertName", self.ctx.args.activity_log_alert_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( + "api-version", "2020-10-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_list.py new file mode 100644 index 00000000000..2b0b03f8202 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_list.py @@ -0,0 +1,425 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log alert list", +) +class List(AAZCommand): + """List activity log alert rules under a resource group or the current subscription. + """ + + _aaz_info = { + "version": "2020-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/activitylogalerts", "2020-10-01"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts", "2020-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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.ActivityLogAlertsListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.ActivityLogAlertsListBySubscriptionId(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.value, client_flatten=True) + return result + + class ActivityLogAlertsListByResourceGroup(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/activityLogAlerts", + **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( + "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( + "api-version", "2020-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType() + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.actions = AAZObjectType( + flags={"required": True}, + ) + properties.condition = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType() + properties.scopes = AAZListType( + flags={"required": True}, + ) + + actions = cls._schema_on_200.value.Element.properties.actions + actions.action_groups = AAZListType( + serialized_name="actionGroups", + ) + + action_groups = cls._schema_on_200.value.Element.properties.actions.action_groups + action_groups.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.actions.action_groups.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + flags={"required": True}, + ) + _element.webhook_properties = AAZDictType( + serialized_name="webhookProperties", + ) + + webhook_properties = cls._schema_on_200.value.Element.properties.actions.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrType() + + condition = cls._schema_on_200.value.Element.properties.condition + condition.all_of = AAZListType( + serialized_name="allOf", + flags={"required": True}, + ) + + all_of = cls._schema_on_200.value.Element.properties.condition.all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.condition.all_of.Element + _element.any_of = AAZListType( + serialized_name="anyOf", + ) + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + any_of = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of + any_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of.Element + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + contains_any = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrType() + + contains_any = cls._schema_on_200.value.Element.properties.condition.all_of.Element.contains_any + contains_any.Element = AAZStrType() + + scopes = cls._schema_on_200.value.Element.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class ActivityLogAlertsListBySubscriptionId(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}/providers/Microsoft.Insights/activityLogAlerts", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType() + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.actions = AAZObjectType( + flags={"required": True}, + ) + properties.condition = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType() + properties.scopes = AAZListType( + flags={"required": True}, + ) + + actions = cls._schema_on_200.value.Element.properties.actions + actions.action_groups = AAZListType( + serialized_name="actionGroups", + ) + + action_groups = cls._schema_on_200.value.Element.properties.actions.action_groups + action_groups.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.actions.action_groups.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + flags={"required": True}, + ) + _element.webhook_properties = AAZDictType( + serialized_name="webhookProperties", + ) + + webhook_properties = cls._schema_on_200.value.Element.properties.actions.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrType() + + condition = cls._schema_on_200.value.Element.properties.condition + condition.all_of = AAZListType( + serialized_name="allOf", + flags={"required": True}, + ) + + all_of = cls._schema_on_200.value.Element.properties.condition.all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.condition.all_of.Element + _element.any_of = AAZListType( + serialized_name="anyOf", + ) + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + any_of = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of + any_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of.Element + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + contains_any = cls._schema_on_200.value.Element.properties.condition.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrType() + + contains_any = cls._schema_on_200.value.Element.properties.condition.all_of.Element.contains_any + contains_any.Element = AAZStrType() + + scopes = cls._schema_on_200.value.Element.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_show.py new file mode 100644 index 00000000000..4d03f869bfa --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_show.py @@ -0,0 +1,249 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log alert show", +) +class Show(AAZCommand): + """Get an activity log alert. + """ + + _aaz_info = { + "version": "2020-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts/{}", "2020-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.activity_log_alert_name = AAZStrArg( + options=["-n", "--name", "--activity-log-alert-name"], + help="The name of the activity log alert.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActivityLogAlertsGet(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 ActivityLogAlertsGet(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/activityLogAlerts/{activityLogAlertName}", + **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( + "activityLogAlertName", self.ctx.args.activity_log_alert_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( + "api-version", "2020-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType() + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.actions = AAZObjectType( + flags={"required": True}, + ) + properties.condition = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType() + properties.scopes = AAZListType( + flags={"required": True}, + ) + + actions = cls._schema_on_200.properties.actions + actions.action_groups = AAZListType( + serialized_name="actionGroups", + ) + + action_groups = cls._schema_on_200.properties.actions.action_groups + action_groups.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.actions.action_groups.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + flags={"required": True}, + ) + _element.webhook_properties = AAZDictType( + serialized_name="webhookProperties", + ) + + webhook_properties = cls._schema_on_200.properties.actions.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrType() + + condition = cls._schema_on_200.properties.condition + condition.all_of = AAZListType( + serialized_name="allOf", + flags={"required": True}, + ) + + all_of = cls._schema_on_200.properties.condition.all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.condition.all_of.Element + _element.any_of = AAZListType( + serialized_name="anyOf", + ) + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + any_of = cls._schema_on_200.properties.condition.all_of.Element.any_of + any_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.condition.all_of.Element.any_of.Element + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + contains_any = cls._schema_on_200.properties.condition.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrType() + + contains_any = cls._schema_on_200.properties.condition.all_of.Element.contains_any + contains_any.Element = AAZStrType() + + scopes = cls._schema_on_200.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_update.py new file mode 100644 index 00000000000..cb0af48377d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/activity_log/alert/_update.py @@ -0,0 +1,602 @@ +# -------------------------------------------------------------------------------------------- +# 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 activity-log alert update", +) +class Update(AAZCommand): + """Update a new activity log alert or update an existing one. + + :example: Update the condition + az monitor activity-log alert update -n AlertName -g ResourceGroup --condition category=ServiceHealth and level=Error + + :example: Disable an alert rule. + az monitor activity-log alert update -n AlertName -g ResourceGroup --enable false + + :example: Update the details of this activity log alert rule. + az monitor activity-log alert update --enabled true --name MyActivityLogAlerts --resource- group MyResourceGroup --subscription MySubscription + + :example: Update the details of this activity log alert. + az monitor activity-log alert update --name MyActivityLogAlerts --resource-group MyResourceGroup --tags key=value + """ + + _aaz_info = { + "version": "2020-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts/{}", "2020-10-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.activity_log_alert_name = AAZStrArg( + options=["-n", "--name", "--activity-log-alert-name"], + help="The name of the activity log alert.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.action_groups = AAZListArg( + options=["--action-groups"], + help="The list of the Action Groups.", + nullable=True, + ) + _args_schema.all_of = AAZListArg( + options=["--all-of"], + help="The list of Activity Log Alert rule conditions.", + ) + _args_schema.description = AAZStrArg( + options=["--description"], + help="A description of this Activity Log Alert rule.", + nullable=True, + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + help="Indicates whether this Activity Log Alert rule is enabled. If an Activity Log Alert rule is not enabled, then none of its actions will be activated.", + nullable=True, + ) + _args_schema.scopes = AAZListArg( + options=["--scopes"], + help="A list of resource IDs that will be used as prefixes. The alert will only apply to Activity Log events with resource IDs that fall under one of these prefixes. This list must include at least one item.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="The tags of the resource.", + nullable=True, + ) + + action_groups = cls._args_schema.action_groups + action_groups.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.action_groups.Element + _element.action_group_id = AAZStrArg( + options=["action-group-id"], + help="The resource ID of the Action Group. This cannot be null or empty.", + ) + _element.webhook_properties = AAZDictArg( + options=["webhook-properties"], + help="the dictionary of custom properties to include with the post operation. These data are appended to the webhook payload.", + nullable=True, + ) + + webhook_properties = cls._args_schema.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrArg( + nullable=True, + ) + + all_of = cls._args_schema.all_of + all_of.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.all_of.Element + _element.any_of = AAZListArg( + options=["any-of"], + help="An Activity Log Alert rule condition that is met when at least one of its member leaf conditions are met.", + nullable=True, + ) + _element.contains_any = AAZListArg( + options=["contains-any"], + help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.", + nullable=True, + ) + _element.equals = AAZStrArg( + options=["equals"], + help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.", + nullable=True, + ) + _element.field = AAZStrArg( + options=["field"], + help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.", + nullable=True, + ) + + any_of = cls._args_schema.all_of.Element.any_of + any_of.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.all_of.Element.any_of.Element + _element.contains_any = AAZListArg( + options=["contains-any"], + help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.", + nullable=True, + ) + _element.equals = AAZStrArg( + options=["equals"], + help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.", + nullable=True, + ) + _element.field = AAZStrArg( + options=["field"], + help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.", + nullable=True, + ) + + contains_any = cls._args_schema.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrArg( + nullable=True, + ) + + contains_any = cls._args_schema.all_of.Element.contains_any + contains_any.Element = AAZStrArg( + nullable=True, + ) + + scopes = cls._args_schema.scopes + scopes.Element = AAZStrArg( + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ActivityLogAlertsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.ActivityLogAlertsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class ActivityLogAlertsGet(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/activityLogAlerts/{activityLogAlertName}", + **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( + "activityLogAlertName", self.ctx.args.activity_log_alert_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( + "api-version", "2020-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() + _UpdateHelper._build_schema_activity_log_alert_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ActivityLogAlertsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "activityLogAlertName", self.ctx.args.activity_log_alert_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( + "api-version", "2020-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_activity_log_alert_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("actions", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("condition", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("enabled", AAZBoolType, ".enabled") + properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}}) + + actions = _builder.get(".properties.actions") + if actions is not None: + actions.set_prop("actionGroups", AAZListType, ".action_groups") + + action_groups = _builder.get(".properties.actions.actionGroups") + if action_groups is not None: + action_groups.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.actions.actionGroups[]") + if _elements is not None: + _elements.set_prop("actionGroupId", AAZStrType, ".action_group_id", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("webhookProperties", AAZDictType, ".webhook_properties") + + webhook_properties = _builder.get(".properties.actions.actionGroups[].webhookProperties") + if webhook_properties is not None: + webhook_properties.set_elements(AAZStrType, ".") + + condition = _builder.get(".properties.condition") + if condition is not None: + condition.set_prop("allOf", AAZListType, ".all_of", typ_kwargs={"flags": {"required": True}}) + + all_of = _builder.get(".properties.condition.allOf") + if all_of is not None: + all_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.condition.allOf[]") + if _elements is not None: + _elements.set_prop("anyOf", AAZListType, ".any_of") + _elements.set_prop("containsAny", AAZListType, ".contains_any") + _elements.set_prop("equals", AAZStrType, ".equals") + _elements.set_prop("field", AAZStrType, ".field") + + any_of = _builder.get(".properties.condition.allOf[].anyOf") + if any_of is not None: + any_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.condition.allOf[].anyOf[]") + if _elements is not None: + _elements.set_prop("containsAny", AAZListType, ".contains_any") + _elements.set_prop("equals", AAZStrType, ".equals") + _elements.set_prop("field", AAZStrType, ".field") + + contains_any = _builder.get(".properties.condition.allOf[].anyOf[].containsAny") + if contains_any is not None: + contains_any.set_elements(AAZStrType, ".") + + contains_any = _builder.get(".properties.condition.allOf[].containsAny") + if contains_any is not None: + contains_any.set_elements(AAZStrType, ".") + + scopes = _builder.get(".properties.scopes") + if scopes is not None: + scopes.set_elements(AAZStrType, ".") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_activity_log_alert_resource_read = None + + @classmethod + def _build_schema_activity_log_alert_resource_read(cls, _schema): + if cls._schema_activity_log_alert_resource_read is not None: + _schema.id = cls._schema_activity_log_alert_resource_read.id + _schema.location = cls._schema_activity_log_alert_resource_read.location + _schema.name = cls._schema_activity_log_alert_resource_read.name + _schema.properties = cls._schema_activity_log_alert_resource_read.properties + _schema.tags = cls._schema_activity_log_alert_resource_read.tags + _schema.type = cls._schema_activity_log_alert_resource_read.type + return + + cls._schema_activity_log_alert_resource_read = _schema_activity_log_alert_resource_read = AAZObjectType() + + activity_log_alert_resource_read = _schema_activity_log_alert_resource_read + activity_log_alert_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + activity_log_alert_resource_read.location = AAZStrType() + activity_log_alert_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + activity_log_alert_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + activity_log_alert_resource_read.tags = AAZDictType() + activity_log_alert_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_activity_log_alert_resource_read.properties + properties.actions = AAZObjectType( + flags={"required": True}, + ) + properties.condition = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType() + properties.scopes = AAZListType( + flags={"required": True}, + ) + + actions = _schema_activity_log_alert_resource_read.properties.actions + actions.action_groups = AAZListType( + serialized_name="actionGroups", + ) + + action_groups = _schema_activity_log_alert_resource_read.properties.actions.action_groups + action_groups.Element = AAZObjectType() + + _element = _schema_activity_log_alert_resource_read.properties.actions.action_groups.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + flags={"required": True}, + ) + _element.webhook_properties = AAZDictType( + serialized_name="webhookProperties", + ) + + webhook_properties = _schema_activity_log_alert_resource_read.properties.actions.action_groups.Element.webhook_properties + webhook_properties.Element = AAZStrType() + + condition = _schema_activity_log_alert_resource_read.properties.condition + condition.all_of = AAZListType( + serialized_name="allOf", + flags={"required": True}, + ) + + all_of = _schema_activity_log_alert_resource_read.properties.condition.all_of + all_of.Element = AAZObjectType() + + _element = _schema_activity_log_alert_resource_read.properties.condition.all_of.Element + _element.any_of = AAZListType( + serialized_name="anyOf", + ) + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + any_of = _schema_activity_log_alert_resource_read.properties.condition.all_of.Element.any_of + any_of.Element = AAZObjectType() + + _element = _schema_activity_log_alert_resource_read.properties.condition.all_of.Element.any_of.Element + _element.contains_any = AAZListType( + serialized_name="containsAny", + ) + _element.equals = AAZStrType() + _element.field = AAZStrType() + + contains_any = _schema_activity_log_alert_resource_read.properties.condition.all_of.Element.any_of.Element.contains_any + contains_any.Element = AAZStrType() + + contains_any = _schema_activity_log_alert_resource_read.properties.condition.all_of.Element.contains_any + contains_any.Element = AAZStrType() + + scopes = _schema_activity_log_alert_resource_read.properties.scopes + scopes.Element = AAZStrType() + + tags = _schema_activity_log_alert_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_activity_log_alert_resource_read.id + _schema.location = cls._schema_activity_log_alert_resource_read.location + _schema.name = cls._schema_activity_log_alert_resource_read.name + _schema.properties = cls._schema_activity_log_alert_resource_read.properties + _schema.tags = cls._schema_activity_log_alert_resource_read.tags + _schema.type = cls._schema_activity_log_alert_resource_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__cmd_group.py new file mode 100644 index 00000000000..ba0fc35b6d3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__cmd_group.py @@ -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"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__init__.py new file mode 100644 index 00000000000..56240e6757e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._show_predictive_metric import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_create.py new file mode 100644 index 00000000000..cae05d0530d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_create.py @@ -0,0 +1,961 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Create(AAZCommand): + """Create an autoscale setting. + + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings. + + :example: Create autoscale settings to scale between 2 and 5 instances (3 as default). Email the administrator when scaling occurs. + az monitor autoscale create -g myrg --resource resource-id --min-count 2 --max-count 5 --count 3 --email-administrator + az monitor autoscale rule create -g myrg --autoscale-name resource-name --scale out 1 --condition "Percentage CPU > 75 avg 5m" + az monitor autoscale rule create -g myrg --autoscale-name resource-name --scale in 1 --condition "Percentage CPU < 25 avg 5m" + + :example: Create autoscale settings for exactly 4 instances. + az monitor autoscale create -g myrg --resource resource-id --count 4 + + :example: Create new autoscale settings. + az monitor autoscale create --count 3 --max-count 5 --min-count 2 --name MyAutoscaleSettings --resource myScaleSet --resource-group MyResourceGroup --resource-type Microsoft.Compute/virtualMachineScaleSets + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings/{}", "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_name = AAZStrArg( + options=["-n", "--name", "--autoscale-name"], + help="The autoscale setting name.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.location = AAZResourceLocationArg( + help="Resource location", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + help="the enabled flag. Specifies whether automatic scaling is enabled for the resource. The default value is 'false'.", + default=False, + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater in length than 128 characters and a value no greater in length than 256 characters.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Predictive Policy" + + _args_schema = cls._args_schema + _args_schema.scale_look_ahead_time = AAZDurationArg( + options=["--scale-look-ahead-time"], + arg_group="Predictive Policy", + 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).", + ) + _args_schema.scale_mode = AAZStrArg( + options=["--scale-mode"], + arg_group="Predictive Policy", + help="the predictive autoscale mode", + enum={"Disabled": "Disabled", "Enabled": "Enabled", "ForecastOnly": "ForecastOnly"}, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.notifications = AAZListArg( + options=["--notifications"], + arg_group="Properties", + help="the collection of notifications.", + ) + _args_schema.profiles = AAZListArg( + options=["--profiles"], + arg_group="Properties", + help="the collection of automatic scaling profiles that specify different scaling parameters for different time periods. A maximum of 20 profiles can be specified.", + required=True, + ) + _args_schema.target_resource_location = AAZStrArg( + options=["--target-resource-location"], + arg_group="Properties", + help="the location of the resource that the autoscale setting should be added to.", + ) + _args_schema.target_resource_uri = AAZStrArg( + options=["--target-resource-uri"], + arg_group="Properties", + help="the resource identifier of the resource that the autoscale setting should be added to.", + ) + + notifications = cls._args_schema.notifications + notifications.Element = AAZObjectArg() + + _element = cls._args_schema.notifications.Element + _element.email = AAZObjectArg( + options=["email"], + help="the email notification.", + ) + _element.operation = AAZStrArg( + options=["operation"], + help="the operation associated with the notification and its value must be \"scale\"", + required=True, + enum={"Scale": "Scale"}, + ) + _element.webhooks = AAZListArg( + options=["webhooks"], + help="the collection of webhook notifications.", + ) + + email = cls._args_schema.notifications.Element.email + email.custom_emails = AAZListArg( + options=["custom-emails"], + help="the custom e-mails list. This value can be null or empty, in which case this attribute will be ignored.", + ) + email.send_to_subscription_administrator = AAZBoolArg( + options=["send-to-subscription-administrator"], + help="a value indicating whether to send email to subscription administrator.", + default=False, + ) + email.send_to_subscription_co_administrators = AAZBoolArg( + options=["send-to-subscription-co-administrators"], + help="a value indicating whether to send email to subscription co-administrators.", + default=False, + ) + + custom_emails = cls._args_schema.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrArg() + + webhooks = cls._args_schema.notifications.Element.webhooks + webhooks.Element = AAZObjectArg() + + _element = cls._args_schema.notifications.Element.webhooks.Element + _element.properties = AAZDictArg( + options=["properties"], + help="a property bag of settings. This value can be empty.", + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="the service address to receive the notification.", + ) + + properties = cls._args_schema.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrArg() + + profiles = cls._args_schema.profiles + profiles.Element = AAZObjectArg() + + _element = cls._args_schema.profiles.Element + _element.capacity = AAZObjectArg( + options=["capacity"], + help="the number of instances that can be used during this profile.", + required=True, + ) + _element.fixed_date = AAZObjectArg( + options=["fixed-date"], + help="the specific date-time for the profile. This element is not used if the Recurrence element is used.", + ) + _element.name = AAZStrArg( + options=["name"], + help="the name of the profile.", + required=True, + ) + _element.recurrence = AAZObjectArg( + options=["recurrence"], + help="the repeating times at which this profile begins. This element is not used if the FixedDate element is used.", + ) + _element.rules = AAZListArg( + options=["rules"], + help="the collection of rules that provide the triggers and parameters for the scaling action. A maximum of 10 rules can be specified.", + required=True, + ) + + capacity = cls._args_schema.profiles.Element.capacity + capacity.default = AAZStrArg( + options=["default"], + help="the number of instances that will be set if metrics are not available for evaluation. The default is only used if the current instance count is lower than the default.", + required=True, + ) + capacity.maximum = AAZStrArg( + options=["maximum"], + help="the maximum number of instances for the resource. The actual maximum number of instances is limited by the cores that are available in the subscription.", + required=True, + ) + capacity.minimum = AAZStrArg( + options=["minimum"], + help="the minimum number of instances for the resource.", + required=True, + ) + + fixed_date = cls._args_schema.profiles.Element.fixed_date + fixed_date.end = AAZDateTimeArg( + options=["end"], + help="the end time for the profile in ISO 8601 format.", + required=True, + ) + fixed_date.start = AAZDateTimeArg( + options=["start"], + help="the start time for the profile in ISO 8601 format.", + required=True, + ) + fixed_date.time_zone = AAZStrArg( + options=["time-zone"], + help="the timezone of the start and end times for the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands Standard Time", + ) + + recurrence = cls._args_schema.profiles.Element.recurrence + recurrence.frequency = AAZStrArg( + options=["frequency"], + help="the recurrence frequency. How often the schedule profile should take effect. This value must be Week, meaning each week will have the same set of profiles. For example, to set a daily schedule, set **schedule** to every day of the week. The frequency property specifies that the schedule is repeated weekly.", + required=True, + enum={"Day": "Day", "Hour": "Hour", "Minute": "Minute", "Month": "Month", "None": "None", "Second": "Second", "Week": "Week", "Year": "Year"}, + ) + recurrence.schedule = AAZObjectArg( + options=["schedule"], + help="the scheduling constraints for when the profile begins.", + required=True, + ) + + schedule = cls._args_schema.profiles.Element.recurrence.schedule + schedule.days = AAZListArg( + options=["days"], + help="the collection of days that the profile takes effect on. Possible values are Sunday through Saturday.", + required=True, + ) + schedule.hours = AAZListArg( + options=["hours"], + help="A collection of hours that the profile takes effect on. Values supported are 0 to 23 on the 24-hour clock (AM/PM times are not supported).", + required=True, + ) + schedule.minutes = AAZListArg( + options=["minutes"], + help="A collection of minutes at which the profile takes effect at.", + required=True, + ) + schedule.time_zone = AAZStrArg( + options=["time-zone"], + help="the timezone for the hours of the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands Standard Time", + required=True, + ) + + days = cls._args_schema.profiles.Element.recurrence.schedule.days + days.Element = AAZStrArg() + + hours = cls._args_schema.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntArg() + + minutes = cls._args_schema.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntArg() + + rules = cls._args_schema.profiles.Element.rules + rules.Element = AAZObjectArg() + + _element = cls._args_schema.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectArg( + options=["metric-trigger"], + help="the trigger that results in a scaling action.", + required=True, + ) + _element.scale_action = AAZObjectArg( + options=["scale-action"], + help="the parameters for the scaling action.", + required=True, + ) + + metric_trigger = cls._args_schema.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListArg( + options=["dimensions"], + help="List of dimension conditions. For example: [{\"DimensionName\":\"AppName\",\"Operator\":\"Equals\",\"Values\":[\"App1\"]},{\"DimensionName\":\"Deployment\",\"Operator\":\"Equals\",\"Values\":[\"default\"]}].", + ) + metric_trigger.divide_per_instance = AAZBoolArg( + options=["divide-per-instance"], + help="a value indicating whether metric should divide per instance.", + ) + metric_trigger.metric_name = AAZStrArg( + options=["metric-name"], + help="the name of the metric that defines what the rule monitors.", + required=True, + ) + metric_trigger.metric_namespace = AAZStrArg( + options=["metric-namespace"], + help="the namespace of the metric that defines what the rule monitors.", + ) + metric_trigger.metric_resource_location = AAZStrArg( + options=["metric-resource-location"], + help="the location of the resource the rule monitors.", + ) + metric_trigger.metric_resource_uri = AAZStrArg( + options=["metric-resource-uri"], + help="the resource identifier of the resource the rule monitors.", + required=True, + ) + metric_trigger.operator = AAZStrArg( + options=["operator"], + help="the operator that is used to compare the metric data and the threshold.", + required=True, + enum={"Equals": "Equals", "GreaterThan": "GreaterThan", "GreaterThanOrEqual": "GreaterThanOrEqual", "LessThan": "LessThan", "LessThanOrEqual": "LessThanOrEqual", "NotEquals": "NotEquals"}, + ) + metric_trigger.statistic = AAZStrArg( + options=["statistic"], + help="the metric statistic type. How the metrics from multiple instances are combined.", + required=True, + enum={"Average": "Average", "Count": "Count", "Max": "Max", "Min": "Min", "Sum": "Sum"}, + ) + metric_trigger.threshold = AAZFloatArg( + options=["threshold"], + help="the threshold of the metric that triggers the scale action.", + required=True, + ) + metric_trigger.time_aggregation = AAZStrArg( + options=["time-aggregation"], + help="time aggregation type. How the data that is collected should be combined over time. The default value is Average.", + required=True, + enum={"Average": "Average", "Count": "Count", "Last": "Last", "Maximum": "Maximum", "Minimum": "Minimum", "Total": "Total"}, + ) + metric_trigger.time_grain = AAZDurationArg( + options=["time-grain"], + help="the granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.", + required=True, + ) + metric_trigger.time_window = AAZDurationArg( + options=["time-window"], + help="the range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.", + required=True, + ) + + dimensions = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectArg() + + _element = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrArg( + options=["dimension-name"], + help="Name of the dimension.", + required=True, + ) + _element.operator = AAZStrArg( + options=["operator"], + help="the dimension operator. Only 'Equals' and 'NotEquals' are supported. 'Equals' being equal to any of the values. 'NotEquals' being not equal to all of the values", + required=True, + enum={"Equals": "Equals", "NotEquals": "NotEquals"}, + ) + _element.values = AAZListArg( + options=["values"], + help="list of dimension values. For example: [\"App1\",\"App2\"].", + required=True, + ) + + values = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrArg() + + scale_action = cls._args_schema.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZDurationArg( + options=["cooldown"], + help="the amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.", + required=True, + ) + scale_action.direction = AAZStrArg( + options=["direction"], + help="the scale direction. Whether the scaling action increases or decreases the number of instances.", + required=True, + enum={"Decrease": "Decrease", "Increase": "Increase", "None": "None"}, + ) + scale_action.type = AAZStrArg( + options=["type"], + help="the type of action that should occur when the scale rule fires.", + required=True, + enum={"ChangeCount": "ChangeCount", "ExactCount": "ExactCount", "PercentChangeCount": "PercentChangeCount", "ServiceAllowedNextValue": "ServiceAllowedNextValue"}, + ) + scale_action.value = AAZStrArg( + options=["value"], + help="the number of instances that are involved in the scaling action. This value must be 1 or greater. The default value is 1.", + default="1", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AutoscaleSettingsCreateOrUpdate(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 AutoscaleSettingsCreateOrUpdate(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, 201]: + return self.on_200_201(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}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "autoscaleSettingName", self.ctx.args.autoscale_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( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("enabled", AAZBoolType, ".enabled") + properties.set_prop("name", AAZStrType, ".autoscale_name") + properties.set_prop("notifications", AAZListType, ".notifications") + properties.set_prop("predictiveAutoscalePolicy", AAZObjectType) + properties.set_prop("profiles", AAZListType, ".profiles", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("targetResourceLocation", AAZStrType, ".target_resource_location") + properties.set_prop("targetResourceUri", AAZStrType, ".target_resource_uri") + + notifications = _builder.get(".properties.notifications") + if notifications is not None: + notifications.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.notifications[]") + if _elements is not None: + _elements.set_prop("email", AAZObjectType, ".email") + _elements.set_prop("operation", AAZStrType, ".operation", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("webhooks", AAZListType, ".webhooks") + + email = _builder.get(".properties.notifications[].email") + if email is not None: + email.set_prop("customEmails", AAZListType, ".custom_emails") + email.set_prop("sendToSubscriptionAdministrator", AAZBoolType, ".send_to_subscription_administrator") + email.set_prop("sendToSubscriptionCoAdministrators", AAZBoolType, ".send_to_subscription_co_administrators") + + custom_emails = _builder.get(".properties.notifications[].email.customEmails") + if custom_emails is not None: + custom_emails.set_elements(AAZStrType, ".") + + webhooks = _builder.get(".properties.notifications[].webhooks") + if webhooks is not None: + webhooks.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.notifications[].webhooks[]") + if _elements is not None: + _elements.set_prop("properties", AAZDictType, ".properties") + _elements.set_prop("serviceUri", AAZStrType, ".service_uri") + + properties = _builder.get(".properties.notifications[].webhooks[].properties") + if properties is not None: + properties.set_elements(AAZStrType, ".") + + predictive_autoscale_policy = _builder.get(".properties.predictiveAutoscalePolicy") + if predictive_autoscale_policy is not None: + predictive_autoscale_policy.set_prop("scaleLookAheadTime", AAZStrType, ".scale_look_ahead_time") + predictive_autoscale_policy.set_prop("scaleMode", AAZStrType, ".scale_mode", typ_kwargs={"flags": {"required": True}}) + + profiles = _builder.get(".properties.profiles") + if profiles is not None: + profiles.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[]") + if _elements is not None: + _elements.set_prop("capacity", AAZObjectType, ".capacity", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("fixedDate", AAZObjectType, ".fixed_date") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("recurrence", AAZObjectType, ".recurrence") + _elements.set_prop("rules", AAZListType, ".rules", typ_kwargs={"flags": {"required": True}}) + + capacity = _builder.get(".properties.profiles[].capacity") + if capacity is not None: + capacity.set_prop("default", AAZStrType, ".default", typ_kwargs={"flags": {"required": True}}) + capacity.set_prop("maximum", AAZStrType, ".maximum", typ_kwargs={"flags": {"required": True}}) + capacity.set_prop("minimum", AAZStrType, ".minimum", typ_kwargs={"flags": {"required": True}}) + + fixed_date = _builder.get(".properties.profiles[].fixedDate") + if fixed_date is not None: + fixed_date.set_prop("end", AAZStrType, ".end", typ_kwargs={"flags": {"required": True}}) + fixed_date.set_prop("start", AAZStrType, ".start", typ_kwargs={"flags": {"required": True}}) + fixed_date.set_prop("timeZone", AAZStrType, ".time_zone") + + recurrence = _builder.get(".properties.profiles[].recurrence") + if recurrence is not None: + recurrence.set_prop("frequency", AAZStrType, ".frequency", typ_kwargs={"flags": {"required": True}}) + recurrence.set_prop("schedule", AAZObjectType, ".schedule", typ_kwargs={"flags": {"required": True}}) + + schedule = _builder.get(".properties.profiles[].recurrence.schedule") + if schedule is not None: + schedule.set_prop("days", AAZListType, ".days", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("hours", AAZListType, ".hours", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("minutes", AAZListType, ".minutes", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("timeZone", AAZStrType, ".time_zone", typ_kwargs={"flags": {"required": True}}) + + days = _builder.get(".properties.profiles[].recurrence.schedule.days") + if days is not None: + days.set_elements(AAZStrType, ".") + + hours = _builder.get(".properties.profiles[].recurrence.schedule.hours") + if hours is not None: + hours.set_elements(AAZIntType, ".") + + minutes = _builder.get(".properties.profiles[].recurrence.schedule.minutes") + if minutes is not None: + minutes.set_elements(AAZIntType, ".") + + rules = _builder.get(".properties.profiles[].rules") + if rules is not None: + rules.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[].rules[]") + if _elements is not None: + _elements.set_prop("metricTrigger", AAZObjectType, ".metric_trigger", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("scaleAction", AAZObjectType, ".scale_action", typ_kwargs={"flags": {"required": True}}) + + metric_trigger = _builder.get(".properties.profiles[].rules[].metricTrigger") + if metric_trigger is not None: + metric_trigger.set_prop("dimensions", AAZListType, ".dimensions") + metric_trigger.set_prop("dividePerInstance", AAZBoolType, ".divide_per_instance") + metric_trigger.set_prop("metricName", AAZStrType, ".metric_name", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("metricNamespace", AAZStrType, ".metric_namespace") + metric_trigger.set_prop("metricResourceLocation", AAZStrType, ".metric_resource_location") + metric_trigger.set_prop("metricResourceUri", AAZStrType, ".metric_resource_uri", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("statistic", AAZStrType, ".statistic", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("threshold", AAZFloatType, ".threshold", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeAggregation", AAZStrType, ".time_aggregation", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeGrain", AAZStrType, ".time_grain", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeWindow", AAZStrType, ".time_window", typ_kwargs={"flags": {"required": True}}) + + dimensions = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions") + if dimensions is not None: + dimensions.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions[]") + if _elements is not None: + _elements.set_prop("DimensionName", AAZStrType, ".dimension_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("Operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("Values", AAZListType, ".values", typ_kwargs={"flags": {"required": True}}) + + values = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions[].Values") + if values is not None: + values.set_elements(AAZStrType, ".") + + scale_action = _builder.get(".properties.profiles[].rules[].scaleAction") + if scale_action is not None: + scale_action.set_prop("cooldown", AAZStrType, ".cooldown", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("direction", AAZStrType, ".direction", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("type", AAZStrType, ".type", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("value", AAZStrType, ".value") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200_201.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _CreateHelper._build_schema_system_data_read(_schema_on_200_201.system_data) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.enabled = AAZBoolType() + properties.name = AAZStrType() + properties.notifications = AAZListType() + properties.predictive_autoscale_policy = AAZObjectType( + serialized_name="predictiveAutoscalePolicy", + ) + properties.profiles = AAZListType( + flags={"required": True}, + ) + properties.target_resource_location = AAZStrType( + serialized_name="targetResourceLocation", + ) + properties.target_resource_uri = AAZStrType( + serialized_name="targetResourceUri", + ) + + notifications = cls._schema_on_200_201.properties.notifications + notifications.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.notifications.Element + _element.email = AAZObjectType() + _element.operation = AAZStrType( + flags={"required": True}, + ) + _element.webhooks = AAZListType() + + email = cls._schema_on_200_201.properties.notifications.Element.email + email.custom_emails = AAZListType( + serialized_name="customEmails", + ) + email.send_to_subscription_administrator = AAZBoolType( + serialized_name="sendToSubscriptionAdministrator", + ) + email.send_to_subscription_co_administrators = AAZBoolType( + serialized_name="sendToSubscriptionCoAdministrators", + ) + + custom_emails = cls._schema_on_200_201.properties.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrType() + + webhooks = cls._schema_on_200_201.properties.notifications.Element.webhooks + webhooks.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.notifications.Element.webhooks.Element + _element.properties = AAZDictType() + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + + properties = cls._schema_on_200_201.properties.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrType() + + predictive_autoscale_policy = cls._schema_on_200_201.properties.predictive_autoscale_policy + predictive_autoscale_policy.scale_look_ahead_time = AAZStrType( + serialized_name="scaleLookAheadTime", + ) + predictive_autoscale_policy.scale_mode = AAZStrType( + serialized_name="scaleMode", + flags={"required": True}, + ) + + profiles = cls._schema_on_200_201.properties.profiles + profiles.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.profiles.Element + _element.capacity = AAZObjectType( + flags={"required": True}, + ) + _element.fixed_date = AAZObjectType( + serialized_name="fixedDate", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.recurrence = AAZObjectType() + _element.rules = AAZListType( + flags={"required": True}, + ) + + capacity = cls._schema_on_200_201.properties.profiles.Element.capacity + capacity.default = AAZStrType( + flags={"required": True}, + ) + capacity.maximum = AAZStrType( + flags={"required": True}, + ) + capacity.minimum = AAZStrType( + flags={"required": True}, + ) + + fixed_date = cls._schema_on_200_201.properties.profiles.Element.fixed_date + fixed_date.end = AAZStrType( + flags={"required": True}, + ) + fixed_date.start = AAZStrType( + flags={"required": True}, + ) + fixed_date.time_zone = AAZStrType( + serialized_name="timeZone", + ) + + recurrence = cls._schema_on_200_201.properties.profiles.Element.recurrence + recurrence.frequency = AAZStrType( + flags={"required": True}, + ) + recurrence.schedule = AAZObjectType( + flags={"required": True}, + ) + + schedule = cls._schema_on_200_201.properties.profiles.Element.recurrence.schedule + schedule.days = AAZListType( + flags={"required": True}, + ) + schedule.hours = AAZListType( + flags={"required": True}, + ) + schedule.minutes = AAZListType( + flags={"required": True}, + ) + schedule.time_zone = AAZStrType( + serialized_name="timeZone", + flags={"required": True}, + ) + + days = cls._schema_on_200_201.properties.profiles.Element.recurrence.schedule.days + days.Element = AAZStrType() + + hours = cls._schema_on_200_201.properties.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntType() + + minutes = cls._schema_on_200_201.properties.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntType() + + rules = cls._schema_on_200_201.properties.profiles.Element.rules + rules.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectType( + serialized_name="metricTrigger", + flags={"required": True}, + ) + _element.scale_action = AAZObjectType( + serialized_name="scaleAction", + flags={"required": True}, + ) + + metric_trigger = cls._schema_on_200_201.properties.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListType() + metric_trigger.divide_per_instance = AAZBoolType( + serialized_name="dividePerInstance", + ) + metric_trigger.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + metric_trigger.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + metric_trigger.metric_resource_location = AAZStrType( + serialized_name="metricResourceLocation", + ) + metric_trigger.metric_resource_uri = AAZStrType( + serialized_name="metricResourceUri", + flags={"required": True}, + ) + metric_trigger.operator = AAZStrType( + flags={"required": True}, + ) + metric_trigger.statistic = AAZStrType( + flags={"required": True}, + ) + metric_trigger.threshold = AAZFloatType( + flags={"required": True}, + ) + metric_trigger.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + metric_trigger.time_grain = AAZStrType( + serialized_name="timeGrain", + flags={"required": True}, + ) + metric_trigger.time_window = AAZStrType( + serialized_name="timeWindow", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200_201.properties.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrType( + serialized_name="DimensionName", + flags={"required": True}, + ) + _element.operator = AAZStrType( + serialized_name="Operator", + flags={"required": True}, + ) + _element.values = AAZListType( + serialized_name="Values", + flags={"required": True}, + ) + + values = cls._schema_on_200_201.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrType() + + scale_action = cls._schema_on_200_201.properties.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZStrType( + flags={"required": True}, + ) + scale_action.direction = AAZStrType( + flags={"required": True}, + ) + scale_action.type = AAZStrType( + flags={"required": True}, + ) + scale_action.value = AAZStrType() + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_delete.py new file mode 100644 index 00000000000..36d86ffc8fc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_delete.py @@ -0,0 +1,135 @@ +# -------------------------------------------------------------------------------------------- +# 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 delete", +) +class Delete(AAZCommand): + """Delete an autoscale setting + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings/{}", "2022-10-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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_name = AAZStrArg( + options=["-n", "--name", "--autoscale-name"], + help="The autoscale setting name.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AutoscaleSettingsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class AutoscaleSettingsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(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}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "autoscaleSettingName", self.ctx.args.autoscale_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( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_list.py new file mode 100644 index 00000000000..94a8c10b597 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_list.py @@ -0,0 +1,452 @@ +# -------------------------------------------------------------------------------------------- +# 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 list", +) +class List(AAZCommand): + """Lists the autoscale settings for a resource group + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings", "2022-10-01"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AutoscaleSettingsListByResourceGroup(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class AutoscaleSettingsListByResourceGroup(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", + **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( + "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( + "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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ListHelper._build_schema_system_data_read(_element.system_data) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.enabled = AAZBoolType() + properties.name = AAZStrType() + properties.notifications = AAZListType() + properties.predictive_autoscale_policy = AAZObjectType( + serialized_name="predictiveAutoscalePolicy", + ) + properties.profiles = AAZListType( + flags={"required": True}, + ) + properties.target_resource_location = AAZStrType( + serialized_name="targetResourceLocation", + ) + properties.target_resource_uri = AAZStrType( + serialized_name="targetResourceUri", + ) + + notifications = cls._schema_on_200.value.Element.properties.notifications + notifications.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.notifications.Element + _element.email = AAZObjectType() + _element.operation = AAZStrType( + flags={"required": True}, + ) + _element.webhooks = AAZListType() + + email = cls._schema_on_200.value.Element.properties.notifications.Element.email + email.custom_emails = AAZListType( + serialized_name="customEmails", + ) + email.send_to_subscription_administrator = AAZBoolType( + serialized_name="sendToSubscriptionAdministrator", + ) + email.send_to_subscription_co_administrators = AAZBoolType( + serialized_name="sendToSubscriptionCoAdministrators", + ) + + custom_emails = cls._schema_on_200.value.Element.properties.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrType() + + webhooks = cls._schema_on_200.value.Element.properties.notifications.Element.webhooks + webhooks.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.notifications.Element.webhooks.Element + _element.properties = AAZDictType() + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + + properties = cls._schema_on_200.value.Element.properties.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrType() + + predictive_autoscale_policy = cls._schema_on_200.value.Element.properties.predictive_autoscale_policy + predictive_autoscale_policy.scale_look_ahead_time = AAZStrType( + serialized_name="scaleLookAheadTime", + ) + predictive_autoscale_policy.scale_mode = AAZStrType( + serialized_name="scaleMode", + flags={"required": True}, + ) + + profiles = cls._schema_on_200.value.Element.properties.profiles + profiles.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.profiles.Element + _element.capacity = AAZObjectType( + flags={"required": True}, + ) + _element.fixed_date = AAZObjectType( + serialized_name="fixedDate", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.recurrence = AAZObjectType() + _element.rules = AAZListType( + flags={"required": True}, + ) + + capacity = cls._schema_on_200.value.Element.properties.profiles.Element.capacity + capacity.default = AAZStrType( + flags={"required": True}, + ) + capacity.maximum = AAZStrType( + flags={"required": True}, + ) + capacity.minimum = AAZStrType( + flags={"required": True}, + ) + + fixed_date = cls._schema_on_200.value.Element.properties.profiles.Element.fixed_date + fixed_date.end = AAZStrType( + flags={"required": True}, + ) + fixed_date.start = AAZStrType( + flags={"required": True}, + ) + fixed_date.time_zone = AAZStrType( + serialized_name="timeZone", + ) + + recurrence = cls._schema_on_200.value.Element.properties.profiles.Element.recurrence + recurrence.frequency = AAZStrType( + flags={"required": True}, + ) + recurrence.schedule = AAZObjectType( + flags={"required": True}, + ) + + schedule = cls._schema_on_200.value.Element.properties.profiles.Element.recurrence.schedule + schedule.days = AAZListType( + flags={"required": True}, + ) + schedule.hours = AAZListType( + flags={"required": True}, + ) + schedule.minutes = AAZListType( + flags={"required": True}, + ) + schedule.time_zone = AAZStrType( + serialized_name="timeZone", + flags={"required": True}, + ) + + days = cls._schema_on_200.value.Element.properties.profiles.Element.recurrence.schedule.days + days.Element = AAZStrType() + + hours = cls._schema_on_200.value.Element.properties.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntType() + + minutes = cls._schema_on_200.value.Element.properties.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntType() + + rules = cls._schema_on_200.value.Element.properties.profiles.Element.rules + rules.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectType( + serialized_name="metricTrigger", + flags={"required": True}, + ) + _element.scale_action = AAZObjectType( + serialized_name="scaleAction", + flags={"required": True}, + ) + + metric_trigger = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListType() + metric_trigger.divide_per_instance = AAZBoolType( + serialized_name="dividePerInstance", + ) + metric_trigger.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + metric_trigger.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + metric_trigger.metric_resource_location = AAZStrType( + serialized_name="metricResourceLocation", + ) + metric_trigger.metric_resource_uri = AAZStrType( + serialized_name="metricResourceUri", + flags={"required": True}, + ) + metric_trigger.operator = AAZStrType( + flags={"required": True}, + ) + metric_trigger.statistic = AAZStrType( + flags={"required": True}, + ) + metric_trigger.threshold = AAZFloatType( + flags={"required": True}, + ) + metric_trigger.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + metric_trigger.time_grain = AAZStrType( + serialized_name="timeGrain", + flags={"required": True}, + ) + metric_trigger.time_window = AAZStrType( + serialized_name="timeWindow", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrType( + serialized_name="DimensionName", + flags={"required": True}, + ) + _element.operator = AAZStrType( + serialized_name="Operator", + flags={"required": True}, + ) + _element.values = AAZListType( + serialized_name="Values", + flags={"required": True}, + ) + + values = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrType() + + scale_action = cls._schema_on_200.value.Element.properties.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZStrType( + flags={"required": True}, + ) + scale_action.direction = AAZStrType( + flags={"required": True}, + ) + scale_action.type = AAZStrType( + flags={"required": True}, + ) + scale_action.value = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show.py new file mode 100644 index 00000000000..13cd124dd29 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show.py @@ -0,0 +1,452 @@ +# -------------------------------------------------------------------------------------------- +# 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", +) +class Show(AAZCommand): + """Get an autoscale setting + + :example: Show autoscale setting details. + az monitor autoscale show --name MyAutoscaleSettings --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings/{}", "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_name = AAZStrArg( + options=["-n", "--name", "--autoscale-name"], + help="The autoscale setting name.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AutoscaleSettingsGet(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 AutoscaleSettingsGet(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}", + **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_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( + "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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _ShowHelper._build_schema_system_data_read(_schema_on_200.system_data) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.enabled = AAZBoolType() + properties.name = AAZStrType() + properties.notifications = AAZListType() + properties.predictive_autoscale_policy = AAZObjectType( + serialized_name="predictiveAutoscalePolicy", + ) + properties.profiles = AAZListType( + flags={"required": True}, + ) + properties.target_resource_location = AAZStrType( + serialized_name="targetResourceLocation", + ) + properties.target_resource_uri = AAZStrType( + serialized_name="targetResourceUri", + ) + + notifications = cls._schema_on_200.properties.notifications + notifications.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.notifications.Element + _element.email = AAZObjectType() + _element.operation = AAZStrType( + flags={"required": True}, + ) + _element.webhooks = AAZListType() + + email = cls._schema_on_200.properties.notifications.Element.email + email.custom_emails = AAZListType( + serialized_name="customEmails", + ) + email.send_to_subscription_administrator = AAZBoolType( + serialized_name="sendToSubscriptionAdministrator", + ) + email.send_to_subscription_co_administrators = AAZBoolType( + serialized_name="sendToSubscriptionCoAdministrators", + ) + + custom_emails = cls._schema_on_200.properties.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrType() + + webhooks = cls._schema_on_200.properties.notifications.Element.webhooks + webhooks.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.notifications.Element.webhooks.Element + _element.properties = AAZDictType() + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + + properties = cls._schema_on_200.properties.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrType() + + predictive_autoscale_policy = cls._schema_on_200.properties.predictive_autoscale_policy + predictive_autoscale_policy.scale_look_ahead_time = AAZStrType( + serialized_name="scaleLookAheadTime", + ) + predictive_autoscale_policy.scale_mode = AAZStrType( + serialized_name="scaleMode", + flags={"required": True}, + ) + + profiles = cls._schema_on_200.properties.profiles + profiles.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.profiles.Element + _element.capacity = AAZObjectType( + flags={"required": True}, + ) + _element.fixed_date = AAZObjectType( + serialized_name="fixedDate", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.recurrence = AAZObjectType() + _element.rules = AAZListType( + flags={"required": True}, + ) + + capacity = cls._schema_on_200.properties.profiles.Element.capacity + capacity.default = AAZStrType( + flags={"required": True}, + ) + capacity.maximum = AAZStrType( + flags={"required": True}, + ) + capacity.minimum = AAZStrType( + flags={"required": True}, + ) + + fixed_date = cls._schema_on_200.properties.profiles.Element.fixed_date + fixed_date.end = AAZStrType( + flags={"required": True}, + ) + fixed_date.start = AAZStrType( + flags={"required": True}, + ) + fixed_date.time_zone = AAZStrType( + serialized_name="timeZone", + ) + + recurrence = cls._schema_on_200.properties.profiles.Element.recurrence + recurrence.frequency = AAZStrType( + flags={"required": True}, + ) + recurrence.schedule = AAZObjectType( + flags={"required": True}, + ) + + schedule = cls._schema_on_200.properties.profiles.Element.recurrence.schedule + schedule.days = AAZListType( + flags={"required": True}, + ) + schedule.hours = AAZListType( + flags={"required": True}, + ) + schedule.minutes = AAZListType( + flags={"required": True}, + ) + schedule.time_zone = AAZStrType( + serialized_name="timeZone", + flags={"required": True}, + ) + + days = cls._schema_on_200.properties.profiles.Element.recurrence.schedule.days + days.Element = AAZStrType() + + hours = cls._schema_on_200.properties.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntType() + + minutes = cls._schema_on_200.properties.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntType() + + rules = cls._schema_on_200.properties.profiles.Element.rules + rules.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectType( + serialized_name="metricTrigger", + flags={"required": True}, + ) + _element.scale_action = AAZObjectType( + serialized_name="scaleAction", + flags={"required": True}, + ) + + metric_trigger = cls._schema_on_200.properties.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListType() + metric_trigger.divide_per_instance = AAZBoolType( + serialized_name="dividePerInstance", + ) + metric_trigger.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + metric_trigger.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + metric_trigger.metric_resource_location = AAZStrType( + serialized_name="metricResourceLocation", + ) + metric_trigger.metric_resource_uri = AAZStrType( + serialized_name="metricResourceUri", + flags={"required": True}, + ) + metric_trigger.operator = AAZStrType( + flags={"required": True}, + ) + metric_trigger.statistic = AAZStrType( + flags={"required": True}, + ) + metric_trigger.threshold = AAZFloatType( + flags={"required": True}, + ) + metric_trigger.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + metric_trigger.time_grain = AAZStrType( + serialized_name="timeGrain", + flags={"required": True}, + ) + metric_trigger.time_window = AAZStrType( + serialized_name="timeWindow", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.properties.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrType( + serialized_name="DimensionName", + flags={"required": True}, + ) + _element.operator = AAZStrType( + serialized_name="Operator", + flags={"required": True}, + ) + _element.values = AAZListType( + serialized_name="Values", + flags={"required": True}, + ) + + values = cls._schema_on_200.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrType() + + scale_action = cls._schema_on_200.properties.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZStrType( + flags={"required": True}, + ) + scale_action.direction = AAZStrType( + flags={"required": True}, + ) + scale_action.type = AAZStrType( + flags={"required": True}, + ) + scale_action.value = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show_predictive_metric.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show_predictive_metric.py new file mode 100644 index 00000000000..c33c9bdd235 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_show_predictive_metric.py @@ -0,0 +1,227 @@ +# -------------------------------------------------------------------------------------------- +# 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, + id_part="name", + ) + _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 + + +class _ShowPredictiveMetricHelper: + """Helper class for ShowPredictiveMetric""" + + +__all__ = ["ShowPredictiveMetric"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_update.py new file mode 100644 index 00000000000..cc7580abf6e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/autoscale/_update.py @@ -0,0 +1,1108 @@ +# -------------------------------------------------------------------------------------------- +# 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 update", +) +class Update(AAZCommand): + """Update an autoscale setting. + + For more information on autoscaling, visit: https://learn.microsoft.com/azure/monitoring-and-diagnostics/monitoring-understanding-autoscale-settings. + + :example: Update autoscale settings to use a fixed 3 instances by default. + az monitor autoscale update -g myrg -n autoscale-name --count 3 + + :example: Update autoscale settings to remove an email notification. + az monitor autoscale update -g myrg -n autoscale-name --remove-action email bob@contoso.com + + :example: Update autoscale settings. + az monitor autoscale update --count 3 --email-administrator true --enabled true --max-count 5 --min-count 2 --name MyAutoscaleSettings --resource-group MyResourceGroup --tags key[=value] + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/autoscalesettings/{}", "2022-10-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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_name = AAZStrArg( + options=["-n", "--name", "--autoscale-name"], + help="The autoscale setting name.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + help="the enabled flag. Specifies whether automatic scaling is enabled for the resource. The default value is 'false'.", + nullable=True, + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater in length than 128 characters and a value no greater in length than 256 characters.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Predictive Policy" + + _args_schema = cls._args_schema + _args_schema.scale_look_ahead_time = AAZDurationArg( + options=["--scale-look-ahead-time"], + arg_group="Predictive Policy", + 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).", + nullable=True, + ) + _args_schema.scale_mode = AAZStrArg( + options=["--scale-mode"], + arg_group="Predictive Policy", + help="the predictive autoscale mode", + enum={"Disabled": "Disabled", "Enabled": "Enabled", "ForecastOnly": "ForecastOnly"}, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.notifications = AAZListArg( + options=["--notifications"], + arg_group="Properties", + help="the collection of notifications.", + nullable=True, + ) + _args_schema.profiles = AAZListArg( + options=["--profiles"], + arg_group="Properties", + help="the collection of automatic scaling profiles that specify different scaling parameters for different time periods. A maximum of 20 profiles can be specified.", + ) + _args_schema.target_resource_location = AAZStrArg( + options=["--target-resource-location"], + arg_group="Properties", + help="the location of the resource that the autoscale setting should be added to.", + nullable=True, + ) + _args_schema.target_resource_uri = AAZStrArg( + options=["--target-resource-uri"], + arg_group="Properties", + help="the resource identifier of the resource that the autoscale setting should be added to.", + nullable=True, + ) + + notifications = cls._args_schema.notifications + notifications.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.notifications.Element + _element.email = AAZObjectArg( + options=["email"], + help="the email notification.", + nullable=True, + ) + _element.operation = AAZStrArg( + options=["operation"], + help="the operation associated with the notification and its value must be \"scale\"", + enum={"Scale": "Scale"}, + ) + _element.webhooks = AAZListArg( + options=["webhooks"], + help="the collection of webhook notifications.", + nullable=True, + ) + + email = cls._args_schema.notifications.Element.email + email.custom_emails = AAZListArg( + options=["custom-emails"], + help="the custom e-mails list. This value can be null or empty, in which case this attribute will be ignored.", + nullable=True, + ) + email.send_to_subscription_administrator = AAZBoolArg( + options=["send-to-subscription-administrator"], + help="a value indicating whether to send email to subscription administrator.", + nullable=True, + ) + email.send_to_subscription_co_administrators = AAZBoolArg( + options=["send-to-subscription-co-administrators"], + help="a value indicating whether to send email to subscription co-administrators.", + nullable=True, + ) + + custom_emails = cls._args_schema.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrArg( + nullable=True, + ) + + webhooks = cls._args_schema.notifications.Element.webhooks + webhooks.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.notifications.Element.webhooks.Element + _element.properties = AAZDictArg( + options=["properties"], + help="a property bag of settings. This value can be empty.", + nullable=True, + ) + _element.service_uri = AAZStrArg( + options=["service-uri"], + help="the service address to receive the notification.", + nullable=True, + ) + + properties = cls._args_schema.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrArg( + nullable=True, + ) + + profiles = cls._args_schema.profiles + profiles.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.profiles.Element + _element.capacity = AAZObjectArg( + options=["capacity"], + help="the number of instances that can be used during this profile.", + ) + _element.fixed_date = AAZObjectArg( + options=["fixed-date"], + help="the specific date-time for the profile. This element is not used if the Recurrence element is used.", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="the name of the profile.", + ) + _element.recurrence = AAZObjectArg( + options=["recurrence"], + help="the repeating times at which this profile begins. This element is not used if the FixedDate element is used.", + nullable=True, + ) + _element.rules = AAZListArg( + options=["rules"], + help="the collection of rules that provide the triggers and parameters for the scaling action. A maximum of 10 rules can be specified.", + ) + + capacity = cls._args_schema.profiles.Element.capacity + capacity.default = AAZStrArg( + options=["default"], + help="the number of instances that will be set if metrics are not available for evaluation. The default is only used if the current instance count is lower than the default.", + ) + capacity.maximum = AAZStrArg( + options=["maximum"], + help="the maximum number of instances for the resource. The actual maximum number of instances is limited by the cores that are available in the subscription.", + ) + capacity.minimum = AAZStrArg( + options=["minimum"], + help="the minimum number of instances for the resource.", + ) + + fixed_date = cls._args_schema.profiles.Element.fixed_date + fixed_date.end = AAZDateTimeArg( + options=["end"], + help="the end time for the profile in ISO 8601 format.", + ) + fixed_date.start = AAZDateTimeArg( + options=["start"], + help="the start time for the profile in ISO 8601 format.", + ) + fixed_date.time_zone = AAZStrArg( + options=["time-zone"], + help="the timezone of the start and end times for the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands Standard Time", + nullable=True, + ) + + recurrence = cls._args_schema.profiles.Element.recurrence + recurrence.frequency = AAZStrArg( + options=["frequency"], + help="the recurrence frequency. How often the schedule profile should take effect. This value must be Week, meaning each week will have the same set of profiles. For example, to set a daily schedule, set **schedule** to every day of the week. The frequency property specifies that the schedule is repeated weekly.", + enum={"Day": "Day", "Hour": "Hour", "Minute": "Minute", "Month": "Month", "None": "None", "Second": "Second", "Week": "Week", "Year": "Year"}, + ) + recurrence.schedule = AAZObjectArg( + options=["schedule"], + help="the scheduling constraints for when the profile begins.", + ) + + schedule = cls._args_schema.profiles.Element.recurrence.schedule + schedule.days = AAZListArg( + options=["days"], + help="the collection of days that the profile takes effect on. Possible values are Sunday through Saturday.", + ) + schedule.hours = AAZListArg( + options=["hours"], + help="A collection of hours that the profile takes effect on. Values supported are 0 to 23 on the 24-hour clock (AM/PM times are not supported).", + ) + schedule.minutes = AAZListArg( + options=["minutes"], + help="A collection of minutes at which the profile takes effect at.", + ) + schedule.time_zone = AAZStrArg( + options=["time-zone"], + help="the timezone for the hours of the profile. Some examples of valid time zones are: Dateline Standard Time, UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific Standard Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain Standard Time (Mexico), Mountain Standard Time, Central America Standard Time, Central Standard Time, Central Standard Time (Mexico), Canada Central Standard Time, SA Pacific Standard Time, Eastern Standard Time, US Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, Atlantic Standard Time, Central Brazilian Standard Time, SA Western Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. South America Standard Time, Argentina Standard Time, SA Eastern Standard Time, Greenland Standard Time, Montevideo Standard Time, Bahia Standard Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich Standard Time, W. Europe Standard Time, Central Europe Standard Time, Romance Standard Time, Central European Standard Time, W. Central Africa Standard Time, Namibia Standard Time, Jordan Standard Time, GTB Standard Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, Turkey Standard Time, Israel Standard Time, Kaliningrad Standard Time, Libya Standard Time, Arabic Standard Time, Arab Standard Time, Belarus Standard Time, Russian Standard Time, E. Africa Standard Time, Iran Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia Time Zone 3, Mauritius Standard Time, Georgian Standard Time, Caucasus Standard Time, Afghanistan Standard Time, West Asia Standard Time, Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, Bangladesh Standard Time, N. Central Asia Standard Time, Myanmar Standard Time, SE Asia Standard Time, North Asia Standard Time, China Standard Time, North Asia East Standard Time, Singapore Standard Time, W. Australia Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time, Cen. Australia Standard Time, AUS Central Standard Time, E. Australia Standard Time, AUS Eastern Standard Time, West Pacific Standard Time, Tasmania Standard Time, Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard Time, UTC+12, Fiji Standard Time, Kamchatka Standard Time, Tonga Standard Time, Samoa Standard Time, Line Islands Standard Time", + ) + + days = cls._args_schema.profiles.Element.recurrence.schedule.days + days.Element = AAZStrArg( + nullable=True, + ) + + hours = cls._args_schema.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntArg( + nullable=True, + ) + + minutes = cls._args_schema.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntArg( + nullable=True, + ) + + rules = cls._args_schema.profiles.Element.rules + rules.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectArg( + options=["metric-trigger"], + help="the trigger that results in a scaling action.", + ) + _element.scale_action = AAZObjectArg( + options=["scale-action"], + help="the parameters for the scaling action.", + ) + + metric_trigger = cls._args_schema.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListArg( + options=["dimensions"], + help="List of dimension conditions. For example: [{\"DimensionName\":\"AppName\",\"Operator\":\"Equals\",\"Values\":[\"App1\"]},{\"DimensionName\":\"Deployment\",\"Operator\":\"Equals\",\"Values\":[\"default\"]}].", + nullable=True, + ) + metric_trigger.divide_per_instance = AAZBoolArg( + options=["divide-per-instance"], + help="a value indicating whether metric should divide per instance.", + nullable=True, + ) + metric_trigger.metric_name = AAZStrArg( + options=["metric-name"], + help="the name of the metric that defines what the rule monitors.", + ) + metric_trigger.metric_namespace = AAZStrArg( + options=["metric-namespace"], + help="the namespace of the metric that defines what the rule monitors.", + nullable=True, + ) + metric_trigger.metric_resource_location = AAZStrArg( + options=["metric-resource-location"], + help="the location of the resource the rule monitors.", + nullable=True, + ) + metric_trigger.metric_resource_uri = AAZStrArg( + options=["metric-resource-uri"], + help="the resource identifier of the resource the rule monitors.", + ) + metric_trigger.operator = AAZStrArg( + options=["operator"], + help="the operator that is used to compare the metric data and the threshold.", + enum={"Equals": "Equals", "GreaterThan": "GreaterThan", "GreaterThanOrEqual": "GreaterThanOrEqual", "LessThan": "LessThan", "LessThanOrEqual": "LessThanOrEqual", "NotEquals": "NotEquals"}, + ) + metric_trigger.statistic = AAZStrArg( + options=["statistic"], + help="the metric statistic type. How the metrics from multiple instances are combined.", + enum={"Average": "Average", "Count": "Count", "Max": "Max", "Min": "Min", "Sum": "Sum"}, + ) + metric_trigger.threshold = AAZFloatArg( + options=["threshold"], + help="the threshold of the metric that triggers the scale action.", + ) + metric_trigger.time_aggregation = AAZStrArg( + options=["time-aggregation"], + help="time aggregation type. How the data that is collected should be combined over time. The default value is Average.", + enum={"Average": "Average", "Count": "Count", "Last": "Last", "Maximum": "Maximum", "Minimum": "Minimum", "Total": "Total"}, + ) + metric_trigger.time_grain = AAZDurationArg( + options=["time-grain"], + help="the granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.", + ) + metric_trigger.time_window = AAZDurationArg( + options=["time-window"], + help="the range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.", + ) + + dimensions = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrArg( + options=["dimension-name"], + help="Name of the dimension.", + ) + _element.operator = AAZStrArg( + options=["operator"], + help="the dimension operator. Only 'Equals' and 'NotEquals' are supported. 'Equals' being equal to any of the values. 'NotEquals' being not equal to all of the values", + enum={"Equals": "Equals", "NotEquals": "NotEquals"}, + ) + _element.values = AAZListArg( + options=["values"], + help="list of dimension values. For example: [\"App1\",\"App2\"].", + ) + + values = cls._args_schema.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrArg( + nullable=True, + ) + + scale_action = cls._args_schema.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZDurationArg( + options=["cooldown"], + help="the amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.", + ) + scale_action.direction = AAZStrArg( + options=["direction"], + help="the scale direction. Whether the scaling action increases or decreases the number of instances.", + enum={"Decrease": "Decrease", "Increase": "Increase", "None": "None"}, + ) + scale_action.type = AAZStrArg( + options=["type"], + help="the type of action that should occur when the scale rule fires.", + enum={"ChangeCount": "ChangeCount", "ExactCount": "ExactCount", "PercentChangeCount": "PercentChangeCount", "ServiceAllowedNextValue": "ServiceAllowedNextValue"}, + ) + scale_action.value = AAZStrArg( + options=["value"], + help="the number of instances that are involved in the scaling action. This value must be 1 or greater. The default value is 1.", + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AutoscaleSettingsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.AutoscaleSettingsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class AutoscaleSettingsGet(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}", + **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_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( + "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() + _UpdateHelper._build_schema_autoscale_setting_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class AutoscaleSettingsCreateOrUpdate(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, 201]: + return self.on_200_201(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}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "autoscaleSettingName", self.ctx.args.autoscale_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( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_autoscale_setting_resource_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("enabled", AAZBoolType, ".enabled") + properties.set_prop("name", AAZStrType, ".autoscale_name") + properties.set_prop("notifications", AAZListType, ".notifications") + properties.set_prop("predictiveAutoscalePolicy", AAZObjectType) + properties.set_prop("profiles", AAZListType, ".profiles", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("targetResourceLocation", AAZStrType, ".target_resource_location") + properties.set_prop("targetResourceUri", AAZStrType, ".target_resource_uri") + + notifications = _builder.get(".properties.notifications") + if notifications is not None: + notifications.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.notifications[]") + if _elements is not None: + _elements.set_prop("email", AAZObjectType, ".email") + _elements.set_prop("operation", AAZStrType, ".operation", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("webhooks", AAZListType, ".webhooks") + + email = _builder.get(".properties.notifications[].email") + if email is not None: + email.set_prop("customEmails", AAZListType, ".custom_emails") + email.set_prop("sendToSubscriptionAdministrator", AAZBoolType, ".send_to_subscription_administrator") + email.set_prop("sendToSubscriptionCoAdministrators", AAZBoolType, ".send_to_subscription_co_administrators") + + custom_emails = _builder.get(".properties.notifications[].email.customEmails") + if custom_emails is not None: + custom_emails.set_elements(AAZStrType, ".") + + webhooks = _builder.get(".properties.notifications[].webhooks") + if webhooks is not None: + webhooks.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.notifications[].webhooks[]") + if _elements is not None: + _elements.set_prop("properties", AAZDictType, ".properties") + _elements.set_prop("serviceUri", AAZStrType, ".service_uri") + + properties = _builder.get(".properties.notifications[].webhooks[].properties") + if properties is not None: + properties.set_elements(AAZStrType, ".") + + predictive_autoscale_policy = _builder.get(".properties.predictiveAutoscalePolicy") + if predictive_autoscale_policy is not None: + predictive_autoscale_policy.set_prop("scaleLookAheadTime", AAZStrType, ".scale_look_ahead_time") + predictive_autoscale_policy.set_prop("scaleMode", AAZStrType, ".scale_mode", typ_kwargs={"flags": {"required": True}}) + + profiles = _builder.get(".properties.profiles") + if profiles is not None: + profiles.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[]") + if _elements is not None: + _elements.set_prop("capacity", AAZObjectType, ".capacity", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("fixedDate", AAZObjectType, ".fixed_date") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("recurrence", AAZObjectType, ".recurrence") + _elements.set_prop("rules", AAZListType, ".rules", typ_kwargs={"flags": {"required": True}}) + + capacity = _builder.get(".properties.profiles[].capacity") + if capacity is not None: + capacity.set_prop("default", AAZStrType, ".default", typ_kwargs={"flags": {"required": True}}) + capacity.set_prop("maximum", AAZStrType, ".maximum", typ_kwargs={"flags": {"required": True}}) + capacity.set_prop("minimum", AAZStrType, ".minimum", typ_kwargs={"flags": {"required": True}}) + + fixed_date = _builder.get(".properties.profiles[].fixedDate") + if fixed_date is not None: + fixed_date.set_prop("end", AAZStrType, ".end", typ_kwargs={"flags": {"required": True}}) + fixed_date.set_prop("start", AAZStrType, ".start", typ_kwargs={"flags": {"required": True}}) + fixed_date.set_prop("timeZone", AAZStrType, ".time_zone") + + recurrence = _builder.get(".properties.profiles[].recurrence") + if recurrence is not None: + recurrence.set_prop("frequency", AAZStrType, ".frequency", typ_kwargs={"flags": {"required": True}}) + recurrence.set_prop("schedule", AAZObjectType, ".schedule", typ_kwargs={"flags": {"required": True}}) + + schedule = _builder.get(".properties.profiles[].recurrence.schedule") + if schedule is not None: + schedule.set_prop("days", AAZListType, ".days", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("hours", AAZListType, ".hours", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("minutes", AAZListType, ".minutes", typ_kwargs={"flags": {"required": True}}) + schedule.set_prop("timeZone", AAZStrType, ".time_zone", typ_kwargs={"flags": {"required": True}}) + + days = _builder.get(".properties.profiles[].recurrence.schedule.days") + if days is not None: + days.set_elements(AAZStrType, ".") + + hours = _builder.get(".properties.profiles[].recurrence.schedule.hours") + if hours is not None: + hours.set_elements(AAZIntType, ".") + + minutes = _builder.get(".properties.profiles[].recurrence.schedule.minutes") + if minutes is not None: + minutes.set_elements(AAZIntType, ".") + + rules = _builder.get(".properties.profiles[].rules") + if rules is not None: + rules.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[].rules[]") + if _elements is not None: + _elements.set_prop("metricTrigger", AAZObjectType, ".metric_trigger", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("scaleAction", AAZObjectType, ".scale_action", typ_kwargs={"flags": {"required": True}}) + + metric_trigger = _builder.get(".properties.profiles[].rules[].metricTrigger") + if metric_trigger is not None: + metric_trigger.set_prop("dimensions", AAZListType, ".dimensions") + metric_trigger.set_prop("dividePerInstance", AAZBoolType, ".divide_per_instance") + metric_trigger.set_prop("metricName", AAZStrType, ".metric_name", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("metricNamespace", AAZStrType, ".metric_namespace") + metric_trigger.set_prop("metricResourceLocation", AAZStrType, ".metric_resource_location") + metric_trigger.set_prop("metricResourceUri", AAZStrType, ".metric_resource_uri", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("statistic", AAZStrType, ".statistic", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("threshold", AAZFloatType, ".threshold", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeAggregation", AAZStrType, ".time_aggregation", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeGrain", AAZStrType, ".time_grain", typ_kwargs={"flags": {"required": True}}) + metric_trigger.set_prop("timeWindow", AAZStrType, ".time_window", typ_kwargs={"flags": {"required": True}}) + + dimensions = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions") + if dimensions is not None: + dimensions.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions[]") + if _elements is not None: + _elements.set_prop("DimensionName", AAZStrType, ".dimension_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("Operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("Values", AAZListType, ".values", typ_kwargs={"flags": {"required": True}}) + + values = _builder.get(".properties.profiles[].rules[].metricTrigger.dimensions[].Values") + if values is not None: + values.set_elements(AAZStrType, ".") + + scale_action = _builder.get(".properties.profiles[].rules[].scaleAction") + if scale_action is not None: + scale_action.set_prop("cooldown", AAZStrType, ".cooldown", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("direction", AAZStrType, ".direction", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("type", AAZStrType, ".type", typ_kwargs={"flags": {"required": True}}) + scale_action.set_prop("value", AAZStrType, ".value") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_autoscale_setting_resource_read = None + + @classmethod + def _build_schema_autoscale_setting_resource_read(cls, _schema): + if cls._schema_autoscale_setting_resource_read is not None: + _schema.id = cls._schema_autoscale_setting_resource_read.id + _schema.location = cls._schema_autoscale_setting_resource_read.location + _schema.name = cls._schema_autoscale_setting_resource_read.name + _schema.properties = cls._schema_autoscale_setting_resource_read.properties + _schema.system_data = cls._schema_autoscale_setting_resource_read.system_data + _schema.tags = cls._schema_autoscale_setting_resource_read.tags + _schema.type = cls._schema_autoscale_setting_resource_read.type + return + + cls._schema_autoscale_setting_resource_read = _schema_autoscale_setting_resource_read = AAZObjectType() + + autoscale_setting_resource_read = _schema_autoscale_setting_resource_read + autoscale_setting_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + autoscale_setting_resource_read.location = AAZStrType( + flags={"required": True}, + ) + autoscale_setting_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + autoscale_setting_resource_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + autoscale_setting_resource_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + cls._build_schema_system_data_read(autoscale_setting_resource_read.system_data) + autoscale_setting_resource_read.tags = AAZDictType() + autoscale_setting_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_autoscale_setting_resource_read.properties + properties.enabled = AAZBoolType() + properties.name = AAZStrType() + properties.notifications = AAZListType() + properties.predictive_autoscale_policy = AAZObjectType( + serialized_name="predictiveAutoscalePolicy", + ) + properties.profiles = AAZListType( + flags={"required": True}, + ) + properties.target_resource_location = AAZStrType( + serialized_name="targetResourceLocation", + ) + properties.target_resource_uri = AAZStrType( + serialized_name="targetResourceUri", + ) + + notifications = _schema_autoscale_setting_resource_read.properties.notifications + notifications.Element = AAZObjectType() + + _element = _schema_autoscale_setting_resource_read.properties.notifications.Element + _element.email = AAZObjectType() + _element.operation = AAZStrType( + flags={"required": True}, + ) + _element.webhooks = AAZListType() + + email = _schema_autoscale_setting_resource_read.properties.notifications.Element.email + email.custom_emails = AAZListType( + serialized_name="customEmails", + ) + email.send_to_subscription_administrator = AAZBoolType( + serialized_name="sendToSubscriptionAdministrator", + ) + email.send_to_subscription_co_administrators = AAZBoolType( + serialized_name="sendToSubscriptionCoAdministrators", + ) + + custom_emails = _schema_autoscale_setting_resource_read.properties.notifications.Element.email.custom_emails + custom_emails.Element = AAZStrType() + + webhooks = _schema_autoscale_setting_resource_read.properties.notifications.Element.webhooks + webhooks.Element = AAZObjectType() + + _element = _schema_autoscale_setting_resource_read.properties.notifications.Element.webhooks.Element + _element.properties = AAZDictType() + _element.service_uri = AAZStrType( + serialized_name="serviceUri", + ) + + properties = _schema_autoscale_setting_resource_read.properties.notifications.Element.webhooks.Element.properties + properties.Element = AAZStrType() + + predictive_autoscale_policy = _schema_autoscale_setting_resource_read.properties.predictive_autoscale_policy + predictive_autoscale_policy.scale_look_ahead_time = AAZStrType( + serialized_name="scaleLookAheadTime", + ) + predictive_autoscale_policy.scale_mode = AAZStrType( + serialized_name="scaleMode", + flags={"required": True}, + ) + + profiles = _schema_autoscale_setting_resource_read.properties.profiles + profiles.Element = AAZObjectType() + + _element = _schema_autoscale_setting_resource_read.properties.profiles.Element + _element.capacity = AAZObjectType( + flags={"required": True}, + ) + _element.fixed_date = AAZObjectType( + serialized_name="fixedDate", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.recurrence = AAZObjectType() + _element.rules = AAZListType( + flags={"required": True}, + ) + + capacity = _schema_autoscale_setting_resource_read.properties.profiles.Element.capacity + capacity.default = AAZStrType( + flags={"required": True}, + ) + capacity.maximum = AAZStrType( + flags={"required": True}, + ) + capacity.minimum = AAZStrType( + flags={"required": True}, + ) + + fixed_date = _schema_autoscale_setting_resource_read.properties.profiles.Element.fixed_date + fixed_date.end = AAZStrType( + flags={"required": True}, + ) + fixed_date.start = AAZStrType( + flags={"required": True}, + ) + fixed_date.time_zone = AAZStrType( + serialized_name="timeZone", + ) + + recurrence = _schema_autoscale_setting_resource_read.properties.profiles.Element.recurrence + recurrence.frequency = AAZStrType( + flags={"required": True}, + ) + recurrence.schedule = AAZObjectType( + flags={"required": True}, + ) + + schedule = _schema_autoscale_setting_resource_read.properties.profiles.Element.recurrence.schedule + schedule.days = AAZListType( + flags={"required": True}, + ) + schedule.hours = AAZListType( + flags={"required": True}, + ) + schedule.minutes = AAZListType( + flags={"required": True}, + ) + schedule.time_zone = AAZStrType( + serialized_name="timeZone", + flags={"required": True}, + ) + + days = _schema_autoscale_setting_resource_read.properties.profiles.Element.recurrence.schedule.days + days.Element = AAZStrType() + + hours = _schema_autoscale_setting_resource_read.properties.profiles.Element.recurrence.schedule.hours + hours.Element = AAZIntType() + + minutes = _schema_autoscale_setting_resource_read.properties.profiles.Element.recurrence.schedule.minutes + minutes.Element = AAZIntType() + + rules = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules + rules.Element = AAZObjectType() + + _element = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element + _element.metric_trigger = AAZObjectType( + serialized_name="metricTrigger", + flags={"required": True}, + ) + _element.scale_action = AAZObjectType( + serialized_name="scaleAction", + flags={"required": True}, + ) + + metric_trigger = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element.metric_trigger + metric_trigger.dimensions = AAZListType() + metric_trigger.divide_per_instance = AAZBoolType( + serialized_name="dividePerInstance", + ) + metric_trigger.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + metric_trigger.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + metric_trigger.metric_resource_location = AAZStrType( + serialized_name="metricResourceLocation", + ) + metric_trigger.metric_resource_uri = AAZStrType( + serialized_name="metricResourceUri", + flags={"required": True}, + ) + metric_trigger.operator = AAZStrType( + flags={"required": True}, + ) + metric_trigger.statistic = AAZStrType( + flags={"required": True}, + ) + metric_trigger.threshold = AAZFloatType( + flags={"required": True}, + ) + metric_trigger.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + metric_trigger.time_grain = AAZStrType( + serialized_name="timeGrain", + flags={"required": True}, + ) + metric_trigger.time_window = AAZStrType( + serialized_name="timeWindow", + flags={"required": True}, + ) + + dimensions = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element.metric_trigger.dimensions + dimensions.Element = AAZObjectType() + + _element = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element + _element.dimension_name = AAZStrType( + serialized_name="DimensionName", + flags={"required": True}, + ) + _element.operator = AAZStrType( + serialized_name="Operator", + flags={"required": True}, + ) + _element.values = AAZListType( + serialized_name="Values", + flags={"required": True}, + ) + + values = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element.metric_trigger.dimensions.Element.values + values.Element = AAZStrType() + + scale_action = _schema_autoscale_setting_resource_read.properties.profiles.Element.rules.Element.scale_action + scale_action.cooldown = AAZStrType( + flags={"required": True}, + ) + scale_action.direction = AAZStrType( + flags={"required": True}, + ) + scale_action.type = AAZStrType( + flags={"required": True}, + ) + scale_action.value = AAZStrType() + + tags = _schema_autoscale_setting_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_autoscale_setting_resource_read.id + _schema.location = cls._schema_autoscale_setting_resource_read.location + _schema.name = cls._schema_autoscale_setting_resource_read.name + _schema.properties = cls._schema_autoscale_setting_resource_read.properties + _schema.system_data = cls._schema_autoscale_setting_resource_read.system_data + _schema.tags = cls._schema_autoscale_setting_resource_read.tags + _schema.type = cls._schema_autoscale_setting_resource_read.type + + _schema_system_data_read = None + + @classmethod + def _build_schema_system_data_read(cls, _schema): + if cls._schema_system_data_read is not None: + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + return + + cls._schema_system_data_read = _schema_system_data_read = AAZObjectType( + flags={"read_only": True} + ) + + system_data_read = _schema_system_data_read + system_data_read.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data_read.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data_read.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data_read.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data_read.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data_read.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.created_at = cls._schema_system_data_read.created_at + _schema.created_by = cls._schema_system_data_read.created_by + _schema.created_by_type = cls._schema_system_data_read.created_by_type + _schema.last_modified_at = cls._schema_system_data_read.last_modified_at + _schema.last_modified_by = cls._schema_system_data_read.last_modified_by + _schema.last_modified_by_type = cls._schema_system_data_read.last_modified_by_type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__cmd_group.py new file mode 100644 index 00000000000..7c8dd590eea --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__cmd_group.py @@ -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 dashboard", +) +class __CMDGroup(AAZCommandGroup): + """Manage Dashboard with Grafana resources + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__init__.py new file mode 100644 index 00000000000..2d1a2078686 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_create.py new file mode 100644 index 00000000000..f085841ce6e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_create.py @@ -0,0 +1,271 @@ +# -------------------------------------------------------------------------------------------- +# 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 dashboard create", +) +class Create(AAZCommand): + """Create a Dashboard with Grafana resource. This API is idempotent, so user can either create a new dashboard or update an existing dashboard. + + :example: Create a Dashboard with Grafana + az monitor dashboard create --resource-group myResourceGroup --dashboard-name myDashboard --location westus + """ + + _aaz_info = { + "version": "2025-09-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.dashboard/dashboards/{}", "2025-09-01-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.dashboard_name = AAZStrArg( + options=["-n", "--name", "--dashboard-name"], + help="The name of the Azure Managed Dashboard.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "RequestBodyParameters" + + _args_schema = cls._args_schema + _args_schema.location = AAZResourceLocationArg( + arg_group="RequestBodyParameters", + help="The geo-location where the resource lives", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="RequestBodyParameters", + help="Resource tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.ManagedDashboardsCreate(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 ManagedDashboardsCreate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dashboardName", self.ctx.args.dashboard_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( + "api-version", "2025-09-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200_201.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_delete.py new file mode 100644 index 00000000000..a225108cabb --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_delete.py @@ -0,0 +1,139 @@ +# -------------------------------------------------------------------------------------------- +# 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 dashboard delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a Dashboard with Grafana resource. + """ + + _aaz_info = { + "version": "2025-09-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.dashboard/dashboards/{}", "2025-09-01-preview"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.dashboard_name = AAZStrArg( + options=["-n", "--name", "--dashboard-name"], + help="The name of the Azure Managed Dashboard.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ManagedDashboardsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class ManagedDashboardsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/dashboards/{dashboardName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dashboardName", self.ctx.args.dashboard_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( + "api-version", "2025-09-01-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_list.py new file mode 100644 index 00000000000..85ede7b2543 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_list.py @@ -0,0 +1,213 @@ +# -------------------------------------------------------------------------------------------- +# 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 dashboard list", +) +class List(AAZCommand): + """List all Dashboard with Grafana resources under the specified resource group. + """ + + _aaz_info = { + "version": "2025-09-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.dashboard/dashboards", "2025-09-01-preview"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DashboardsList(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class DashboardsList(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.Dashboard/dashboards", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2025-09-01-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_show.py new file mode 100644 index 00000000000..e46312e28b2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_show.py @@ -0,0 +1,213 @@ +# -------------------------------------------------------------------------------------------- +# 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 dashboard show", +) +class Show(AAZCommand): + """Get the properties of a specific Dashboard with Grafana resource. + """ + + _aaz_info = { + "version": "2025-09-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.dashboard/dashboards/{}", "2025-09-01-preview"], + ] + } + + 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.dashboard_name = AAZStrArg( + options=["-n", "--name", "--dashboard-name"], + help="The name of the Azure Managed Dashboard.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DashboardsGet(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 DashboardsGet(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.Dashboard/dashboards/{dashboardName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dashboardName", self.ctx.args.dashboard_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( + "api-version", "2025-09-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_wait.py new file mode 100644 index 00000000000..ca8e31dc412 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/dashboard/_wait.py @@ -0,0 +1,212 @@ +# -------------------------------------------------------------------------------------------- +# 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 dashboard wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.dashboard/dashboards/{}", "2025-09-01-preview"], + ] + } + + 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.dashboard_name = AAZStrArg( + options=["-n", "--name", "--dashboard-name"], + help="The name of the Azure Managed Dashboard.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[a-zA-Z][a-z0-9A-Z-]{0,28}[a-z0-9A-Z]$", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DashboardsGet(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=False) + return result + + class DashboardsGet(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.Dashboard/dashboards/{dashboardName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dashboardName", self.ctx.args.dashboard_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( + "api-version", "2025-09-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__cmd_group.py new file mode 100644 index 00000000000..46ebe7560f3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__cmd_group.py @@ -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 diagnostic-settings", +) +class __CMDGroup(AAZCommandGroup): + """Manage service diagnostic settings. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_create.py new file mode 100644 index 00000000000..dff43b84760 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_create.py @@ -0,0 +1,446 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings create", +) +class Create(AAZCommand): + """Create diagnostic settings for the specified resource. For more information, visit: https://learn.microsoft.com/rest/api/monitor/diagnosticsettings/createorupdate#metricsettings. + + :example: Create diagnostic settings, retention here only applies when the target is a storage account. + az monitor diagnostic-settings create --resource {ID} -n {name} --storage-account {storageAccount} --logs "[{category:WorkflowRuntime,enabled:true,retention-policy:{enabled:false,days:0}}]" --metrics "[{category:WorkflowRuntime,enabled:true,retention-policy:{enabled:false,days:0}}]" + """ + + _aaz_info = { + "version": "2021-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings/{}", "2021-05-01-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting. Required.", + required=True, + ) + _args_schema.event_hub_rule = AAZStrArg( + options=["--event-hub-rule"], + help="Name or ID of the event hub authorization rule.", + ) + _args_schema.event_hub = AAZStrArg( + options=["--event-hub"], + help="Name or ID an event hub. If none is specified, the default event hub will be selected.", + ) + _args_schema.log_analytics_destination_type = AAZStrArg( + options=["--log-analytics-destination-type"], + help="A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination type constructed as follows: `_`. Possible values are: Dedicated and null (null is default.)", + ) + _args_schema.logs = AAZListArg( + options=["--logs"], + help="JSON encoded list of logs settings. Use '@{file}' to load from a file. For more information, visit: https://learn.microsoft.com/rest/api/monitor/diagnosticsettings/createorupdate#logsettings.", + ) + _args_schema.marketplace_partner_id = AAZStrArg( + options=["--marketplace-partner-id"], + help="The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs.", + ) + _args_schema.metrics = AAZListArg( + options=["--metrics"], + help="The list of metric settings.", + ) + _args_schema.service_bus_rule_id = AAZStrArg( + options=["--service-bus-rule-id"], + help="The service bus rule Id of the diagnostic setting. This is here to maintain backwards compatibility.", + ) + _args_schema.storage_account = AAZStrArg( + options=["--storage-account"], + help="Name or ID of the storage account to send diagnostic logs to.", + ) + _args_schema.workspace = AAZStrArg( + options=["--workspace"], + help="Name or ID of the Log Analytics workspace to send diagnostic logs to.", + ) + + logs = cls._args_schema.logs + logs.Element = AAZObjectArg() + + _element = cls._args_schema.logs.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.", + ) + _element.category_group = AAZStrArg( + options=["category-group"], + help="Name of a Diagnostic Log category group for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.", + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="A value indicating whether this log is enabled.", + required=True, + ) + _element.retention_policy = AAZObjectArg( + options=["retention-policy"], + help="The retention policy for this log.", + ) + cls._build_args_retention_policy_create(_element.retention_policy) + + metrics = cls._args_schema.metrics + metrics.Element = AAZObjectArg() + + _element = cls._args_schema.metrics.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Diagnostic Metric category for a resource type this setting is applied to. To obtain the list of Diagnostic metric categories for a resource, first perform a GET diagnostic settings operation.", + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="A value indicating whether this category is enabled.", + required=True, + ) + _element.retention_policy = AAZObjectArg( + options=["retention-policy"], + help="The retention policy for this category.", + ) + cls._build_args_retention_policy_create(_element.retention_policy) + _element.time_grain = AAZDurationArg( + options=["time-grain"], + help="The timegrain of the metric in ISO8601 format.", + ) + + # define Arg Group "Target Resource" + + _args_schema = cls._args_schema + _args_schema.resource = AAZStrArg( + options=["--resource"], + arg_group="Target Resource", + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + _args_retention_policy_create = None + + @classmethod + def _build_args_retention_policy_create(cls, _schema): + if cls._args_retention_policy_create is not None: + _schema.days = cls._args_retention_policy_create.days + _schema.enabled = cls._args_retention_policy_create.enabled + return + + cls._args_retention_policy_create = AAZObjectArg() + + retention_policy_create = cls._args_retention_policy_create + retention_policy_create.days = AAZIntArg( + options=["days"], + help="The number of days for the retention. A value of 0 will retain the events indefinitely.", + required=True, + fmt=AAZIntArgFormat( + minimum=0, + ), + ) + retention_policy_create.enabled = AAZBoolArg( + options=["enabled"], + help="A value indicating whether the retention policy is enabled.", + required=True, + ) + + _schema.days = cls._args_retention_policy_create.days + _schema.enabled = cls._args_retention_policy_create.enabled + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsCreateOrUpdate(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 DiagnosticSettingsCreateOrUpdate(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("eventHubAuthorizationRuleId", AAZStrType, ".event_hub_rule") + properties.set_prop("eventHubName", AAZStrType, ".event_hub") + properties.set_prop("logAnalyticsDestinationType", AAZStrType, ".log_analytics_destination_type") + properties.set_prop("logs", AAZListType, ".logs") + properties.set_prop("marketplacePartnerId", AAZStrType, ".marketplace_partner_id") + properties.set_prop("metrics", AAZListType, ".metrics") + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule_id") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account") + properties.set_prop("workspaceId", AAZStrType, ".workspace") + + logs = _builder.get(".properties.logs") + if logs is not None: + logs.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logs[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("categoryGroup", AAZStrType, ".category_group") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + _build_schema_retention_policy_create(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy")) + + metrics = _builder.get(".properties.metrics") + if metrics is not None: + metrics.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.metrics[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + _build_schema_retention_policy_create(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy")) + _elements.set_prop("timeGrain", AAZStrType, ".time_grain") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.log_analytics_destination_type = AAZStrType( + serialized_name="logAnalyticsDestinationType", + ) + properties.logs = AAZListType() + properties.marketplace_partner_id = AAZStrType( + serialized_name="marketplacePartnerId", + ) + properties.metrics = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.logs.Element + _element.category = AAZStrType() + _element.category_group = AAZStrType( + serialized_name="categoryGroup", + ) + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + + metrics = cls._schema_on_200.properties.metrics + metrics.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.metrics.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +def _build_schema_retention_policy_create(_builder): + if _builder is None: + return + _builder.set_prop("days", AAZIntType, ".days", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + +_schema_retention_policy_read = None + + +def _build_schema_retention_policy_read(_schema): + global _schema_retention_policy_read + if _schema_retention_policy_read is not None: + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + return + + _schema_retention_policy_read = AAZObjectType() + + retention_policy_read = _schema_retention_policy_read + retention_policy_read.days = AAZIntType( + flags={"required": True}, + ) + retention_policy_read.enabled = AAZBoolType( + flags={"required": True}, + ) + + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_delete.py new file mode 100644 index 00000000000..43694f639b3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_delete.py @@ -0,0 +1,134 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings delete", +) +class Delete(AAZCommand): + """Deletes existing diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2021-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings/{}", "2021-05-01-preview"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting. Required.", + required=True, + ) + + # define Arg Group "Target Resource" + + _args_schema = cls._args_schema + _args_schema.resource = AAZStrArg( + options=["--resource"], + arg_group="Target Resource", + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class DiagnosticSettingsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_list.py new file mode 100644 index 00000000000..8c3ba3de383 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_list.py @@ -0,0 +1,269 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings list", +) +class List(AAZCommand): + """Gets the active diagnostic settings list for the specified resource. + """ + + _aaz_info = { + "version": "2021-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings", "2021-05-01-preview"], + ] + } + + 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.resource = AAZStrArg( + options=["--resource"], + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsList(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.value, client_flatten=True) + return result + + class DiagnosticSettingsList(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings", + **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( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + 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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.log_analytics_destination_type = AAZStrType( + serialized_name="logAnalyticsDestinationType", + ) + properties.logs = AAZListType() + properties.marketplace_partner_id = AAZStrType( + serialized_name="marketplacePartnerId", + ) + properties.metrics = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.value.Element.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.logs.Element + _element.category = AAZStrType() + _element.category_group = AAZStrType( + serialized_name="categoryGroup", + ) + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + + metrics = cls._schema_on_200.value.Element.properties.metrics + metrics.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.metrics.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +_schema_retention_policy_read = None + + +def _build_schema_retention_policy_read(_schema): + global _schema_retention_policy_read + if _schema_retention_policy_read is not None: + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + return + + _schema_retention_policy_read = AAZObjectType() + + retention_policy_read = _schema_retention_policy_read + retention_policy_read.days = AAZIntType( + flags={"required": True}, + ) + retention_policy_read.enabled = AAZBoolType( + flags={"required": True}, + ) + + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_show.py new file mode 100644 index 00000000000..f4b66276caf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_show.py @@ -0,0 +1,277 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings show", +) +class Show(AAZCommand): + """Gets the active diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2021-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings/{}", "2021-05-01-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting. Required.", + required=True, + ) + + # define Arg Group "Target Resource" + + _args_schema = cls._args_schema + _args_schema.resource = AAZStrArg( + options=["--resource"], + arg_group="Target Resource", + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsGet(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 DiagnosticSettingsGet(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}", + **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( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.log_analytics_destination_type = AAZStrType( + serialized_name="logAnalyticsDestinationType", + ) + properties.logs = AAZListType() + properties.marketplace_partner_id = AAZStrType( + serialized_name="marketplacePartnerId", + ) + properties.metrics = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.logs.Element + _element.category = AAZStrType() + _element.category_group = AAZStrType( + serialized_name="categoryGroup", + ) + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + + metrics = cls._schema_on_200.properties.metrics + metrics.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.metrics.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + _build_schema_retention_policy_read(_element.retention_policy) + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +_schema_retention_policy_read = None + + +def _build_schema_retention_policy_read(_schema): + global _schema_retention_policy_read + if _schema_retention_policy_read is not None: + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + return + + _schema_retention_policy_read = AAZObjectType() + + retention_policy_read = _schema_retention_policy_read + retention_policy_read.days = AAZIntType( + flags={"required": True}, + ) + retention_policy_read.enabled = AAZBoolType( + flags={"required": True}, + ) + + _schema.days = _schema_retention_policy_read.days + _schema.enabled = _schema_retention_policy_read.enabled + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_update.py new file mode 100644 index 00000000000..7ca9eb45851 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/_update.py @@ -0,0 +1,612 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings update", +) +class Update(AAZCommand): + """Update diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2021-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings/{}", "2021-05-01-preview"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting. Required.", + required=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.event_hub_rule = AAZStrArg( + options=["--event-hub-rule"], + arg_group="Properties", + help="The resource Id for the event hub authorization rule.", + nullable=True, + ) + _args_schema.event_hub = AAZStrArg( + options=["--event-hub"], + arg_group="Properties", + help="The name of the event hub. If none is specified, the default event hub will be selected.", + nullable=True, + ) + _args_schema.log_analytics_destination_type = AAZStrArg( + options=["--log-ana-dtype", "--log-analytics-destination-type"], + arg_group="Properties", + help="A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination type constructed as follows: `_`. Possible values are: Dedicated and null (null is default.)", + nullable=True, + ) + _args_schema.logs = AAZListArg( + options=["--logs"], + arg_group="Properties", + help="The list of logs settings.", + nullable=True, + ) + _args_schema.marketplace_partner_id = AAZStrArg( + options=["--marketplace-partner-id"], + arg_group="Properties", + help="The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs.", + nullable=True, + ) + _args_schema.metrics = AAZListArg( + options=["--metrics"], + arg_group="Properties", + help="The list of metric settings.", + nullable=True, + ) + _args_schema.service_bus_rule_id = AAZStrArg( + options=["--service-bus-rule-id"], + arg_group="Properties", + help="The service bus rule Id of the diagnostic setting. This is here to maintain backwards compatibility.", + nullable=True, + ) + _args_schema.storage_account_id = AAZStrArg( + options=["--storage-account-id"], + arg_group="Properties", + help="The resource ID of the storage account to which you would like to send Diagnostic Logs.", + nullable=True, + ) + _args_schema.workspace_id = AAZStrArg( + options=["--workspace-id"], + arg_group="Properties", + help="The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2", + nullable=True, + ) + + logs = cls._args_schema.logs + logs.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.logs.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.", + nullable=True, + ) + _element.category_group = AAZStrArg( + options=["category-group"], + help="Name of a Diagnostic Log category group for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.", + nullable=True, + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="a value indicating whether this log is enabled.", + ) + _element.retention_policy = AAZObjectArg( + options=["retention-policy"], + help="the retention policy for this log.", + nullable=True, + ) + cls._build_args_retention_policy_update(_element.retention_policy) + + metrics = cls._args_schema.metrics + metrics.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.metrics.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Diagnostic Metric category for a resource type this setting is applied to. To obtain the list of Diagnostic metric categories for a resource, first perform a GET diagnostic settings operation.", + nullable=True, + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="a value indicating whether this category is enabled.", + ) + _element.retention_policy = AAZObjectArg( + options=["retention-policy"], + help="the retention policy for this category.", + nullable=True, + ) + cls._build_args_retention_policy_update(_element.retention_policy) + _element.time_grain = AAZDurationArg( + options=["time-grain"], + help="the timegrain of the metric in ISO8601 format.", + nullable=True, + ) + + # define Arg Group "Target Resource" + + _args_schema = cls._args_schema + _args_schema.resource = AAZStrArg( + options=["--resource"], + arg_group="Target Resource", + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + _args_retention_policy_update = None + + @classmethod + def _build_args_retention_policy_update(cls, _schema): + if cls._args_retention_policy_update is not None: + _schema.days = cls._args_retention_policy_update.days + _schema.enabled = cls._args_retention_policy_update.enabled + return + + cls._args_retention_policy_update = AAZObjectArg( + nullable=True, + ) + + retention_policy_update = cls._args_retention_policy_update + retention_policy_update.days = AAZIntArg( + options=["days"], + help="the number of days for the retention in days. A value of 0 will retain the events indefinitely.", + fmt=AAZIntArgFormat( + minimum=0, + ), + ) + retention_policy_update.enabled = AAZBoolArg( + options=["enabled"], + help="a value indicating whether the retention policy is enabled.", + ) + + _schema.days = cls._args_retention_policy_update.days + _schema.enabled = cls._args_retention_policy_update.enabled + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.DiagnosticSettingsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class DiagnosticSettingsGet(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}", + **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( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + 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() + _UpdateHelper._build_schema_diagnostic_settings_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class DiagnosticSettingsCreateOrUpdate(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-05-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_diagnostic_settings_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("eventHubAuthorizationRuleId", AAZStrType, ".event_hub_rule") + properties.set_prop("eventHubName", AAZStrType, ".event_hub") + properties.set_prop("logAnalyticsDestinationType", AAZStrType, ".log_analytics_destination_type") + properties.set_prop("logs", AAZListType, ".logs") + properties.set_prop("marketplacePartnerId", AAZStrType, ".marketplace_partner_id") + properties.set_prop("metrics", AAZListType, ".metrics") + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule_id") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account_id") + properties.set_prop("workspaceId", AAZStrType, ".workspace_id") + + logs = _builder.get(".properties.logs") + if logs is not None: + logs.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logs[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("categoryGroup", AAZStrType, ".category_group") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + _UpdateHelper._build_schema_retention_policy_update(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy")) + + metrics = _builder.get(".properties.metrics") + if metrics is not None: + metrics.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.metrics[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + _UpdateHelper._build_schema_retention_policy_update(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy")) + _elements.set_prop("timeGrain", AAZStrType, ".time_grain") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + @classmethod + def _build_schema_retention_policy_update(cls, _builder): + if _builder is None: + return + _builder.set_prop("days", AAZIntType, ".days", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + _schema_diagnostic_settings_resource_read = None + + @classmethod + def _build_schema_diagnostic_settings_resource_read(cls, _schema): + if cls._schema_diagnostic_settings_resource_read is not None: + _schema.id = cls._schema_diagnostic_settings_resource_read.id + _schema.name = cls._schema_diagnostic_settings_resource_read.name + _schema.properties = cls._schema_diagnostic_settings_resource_read.properties + _schema.system_data = cls._schema_diagnostic_settings_resource_read.system_data + _schema.type = cls._schema_diagnostic_settings_resource_read.type + return + + cls._schema_diagnostic_settings_resource_read = _schema_diagnostic_settings_resource_read = AAZObjectType() + + diagnostic_settings_resource_read = _schema_diagnostic_settings_resource_read + diagnostic_settings_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + diagnostic_settings_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + diagnostic_settings_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + diagnostic_settings_resource_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + diagnostic_settings_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_diagnostic_settings_resource_read.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.log_analytics_destination_type = AAZStrType( + serialized_name="logAnalyticsDestinationType", + ) + properties.logs = AAZListType() + properties.marketplace_partner_id = AAZStrType( + serialized_name="marketplacePartnerId", + ) + properties.metrics = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = _schema_diagnostic_settings_resource_read.properties.logs + logs.Element = AAZObjectType() + + _element = _schema_diagnostic_settings_resource_read.properties.logs.Element + _element.category = AAZStrType() + _element.category_group = AAZStrType( + serialized_name="categoryGroup", + ) + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + cls._build_schema_retention_policy_read(_element.retention_policy) + + metrics = _schema_diagnostic_settings_resource_read.properties.metrics + metrics.Element = AAZObjectType() + + _element = _schema_diagnostic_settings_resource_read.properties.metrics.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + _element.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + ) + cls._build_schema_retention_policy_read(_element.retention_policy) + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + system_data = _schema_diagnostic_settings_resource_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.id = cls._schema_diagnostic_settings_resource_read.id + _schema.name = cls._schema_diagnostic_settings_resource_read.name + _schema.properties = cls._schema_diagnostic_settings_resource_read.properties + _schema.system_data = cls._schema_diagnostic_settings_resource_read.system_data + _schema.type = cls._schema_diagnostic_settings_resource_read.type + + _schema_retention_policy_read = None + + @classmethod + def _build_schema_retention_policy_read(cls, _schema): + if cls._schema_retention_policy_read is not None: + _schema.days = cls._schema_retention_policy_read.days + _schema.enabled = cls._schema_retention_policy_read.enabled + return + + cls._schema_retention_policy_read = _schema_retention_policy_read = AAZObjectType() + + retention_policy_read = _schema_retention_policy_read + retention_policy_read.days = AAZIntType( + flags={"required": True}, + ) + retention_policy_read.enabled = AAZBoolType( + flags={"required": True}, + ) + + _schema.days = cls._schema_retention_policy_read.days + _schema.enabled = cls._schema_retention_policy_read.enabled + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__cmd_group.py new file mode 100644 index 00000000000..6501993c3d6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__cmd_group.py @@ -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 diagnostic-settings categories", +) +class __CMDGroup(AAZCommandGroup): + """Retrieve service diagnostic settings categories. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__init__.py new file mode 100644 index 00000000000..2df85698253 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/__init__.py @@ -0,0 +1,13 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._list import * +from ._show import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_list.py new file mode 100644 index 00000000000..2ff8b01a564 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_list.py @@ -0,0 +1,175 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings categories list", +) +class List(AAZCommand): + """List the diagnostic settings categories for the specified resource. + + :example: List diagnostic settings categories by using resource ID + az monitor diagnostic-settings categories list --resource /subscriptions/00000000-0000-0000- 0000-000000000000/resourcegroups/myRG/providers/microsoft.logic/workflows/myWorkflow + + :example: List diagnostic settings categories by using resource name + az monitor diagnostic-settings categories list -g myRG --resource-type microsoft.logic/workflows --resource myWorkflow + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettingscategories", "2017-05-01-preview"], + ] + } + + 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.resource = AAZStrArg( + options=["--resource"], + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsCategoryList(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 DiagnosticSettingsCategoryList(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories", + **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( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2017-05-01-preview", + 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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.category_type = AAZStrType( + serialized_name="categoryType", + ) + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_show.py new file mode 100644 index 00000000000..dfdaf67a07b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/categories/_show.py @@ -0,0 +1,172 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings categories show", +) +class Show(AAZCommand): + """Gets the diagnostic settings category for the specified resource. + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettingscategories/{}", "2017-05-01-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting. Required.", + required=True, + ) + _args_schema.resource = AAZStrArg( + options=["--resource"], + help="Name or ID of the target resource.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DiagnosticSettingsCategoryGet(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 DiagnosticSettingsCategoryGet(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( + "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettingsCategories/{name}", + **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( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceUri", self.ctx.args.resource, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2017-05-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.category_type = AAZStrType( + serialized_name="categoryType", + ) + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__cmd_group.py new file mode 100644 index 00000000000..481e317c70c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__cmd_group.py @@ -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 diagnostic-settings subscription", +) +class __CMDGroup(AAZCommandGroup): + """Manage diagnostic settings for subscription. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_create.py new file mode 100644 index 00000000000..90a20a59e42 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_create.py @@ -0,0 +1,267 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings subscription create", +) +class Create(AAZCommand): + """Create subscription diagnostic settings for the specified resource. + + :example: Create diagnostic settings for a subscription with EventHub. + az monitor diagnostic-settings subscription create -n {name} --location westus --event-hub-auth-rule {eventHubRuleID} --storage-account {storageAccount} --logs "[{category:Security,enabled:true},{category:Administrative,enabled:true},{category:ServiceHealth,enabled:true},{category:Alert,enabled:true},{category:Recommendation,enabled:true},{category:Policy,enabled:true},{category:Autoscale,enabled:true},{category:ResourceHealth,enabled:true}]" + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/diagnosticsettings/{}", "2017-05-01-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting.", + required=True, + id_part="name", + ) + _args_schema.location = AAZResourceLocationArg( + help="Location of the resource", + ) + _args_schema.event_hub_auth_rule = AAZStrArg( + options=["--event-hub-auth-rule"], + help="The resource Id for the event hub authorization rule.", + ) + _args_schema.event_hub_name = AAZStrArg( + options=["--event-hub-name"], + help="The name of the event hub. If none is specified, the default event hub will be selected.", + ) + _args_schema.logs = AAZListArg( + options=["--logs"], + help="JSON encoded list of logs settings. Use '@{file}' to load from a file.", + ) + _args_schema.service_bus_rule = AAZStrArg( + options=["--service-bus-rule"], + help="The service bus rule ID of the service bus namespace in which you would like to have Event Hubs created for streaming the Activity Log. The rule ID is of the format '{service bus resourceID}/authorizationrules/{key name}'.", + ) + _args_schema.storage_account = AAZStrArg( + options=["--storage-account"], + help="The resource id of the storage account to which you would like to send the Activity Log.", + ) + _args_schema.workspace = AAZStrArg( + options=["--workspace"], + help="The resource id of the log analytics workspace.", + ) + + logs = cls._args_schema.logs + logs.Element = AAZObjectArg() + + _element = cls._args_schema.logs.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Subscription Diagnostic Log category for a resource type this setting is applied to.", + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="a value indicating whether this log is enabled.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SubscriptionDiagnosticSettingsCreateOrUpdate(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 SubscriptionDiagnosticSettingsCreateOrUpdate(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}/providers/microsoft.insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + 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( + "api-version", "2017-05-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location") + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("eventHubAuthorizationRuleId", AAZStrType, ".event_hub_auth_rule") + properties.set_prop("eventHubName", AAZStrType, ".event_hub_name") + properties.set_prop("logs", AAZListType, ".logs") + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account") + properties.set_prop("workspaceId", AAZStrType, ".workspace") + + logs = _builder.get(".properties.logs") + if logs is not None: + logs.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logs[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType() + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.logs = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.logs.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_delete.py new file mode 100644 index 00000000000..cd269eec66d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_delete.py @@ -0,0 +1,125 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings subscription delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Deletes existing subscription diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/diagnosticsettings/{}", "2017-05-01-preview"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SubscriptionDiagnosticSettingsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class SubscriptionDiagnosticSettingsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/providers/microsoft.insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + 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( + "api-version", "2017-05-01-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_list.py new file mode 100644 index 00000000000..0ed3f275781 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_list.py @@ -0,0 +1,184 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings subscription list", +) +class List(AAZCommand): + """Gets the active subscription diagnostic settings list for the specified subscriptionId. :keyword callable cls: A custom type or function that will be passed the direct response:return: SubscriptionDiagnosticSettingsResourceCollection or the result of cls(response):rtype: ~$(python-base-namespace).v2017_05_01_preview.models.SubscriptionDiagnosticSettingsResourceCollection:raises ~azure.core.exceptions.HttpResponseError:. + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/diagnosticsettings", "2017-05-01-preview"], + ] + } + + 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 "" + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SubscriptionDiagnosticSettingsList(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 SubscriptionDiagnosticSettingsList(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}/providers/microsoft.insights/diagnosticSettings", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2017-05-01-preview", + 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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType() + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.logs = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.value.Element.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.logs.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_show.py new file mode 100644 index 00000000000..767be61e567 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_show.py @@ -0,0 +1,190 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings subscription show", +) +class Show(AAZCommand): + """Gets the active subscription diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/diagnosticsettings/{}", "2017-05-01-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SubscriptionDiagnosticSettingsGet(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 SubscriptionDiagnosticSettingsGet(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}/providers/microsoft.insights/diagnosticSettings/{name}", + **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( + "name", self.ctx.args.name, + 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( + "api-version", "2017-05-01-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType() + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.logs = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = cls._schema_on_200.properties.logs + logs.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.logs.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_update.py new file mode 100644 index 00000000000..41fa987de45 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/diagnostic_settings/subscription/_update.py @@ -0,0 +1,411 @@ +# -------------------------------------------------------------------------------------------- +# 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 diagnostic-settings subscription update", +) +class Update(AAZCommand): + """Update subscription diagnostic settings for the specified resource. + """ + + _aaz_info = { + "version": "2017-05-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/diagnosticsettings/{}", "2017-05-01-preview"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the diagnostic setting.", + required=True, + id_part="name", + ) + _args_schema.location = AAZResourceLocationArg( + help="Location of the resource", + nullable=True, + ) + _args_schema.event_hub_auth_rule = AAZStrArg( + options=["--event-hub-auth-rule"], + help="The resource Id for the event hub authorization rule.", + nullable=True, + ) + _args_schema.event_hub_name = AAZStrArg( + options=["--event-hub-name"], + help="The name of the event hub. If none is specified, the default event hub will be selected.", + nullable=True, + ) + _args_schema.logs = AAZListArg( + options=["--logs"], + help="JSON encoded list of logs settings. Use '@{file}' to load from a file.", + nullable=True, + ) + _args_schema.service_bus_rule = AAZStrArg( + options=["--service-bus-rule"], + help="The service bus rule ID of the service bus namespace in which you would like to have Event Hubs created for streaming the Activity Log. The rule ID is of the format '{service bus resourceID}/authorizationrules/{key name}'.", + nullable=True, + ) + _args_schema.storage_account = AAZStrArg( + options=["--storage-account"], + help="The resource id of the storage account to which you would like to send the Activity Log.", + nullable=True, + ) + _args_schema.workspace = AAZStrArg( + options=["--workspace"], + help="The resource id of the log analytics workspace.", + nullable=True, + ) + + logs = cls._args_schema.logs + logs.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.logs.Element + _element.category = AAZStrArg( + options=["category"], + help="Name of a Subscription Diagnostic Log category for a resource type this setting is applied to.", + nullable=True, + ) + _element.enabled = AAZBoolArg( + options=["enabled"], + help="a value indicating whether this log is enabled.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SubscriptionDiagnosticSettingsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.SubscriptionDiagnosticSettingsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class SubscriptionDiagnosticSettingsGet(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}/providers/microsoft.insights/diagnosticSettings/{name}", + **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( + "name", self.ctx.args.name, + 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( + "api-version", "2017-05-01-preview", + 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() + _build_schema_subscription_diagnostic_settings_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class SubscriptionDiagnosticSettingsCreateOrUpdate(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}/providers/microsoft.insights/diagnosticSettings/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + 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( + "api-version", "2017-05-01-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _build_schema_subscription_diagnostic_settings_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("location", AAZStrType, ".location") + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("eventHubAuthorizationRuleId", AAZStrType, ".event_hub_auth_rule") + properties.set_prop("eventHubName", AAZStrType, ".event_hub_name") + properties.set_prop("logs", AAZListType, ".logs") + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account") + properties.set_prop("workspaceId", AAZStrType, ".workspace") + + logs = _builder.get(".properties.logs") + if logs is not None: + logs.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.logs[]") + if _elements is not None: + _elements.set_prop("category", AAZStrType, ".category") + _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_subscription_diagnostic_settings_resource_read = None + + +def _build_schema_subscription_diagnostic_settings_resource_read(_schema): + global _schema_subscription_diagnostic_settings_resource_read + if _schema_subscription_diagnostic_settings_resource_read is not None: + _schema.id = _schema_subscription_diagnostic_settings_resource_read.id + _schema.location = _schema_subscription_diagnostic_settings_resource_read.location + _schema.name = _schema_subscription_diagnostic_settings_resource_read.name + _schema.properties = _schema_subscription_diagnostic_settings_resource_read.properties + _schema.type = _schema_subscription_diagnostic_settings_resource_read.type + return + + _schema_subscription_diagnostic_settings_resource_read = AAZObjectType() + + subscription_diagnostic_settings_resource_read = _schema_subscription_diagnostic_settings_resource_read + subscription_diagnostic_settings_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + subscription_diagnostic_settings_resource_read.location = AAZStrType() + subscription_diagnostic_settings_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + subscription_diagnostic_settings_resource_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + subscription_diagnostic_settings_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_subscription_diagnostic_settings_resource_read.properties + properties.event_hub_authorization_rule_id = AAZStrType( + serialized_name="eventHubAuthorizationRuleId", + ) + properties.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + properties.logs = AAZListType() + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + properties.workspace_id = AAZStrType( + serialized_name="workspaceId", + ) + + logs = _schema_subscription_diagnostic_settings_resource_read.properties.logs + logs.Element = AAZObjectType() + + _element = _schema_subscription_diagnostic_settings_resource_read.properties.logs.Element + _element.category = AAZStrType() + _element.enabled = AAZBoolType( + flags={"required": True}, + ) + + _schema.id = _schema_subscription_diagnostic_settings_resource_read.id + _schema.location = _schema_subscription_diagnostic_settings_resource_read.location + _schema.name = _schema_subscription_diagnostic_settings_resource_read.name + _schema.properties = _schema_subscription_diagnostic_settings_resource_read.properties + _schema.type = _schema_subscription_diagnostic_settings_resource_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__cmd_group.py new file mode 100644 index 00000000000..16575d78395 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__cmd_group.py @@ -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 log-analytics", +) +class __CMDGroup(AAZCommandGroup): + """Manage Azure log analytics. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__init__.py new file mode 100644 index 00000000000..5a9d61963d6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/__init__.py @@ -0,0 +1,11 @@ +# -------------------------------------------------------------------------------------------- +# 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 * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__cmd_group.py new file mode 100644 index 00000000000..5b4f711305b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__cmd_group.py @@ -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 log-analytics cluster", +) +class __CMDGroup(AAZCommandGroup): + """Manage Azure log analytics cluster. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__init__.py new file mode 100644 index 00000000000..db73033039b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_create.py new file mode 100644 index 00000000000..c4f0d454c19 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_create.py @@ -0,0 +1,504 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster create", +) +class Create(AAZCommand): + """Create a cluster instance. + + :example: Create a cluster instance. + az monitor log-analytics cluster create -g MyResourceGroup -n MyCluster --sku-capacity 1000 + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="The name of the Log Analytics cluster.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Identity" + + _args_schema = cls._args_schema + _args_schema.identity_type = AAZStrArg( + options=["--type", "--identity-type"], + arg_group="Identity", + help="Type of managed service identity.", + default="SystemAssigned", + enum={"None": "None", "SystemAssigned": "SystemAssigned", "SystemAssigned,UserAssigned": "SystemAssigned,UserAssigned", "UserAssigned": "UserAssigned"}, + ) + _args_schema.user_assigned = AAZDictArg( + options=["--user-assigned"], + arg_group="Identity", + help="The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.", + ) + + user_assigned = cls._args_schema.user_assigned + user_assigned.Element = AAZObjectArg( + nullable=True, + blank={}, + ) + + # define Arg Group "Key Properties" + + _args_schema = cls._args_schema + _args_schema.key_name = AAZStrArg( + options=["--key-name"], + arg_group="Key Properties", + help="The name of the key associated with the Log Analytics cluster.", + ) + _args_schema.key_rsa_size = AAZIntArg( + options=["--key-rsa-size"], + arg_group="Key Properties", + help="Selected key minimum required size.", + ) + _args_schema.key_vault_uri = AAZStrArg( + options=["--key-vault-uri"], + arg_group="Key Properties", + help="The Key Vault uri which holds they key associated with the Log Analytics cluster.", + ) + _args_schema.key_version = AAZStrArg( + options=["--key-version"], + arg_group="Key Properties", + help="The version of the key associated with the Log Analytics cluster.", + ) + + # define Arg Group "Parameters" + + _args_schema = cls._args_schema + _args_schema.location = AAZResourceLocationArg( + arg_group="Parameters", + help="The geo-location where the resource lives", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Parameters", + help="Resource tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.billing_type = AAZStrArg( + options=["--billing-type"], + arg_group="Properties", + help="The cluster's billing type.", + enum={"Cluster": "Cluster", "Workspaces": "Workspaces"}, + ) + + # define Arg Group "Replication" + + _args_schema = cls._args_schema + _args_schema.replication_enabled = AAZBoolArg( + options=["--replication-enabled"], + arg_group="Replication", + help="Specifies whether the replication is enabled or not. When true the cluster is replicate to the specified location.", + ) + _args_schema.replication_location = AAZStrArg( + options=["--replication-location"], + arg_group="Replication", + help="The secondary location of the replication. If replication is being enabled, enabled must be provided.", + ) + + # define Arg Group "Sku" + + _args_schema = cls._args_schema + _args_schema.sku_capacity = AAZIntArg( + options=["--sku-capacity"], + arg_group="Sku", + help="The capacity of the SKU. It can be decreased only after 31 days.", + enum={"100": 100, "1000": 1000, "10000": 10000, "200": 200, "2000": 2000, "25000": 25000, "300": 300, "400": 400, "500": 500, "5000": 5000, "50000": 50000}, + ) + _args_schema.sku_name = AAZStrArg( + options=["--sku-name"], + arg_group="Sku", + help="The name of the SKU.", + default="CapacityReservation", + enum={"CapacityReservation": "CapacityReservation"}, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.ClustersCreateOrUpdate(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 ClustersCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("sku", AAZObjectType) + _builder.set_prop("tags", AAZDictType, ".tags") + + identity = _builder.get(".identity") + if identity is not None: + identity.set_prop("type", AAZStrType, ".identity_type", typ_kwargs={"flags": {"required": True}}) + identity.set_prop("userAssignedIdentities", AAZDictType, ".user_assigned") + + user_assigned_identities = _builder.get(".identity.userAssignedIdentities") + if user_assigned_identities is not None: + user_assigned_identities.set_elements(AAZObjectType, ".", typ_kwargs={"nullable": True}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("billingType", AAZStrType, ".billing_type") + properties.set_prop("keyVaultProperties", AAZObjectType) + properties.set_prop("replication", AAZObjectType) + + key_vault_properties = _builder.get(".properties.keyVaultProperties") + if key_vault_properties is not None: + key_vault_properties.set_prop("keyName", AAZStrType, ".key_name") + key_vault_properties.set_prop("keyRsaSize", AAZIntType, ".key_rsa_size") + key_vault_properties.set_prop("keyVaultUri", AAZStrType, ".key_vault_uri") + key_vault_properties.set_prop("keyVersion", AAZStrType, ".key_version") + + replication = _builder.get(".properties.replication") + if replication is not None: + replication.set_prop("enabled", AAZBoolType, ".replication_enabled") + replication.set_prop("location", AAZStrType, ".replication_location") + + sku = _builder.get(".sku") + if sku is not None: + sku.set_prop("capacity", AAZIntType, ".sku_capacity") + sku.set_prop("name", AAZStrType, ".sku_name") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.sku = AAZObjectType() + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = cls._schema_on_200.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = cls._schema_on_200.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = cls._schema_on_200.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = cls._schema_on_200.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_delete.py new file mode 100644 index 00000000000..73bbd59ce2f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_delete.py @@ -0,0 +1,163 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a cluster instance. + + :example: Delete a cluster instance. + az monitor log-analytics cluster delete -g MyResourceGroup -n MyCluster + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.ClustersDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class ClustersDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_list.py new file mode 100644 index 00000000000..89139b509ba --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_list.py @@ -0,0 +1,573 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster list", +) +class List(AAZCommand): + """List all cluster instances in a resource group or in current subscription. + + :example: List all cluster instances in a resource group. + az monitor log-analytics cluster list -g MyResourceGroup + + :example: List all cluster instances in current subscription. + az monitor log-analytics cluster list + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.operationalinsights/clusters", "2025-02-01"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters", "2025-02-01"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + condition_1 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + if condition_0: + self.ClustersList(ctx=self.ctx)() + if condition_1: + self.ClustersListByResourceGroup(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class ClustersList(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}/providers/Microsoft.OperationalInsights/clusters", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.sku = AAZObjectType() + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = cls._schema_on_200.value.Element.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = cls._schema_on_200.value.Element.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = cls._schema_on_200.value.Element.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = cls._schema_on_200.value.Element.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class ClustersListByResourceGroup(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.OperationalInsights/clusters", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2025-02-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.sku = AAZObjectType() + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = cls._schema_on_200.value.Element.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = cls._schema_on_200.value.Element.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = cls._schema_on_200.value.Element.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = cls._schema_on_200.value.Element.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_show.py new file mode 100644 index 00000000000..0d888a2abef --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_show.py @@ -0,0 +1,322 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster show", +) +class Show(AAZCommand): + """Show the properties of a cluster instance. + + :example: Show the properties of a cluster instance. + az monitor log-analytics cluster show -g MyResourceGroup -n MyCluster + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(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 ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.sku = AAZObjectType() + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = cls._schema_on_200.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = cls._schema_on_200.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = cls._schema_on_200.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = cls._schema_on_200.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_update.py new file mode 100644 index 00000000000..18c0d6de046 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_update.py @@ -0,0 +1,635 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster update", +) +class Update(AAZCommand): + """Update a cluster instance. + + Update a cluster instance. + + :example: Update a cluster instance. + az monitor log-analytics cluster update -g MyResourceGroup -n MyCluster --key-vault-uri https://myvault.vault.azure.net/ --key-name my-key --key-version fe0adcedd8014aed9c22e9aefb81a1ds --sku-capacity 1000 + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + AZ_SUPPORT_GENERIC_UPDATE = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Identity" + + _args_schema = cls._args_schema + _args_schema.identity_type = AAZStrArg( + options=["--type", "--identity-type"], + arg_group="Identity", + help="Type of managed service identity.", + enum={"None": "None", "SystemAssigned": "SystemAssigned", "SystemAssigned,UserAssigned": "SystemAssigned,UserAssigned", "UserAssigned": "UserAssigned"}, + ) + _args_schema.user_assigned = AAZDictArg( + options=["--user-assigned"], + arg_group="Identity", + help="The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.", + nullable=True, + ) + + user_assigned = cls._args_schema.user_assigned + user_assigned.Element = AAZObjectArg( + nullable=True, + blank={}, + ) + + # define Arg Group "Key Properties" + + _args_schema = cls._args_schema + _args_schema.key_name = AAZStrArg( + options=["--key-name"], + arg_group="Key Properties", + help="The name of the key associated with the Log Analytics cluster.", + nullable=True, + ) + _args_schema.key_rsa_size = AAZIntArg( + options=["--key-rsa-size"], + arg_group="Key Properties", + help="Selected key minimum required size.", + nullable=True, + ) + _args_schema.key_vault_uri = AAZStrArg( + options=["--key-vault-uri"], + arg_group="Key Properties", + help="The Key Vault uri which holds they key associated with the Log Analytics cluster.", + nullable=True, + ) + _args_schema.key_version = AAZStrArg( + options=["--key-version"], + arg_group="Key Properties", + help="The version of the key associated with the Log Analytics cluster.", + nullable=True, + ) + + # define Arg Group "Parameters" + + _args_schema = cls._args_schema + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Parameters", + help="Resource tags.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.billing_type = AAZStrArg( + options=["--billing-type"], + arg_group="Properties", + help="The cluster's billing type.", + nullable=True, + enum={"Cluster": "Cluster", "Workspaces": "Workspaces"}, + ) + + # define Arg Group "Replication" + + _args_schema = cls._args_schema + _args_schema.replication_enabled = AAZBoolArg( + options=["--replication-enabled"], + arg_group="Replication", + help="Specifies whether the replication is enabled or not. When true the cluster is replicate to the specified location.", + nullable=True, + ) + + # define Arg Group "Sku" + + _args_schema = cls._args_schema + _args_schema.sku_capacity = AAZIntArg( + options=["--sku-capacity"], + arg_group="Sku", + help="The capacity of the SKU. It can be decreased only after 31 days.", + nullable=True, + enum={"100": 100, "1000": 1000, "10000": 10000, "200": 200, "2000": 2000, "25000": 25000, "300": 300, "400": 400, "500": 500, "5000": 5000, "50000": 50000}, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + yield self.ClustersCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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() + _UpdateHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ClustersCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("sku", AAZObjectType) + _builder.set_prop("tags", AAZDictType, ".tags") + + identity = _builder.get(".identity") + if identity is not None: + identity.set_prop("type", AAZStrType, ".identity_type", typ_kwargs={"flags": {"required": True}}) + identity.set_prop("userAssignedIdentities", AAZDictType, ".user_assigned") + + user_assigned_identities = _builder.get(".identity.userAssignedIdentities") + if user_assigned_identities is not None: + user_assigned_identities.set_elements(AAZObjectType, ".", typ_kwargs={"nullable": True}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("billingType", AAZStrType, ".billing_type") + properties.set_prop("keyVaultProperties", AAZObjectType) + properties.set_prop("replication", AAZObjectType) + + key_vault_properties = _builder.get(".properties.keyVaultProperties") + if key_vault_properties is not None: + key_vault_properties.set_prop("keyName", AAZStrType, ".key_name") + key_vault_properties.set_prop("keyRsaSize", AAZIntType, ".key_rsa_size") + key_vault_properties.set_prop("keyVaultUri", AAZStrType, ".key_vault_uri") + key_vault_properties.set_prop("keyVersion", AAZStrType, ".key_version") + + replication = _builder.get(".properties.replication") + if replication is not None: + replication.set_prop("enabled", AAZBoolType, ".replication_enabled") + + sku = _builder.get(".sku") + if sku is not None: + sku.set_prop("capacity", AAZIntType, ".sku_capacity") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_cluster_read = None + + @classmethod + def _build_schema_cluster_read(cls, _schema): + if cls._schema_cluster_read is not None: + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + return + + cls._schema_cluster_read = _schema_cluster_read = AAZObjectType() + + cluster_read = _schema_cluster_read + cluster_read.id = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.identity = AAZIdentityObjectType() + cluster_read.location = AAZStrType( + flags={"required": True}, + ) + cluster_read.name = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + cluster_read.sku = AAZObjectType() + cluster_read.tags = AAZDictType() + cluster_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_cluster_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_cluster_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_cluster_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_cluster_read.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = _schema_cluster_read.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = _schema_cluster_read.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = _schema_cluster_read.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = _schema_cluster_read.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = _schema_cluster_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_cluster_read.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = _schema_cluster_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_wait.py new file mode 100644 index 00000000000..51df478ba1a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/_wait.py @@ -0,0 +1,318 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(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=False) + return result + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.sku = AAZObjectType() + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = cls._schema_on_200.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = cls._schema_on_200.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = cls._schema_on_200.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = cls._schema_on_200.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__cmd_group.py new file mode 100644 index 00000000000..e7f1e593afe --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__cmd_group.py @@ -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 log-analytics cluster identity", +) +class __CMDGroup(AAZCommandGroup): + """Manage Identity + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py new file mode 100644 index 00000000000..3a074471e35 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py @@ -0,0 +1,15 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._assign import * +from ._remove import * +from ._show import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_assign.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_assign.py new file mode 100644 index 00000000000..38b1c5781e2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_assign.py @@ -0,0 +1,523 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster identity assign", +) +class Assign(AAZCommand): + """Assign the user or system managed identities. + + :example: Add a system assigned managed identity to an existing cluster + az monitor log-analytics cluster identity assign --name cluster --resource-group rg --system-assigned + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01", "identity"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + return self.build_lro_poller(self._execute_operations, 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Parameters.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="Parameters.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="Parameters.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + yield self.ClustersCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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() + _AssignHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ClustersCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _AssignHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "assign"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "assign"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _AssignHelper: + """Helper class for Assign""" + + _schema_cluster_read = None + + @classmethod + def _build_schema_cluster_read(cls, _schema): + if cls._schema_cluster_read is not None: + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + return + + cls._schema_cluster_read = _schema_cluster_read = AAZObjectType() + + cluster_read = _schema_cluster_read + cluster_read.id = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.identity = AAZIdentityObjectType() + cluster_read.location = AAZStrType( + flags={"required": True}, + ) + cluster_read.name = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + cluster_read.sku = AAZObjectType() + cluster_read.tags = AAZDictType() + cluster_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_cluster_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_cluster_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_cluster_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_cluster_read.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = _schema_cluster_read.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = _schema_cluster_read.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = _schema_cluster_read.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = _schema_cluster_read.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = _schema_cluster_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_cluster_read.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = _schema_cluster_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + + +__all__ = ["Assign"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_remove.py new file mode 100644 index 00000000000..6f8f1d6addf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_remove.py @@ -0,0 +1,520 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster identity remove", +) +class Remove(AAZCommand): + """Remove the user or system managed identities. + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01", "identity"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + return self.build_lro_poller(self._execute_operations, 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Parameters.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="Parameters.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="Parameters.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + yield self.ClustersCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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() + _RemoveHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class ClustersCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _RemoveHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "remove"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "remove"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _RemoveHelper: + """Helper class for Remove""" + + _schema_cluster_read = None + + @classmethod + def _build_schema_cluster_read(cls, _schema): + if cls._schema_cluster_read is not None: + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + return + + cls._schema_cluster_read = _schema_cluster_read = AAZObjectType() + + cluster_read = _schema_cluster_read + cluster_read.id = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.identity = AAZIdentityObjectType() + cluster_read.location = AAZStrType( + flags={"required": True}, + ) + cluster_read.name = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + cluster_read.sku = AAZObjectType() + cluster_read.tags = AAZDictType() + cluster_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_cluster_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_cluster_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_cluster_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_cluster_read.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = _schema_cluster_read.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = _schema_cluster_read.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = _schema_cluster_read.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = _schema_cluster_read.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = _schema_cluster_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_cluster_read.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = _schema_cluster_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + + +__all__ = ["Remove"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_show.py new file mode 100644 index 00000000000..6e82f7111ff --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_show.py @@ -0,0 +1,357 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster identity show", +) +class Show(AAZCommand): + """Show the details of managed identities. + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01", "identity"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(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.selectors.subresource.required(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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() + _ShowHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_cluster_read = None + + @classmethod + def _build_schema_cluster_read(cls, _schema): + if cls._schema_cluster_read is not None: + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + return + + cls._schema_cluster_read = _schema_cluster_read = AAZObjectType() + + cluster_read = _schema_cluster_read + cluster_read.id = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.identity = AAZIdentityObjectType() + cluster_read.location = AAZStrType( + flags={"required": True}, + ) + cluster_read.name = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + cluster_read.sku = AAZObjectType() + cluster_read.tags = AAZDictType() + cluster_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_cluster_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_cluster_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_cluster_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_cluster_read.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = _schema_cluster_read.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = _schema_cluster_read.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = _schema_cluster_read.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = _schema_cluster_read.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = _schema_cluster_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_cluster_read.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = _schema_cluster_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_wait.py new file mode 100644 index 00000000000..1480e0f1c0d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/cluster/identity/_wait.py @@ -0,0 +1,345 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics cluster identity wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/clusters/{}", "2025-02-01", "identity"], + ] + } + + 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.cluster_name = AAZStrArg( + options=["-n", "--name", "--cluster-name"], + help="Name of the Log Analytics Cluster.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ClustersGet(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=False) + return result + + class ClustersGet(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.OperationalInsights/clusters/{clusterName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "clusterName", self.ctx.args.cluster_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( + "api-version", "2025-02-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() + _WaitHelper._build_schema_cluster_read(cls._schema_on_200) + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + _schema_cluster_read = None + + @classmethod + def _build_schema_cluster_read(cls, _schema): + if cls._schema_cluster_read is not None: + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + return + + cls._schema_cluster_read = _schema_cluster_read = AAZObjectType() + + cluster_read = _schema_cluster_read + cluster_read.id = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.identity = AAZIdentityObjectType() + cluster_read.location = AAZStrType( + flags={"required": True}, + ) + cluster_read.name = AAZStrType( + flags={"read_only": True}, + ) + cluster_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + cluster_read.sku = AAZObjectType() + cluster_read.tags = AAZDictType() + cluster_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_cluster_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_cluster_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType( + nullable=True, + ) + + _element = _schema_cluster_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_cluster_read.properties + properties.associated_workspaces = AAZListType( + serialized_name="associatedWorkspaces", + flags={"read_only": True}, + ) + properties.billing_type = AAZStrType( + serialized_name="billingType", + ) + properties.capacity_reservation_properties = AAZObjectType( + serialized_name="capacityReservationProperties", + ) + properties.cluster_id = AAZStrType( + serialized_name="clusterId", + flags={"read_only": True}, + ) + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + properties.is_double_encryption_enabled = AAZBoolType( + serialized_name="isDoubleEncryptionEnabled", + ) + properties.key_vault_properties = AAZObjectType( + serialized_name="keyVaultProperties", + ) + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.replication = AAZObjectType() + + associated_workspaces = _schema_cluster_read.properties.associated_workspaces + associated_workspaces.Element = AAZObjectType() + + _element = _schema_cluster_read.properties.associated_workspaces.Element + _element.associate_date = AAZStrType( + serialized_name="associateDate", + flags={"read_only": True}, + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.workspace_id = AAZStrType( + serialized_name="workspaceId", + flags={"read_only": True}, + ) + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + flags={"read_only": True}, + ) + + capacity_reservation_properties = _schema_cluster_read.properties.capacity_reservation_properties + capacity_reservation_properties.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + capacity_reservation_properties.min_capacity = AAZIntType( + serialized_name="minCapacity", + flags={"read_only": True}, + ) + + key_vault_properties = _schema_cluster_read.properties.key_vault_properties + key_vault_properties.key_name = AAZStrType( + serialized_name="keyName", + ) + key_vault_properties.key_rsa_size = AAZIntType( + serialized_name="keyRsaSize", + ) + key_vault_properties.key_vault_uri = AAZStrType( + serialized_name="keyVaultUri", + ) + key_vault_properties.key_version = AAZStrType( + serialized_name="keyVersion", + ) + + replication = _schema_cluster_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.is_availability_zones_enabled = AAZBoolType( + serialized_name="isAvailabilityZonesEnabled", + ) + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_cluster_read.sku + sku.capacity = AAZIntType() + sku.name = AAZStrType() + + tags = _schema_cluster_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_cluster_read.id + _schema.identity = cls._schema_cluster_read.identity + _schema.location = cls._schema_cluster_read.location + _schema.name = cls._schema_cluster_read.name + _schema.properties = cls._schema_cluster_read.properties + _schema.sku = cls._schema_cluster_read.sku + _schema.tags = cls._schema_cluster_read.tags + _schema.type = cls._schema_cluster_read.type + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__cmd_group.py new file mode 100644 index 00000000000..9966f40445b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage Azure log analytics query pack. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_create.py new file mode 100644 index 00000000000..8ff96f823b7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_create.py @@ -0,0 +1,232 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack create", + is_preview=True, +) +class Create(AAZCommand): + """Create a log analytics query pack. + + :example: Create a query pack + az monitor log-analytics query-pack create -g resourceGroup -n queryPackName --location eastus2 + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}", "2019-09-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.location = AAZResourceLocationArg( + help="Resource location", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Resource tags", + ) + _args_schema.query_pack_name = AAZStrArg( + options=["-n", "--name", "--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueryPacksCreateOrUpdate(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 QueryPacksCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/queryPacks/{queryPackName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.query_pack_id = AAZStrType( + serialized_name="queryPackId", + flags={"read_only": True}, + ) + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_delete.py new file mode 100644 index 00000000000..f218a47e8cc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_delete.py @@ -0,0 +1,136 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack delete", + is_preview=True, + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a log analytics query pack. + + :example: Delete a query pack + az monitor log-analytics query-pack delete-g resourceGroup -n queryPackName + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}", "2019-09-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.query_pack_name = AAZStrArg( + options=["-n", "--name", "--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueryPacksDelete(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class QueryPacksDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/queryPacks/{queryPackName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_list.py new file mode 100644 index 00000000000..691038eeec1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_list.py @@ -0,0 +1,330 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack list", + is_preview=True, +) +class List(AAZCommand): + """List of all log analytics query packs. + + :example: List query packs in a specific subscription + az monitor log-analytics query-pack list + + :example: List query packs in a specific resource group + az monitor log-analytics query-pack list -g resourceGroup + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.operationalinsights/querypacks", "2019-09-01"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks", "2019-09-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.QueryPacksListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.QueryPacksList(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class QueryPacksListByResourceGroup(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.OperationalInsights/queryPacks", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2019-09-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.query_pack_id = AAZStrType( + serialized_name="queryPackId", + flags={"read_only": True}, + ) + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class QueryPacksList(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}/providers/Microsoft.OperationalInsights/queryPacks", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2019-09-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.query_pack_id = AAZStrType( + serialized_name="queryPackId", + flags={"read_only": True}, + ) + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_show.py new file mode 100644 index 00000000000..567d4f41703 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_show.py @@ -0,0 +1,198 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack show", + is_preview=True, +) +class Show(AAZCommand): + """Show a log analytics query pack. + + :example: Show a query pack + az monitor log-analytics query-pack show -g resourceGroup -n queryPackName + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}", "2019-09-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.query_pack_name = AAZStrArg( + options=["-n", "--name", "--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueryPacksGet(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 QueryPacksGet(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.OperationalInsights/queryPacks/{queryPackName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.query_pack_id = AAZStrType( + serialized_name="queryPackId", + flags={"read_only": True}, + ) + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_update.py new file mode 100644 index 00000000000..76487d9405c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/_update.py @@ -0,0 +1,370 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack update", + is_preview=True, +) +class Update(AAZCommand): + """Update a log analytics query pack. + + :example: Update a query pack + az monitor log-analytics query-pack update -g resourceGroupName -n queryPackName --tags label1=value1 + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}", "2019-09-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.tags = AAZDictArg( + options=["--tags"], + help="Resource tags", + nullable=True, + ) + _args_schema.query_pack_name = AAZStrArg( + options=["-n", "--name", "--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueryPacksGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.QueryPacksCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class QueryPacksGet(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.OperationalInsights/queryPacks/{queryPackName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-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() + _build_schema_log_analytics_query_pack_read(cls._schema_on_200) + + return cls._schema_on_200 + + class QueryPacksCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/queryPacks/{queryPackName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _build_schema_log_analytics_query_pack_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_log_analytics_query_pack_read = None + + +def _build_schema_log_analytics_query_pack_read(_schema): + global _schema_log_analytics_query_pack_read + if _schema_log_analytics_query_pack_read is not None: + _schema.id = _schema_log_analytics_query_pack_read.id + _schema.location = _schema_log_analytics_query_pack_read.location + _schema.name = _schema_log_analytics_query_pack_read.name + _schema.properties = _schema_log_analytics_query_pack_read.properties + _schema.tags = _schema_log_analytics_query_pack_read.tags + _schema.type = _schema_log_analytics_query_pack_read.type + return + + _schema_log_analytics_query_pack_read = AAZObjectType() + + log_analytics_query_pack_read = _schema_log_analytics_query_pack_read + log_analytics_query_pack_read.id = AAZStrType( + flags={"read_only": True}, + ) + log_analytics_query_pack_read.location = AAZStrType( + flags={"required": True}, + ) + log_analytics_query_pack_read.name = AAZStrType( + flags={"read_only": True}, + ) + log_analytics_query_pack_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + log_analytics_query_pack_read.tags = AAZDictType() + log_analytics_query_pack_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_log_analytics_query_pack_read.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.query_pack_id = AAZStrType( + serialized_name="queryPackId", + flags={"read_only": True}, + ) + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + tags = _schema_log_analytics_query_pack_read.tags + tags.Element = AAZStrType() + + _schema.id = _schema_log_analytics_query_pack_read.id + _schema.location = _schema_log_analytics_query_pack_read.location + _schema.name = _schema_log_analytics_query_pack_read.name + _schema.properties = _schema_log_analytics_query_pack_read.properties + _schema.tags = _schema_log_analytics_query_pack_read.tags + _schema.type = _schema_log_analytics_query_pack_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__cmd_group.py new file mode 100644 index 00000000000..ebcd3c5df0c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage the query of log analytics query pack + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py new file mode 100644 index 00000000000..10a024b2268 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._search import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_create.py new file mode 100644 index 00000000000..b1064dbe769 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_create.py @@ -0,0 +1,369 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query create", + is_preview=True, +) +class Create(AAZCommand): + """Create a specific query within a log analytics query pack. + + :example: Create a query in a query pack + az monitor log-analytics query-pack query create --query-id 112c6b1f-5a86-4f01-a2d7-efb8e31f930f --display-name queryName -g resourceGroupName --query-pack-name queryPackName --body "heartbeat | take 10" --description "some description" --categories "[network,monitor]" --resource-types "[microsoft.network/loadbalancers,microsoft.insights/autoscalesettings]" --solutions "[networkmonitoring]" --tags "{version:[v2022-01-01,v2021-12-01]}" + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries/{}", "2019-09-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.query_id = AAZStrArg( + options=["-n", "--name", "--query-id"], + help="The id name of a specific query defined in the log analytics query pack. It must be of type GUID.", + required=True, + id_part="child_name_1", + ) + _args_schema.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.body = AAZStrArg( + options=["--body"], + arg_group="Properties", + help="Content of the query.", + required=True, + ) + _args_schema.description = AAZStrArg( + options=["--description"], + arg_group="Properties", + help="Description of the query.", + ) + _args_schema.display_name = AAZStrArg( + options=["--display-name"], + arg_group="Properties", + help="Unique display name for your query within the query pack.", + required=True, + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Properties", + help="Tags associated with the query.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZListArg() + + _element = cls._args_schema.tags.Element + _element.Element = AAZStrArg() + + # define Arg Group "Related" + + _args_schema = cls._args_schema + _args_schema.categories = AAZListArg( + options=["--categories"], + arg_group="Related", + help={"short-summary": "The related categories for the function.", "long-summary": "Supported value are: `security`, `network`, `management`, `virtualmachines`, `container`, `audit`, `desktopanalytics`, `workloads`, `resources`, `applications`, `monitor`, `databases`, `windowsvirtualdesktop` etc."}, + ) + _args_schema.resource_types = AAZListArg( + options=["--resource-types"], + arg_group="Related", + help="The related resource types for the function.", + ) + _args_schema.solutions = AAZListArg( + options=["--solutions"], + arg_group="Related", + help="The related Log Analytics solutions for the function.", + ) + + categories = cls._args_schema.categories + categories.Element = AAZStrArg() + + resource_types = cls._args_schema.resource_types + resource_types.Element = AAZStrArg() + + solutions = cls._args_schema.solutions + solutions.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesPut(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 QueriesPut(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.OperationalInsights/queryPacks/{queryPackName}/queries/{id}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "id", self.ctx.args.query_id, + required=True, + ), + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("body", AAZStrType, ".body", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("displayName", AAZStrType, ".display_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("related", AAZObjectType) + properties.set_prop("tags", AAZDictType, ".tags") + + related = _builder.get(".properties.related") + if related is not None: + related.set_prop("categories", AAZListType, ".categories") + related.set_prop("resourceTypes", AAZListType, ".resource_types") + related.set_prop("solutions", AAZListType, ".solutions") + + categories = _builder.get(".properties.related.categories") + if categories is not None: + categories.set_elements(AAZStrType, ".") + + resource_types = _builder.get(".properties.related.resourceTypes") + if resource_types is not None: + resource_types.set_elements(AAZStrType, ".") + + solutions = _builder.get(".properties.related.solutions") + if solutions is not None: + solutions.set_elements(AAZStrType, ".") + + tags = _builder.get(".properties.tags") + if tags is not None: + tags.set_elements(AAZListType, ".") + + _elements = _builder.get(".properties.tags{}") + if _elements is not None: + _elements.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.author = AAZStrType( + flags={"read_only": True}, + ) + properties.body = AAZStrType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.id = AAZStrType( + flags={"read_only": True}, + ) + properties.related = AAZObjectType() + properties.tags = AAZDictType() + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + related = cls._schema_on_200.properties.related + related.categories = AAZListType() + related.resource_types = AAZListType( + serialized_name="resourceTypes", + ) + related.solutions = AAZListType() + + categories = cls._schema_on_200.properties.related.categories + categories.Element = AAZStrType() + + resource_types = cls._schema_on_200.properties.related.resource_types + resource_types.Element = AAZStrType() + + solutions = cls._schema_on_200.properties.related.solutions + solutions.Element = AAZStrType() + + tags = cls._schema_on_200.properties.tags + tags.Element = AAZListType() + + _element = cls._schema_on_200.properties.tags.Element + _element.Element = AAZStrType() + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_delete.py new file mode 100644 index 00000000000..c541c126ce8 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_delete.py @@ -0,0 +1,146 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query delete", + is_preview=True, + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a specific query defined within a log analytics query pack. + + :example: Delete a query in a query pack + az monitor log-analytics query-pack query delete --query-id 112c6b1f-5a86-4f01-a2d7-efb8e31f930f -g resourceGroup --query-pack-name queryPackName + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries/{}", "2019-09-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.query_id = AAZStrArg( + options=["-n", "--name", "--query-id"], + help="The id name of a specific query defined in the log analytics query pack. It must be of type GUID.", + required=True, + id_part="child_name_1", + ) + _args_schema.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesDelete(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class QueriesDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/queryPacks/{queryPackName}/queries/{id}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "id", self.ctx.args.query_id, + required=True, + ), + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_list.py new file mode 100644 index 00000000000..e0172b68f23 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_list.py @@ -0,0 +1,271 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query list", + is_preview=True, +) +class List(AAZCommand): + """List queries defined within a log analytics query pack. + + :example: List queries in a query pack + az monitor log-analytics query-pack query list -g resourceGroupName --query-pack-name queryPackName + + :example: List queries in a query pack without query body content + az monitor log-analytics query-pack query list -g resourceGroupName --query-pack-name queryPackName --include-body false + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries", "2019-09-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.include_body = AAZBoolArg( + options=["--include-body"], + help="Whether or not to return the body of each applicable query. If false, only return the query information. Default: true.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesList(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class QueriesList(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.OperationalInsights/queryPacks/{queryPackName}/queries", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "includeBody", self.ctx.args.include_body, + ), + **self.serialize_query_param( + "api-version", "2019-09-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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.author = AAZStrType( + flags={"read_only": True}, + ) + properties.body = AAZStrType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.id = AAZStrType( + flags={"read_only": True}, + ) + properties.related = AAZObjectType() + properties.tags = AAZDictType() + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + related = cls._schema_on_200.value.Element.properties.related + related.categories = AAZListType() + related.resource_types = AAZListType( + serialized_name="resourceTypes", + ) + related.solutions = AAZListType() + + categories = cls._schema_on_200.value.Element.properties.related.categories + categories.Element = AAZStrType() + + resource_types = cls._schema_on_200.value.Element.properties.related.resource_types + resource_types.Element = AAZStrType() + + solutions = cls._schema_on_200.value.Element.properties.related.solutions + solutions.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.properties.tags + tags.Element = AAZListType() + + _element = cls._schema_on_200.value.Element.properties.tags.Element + _element.Element = AAZStrType() + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_search.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_search.py new file mode 100644 index 00000000000..5fa70af39fc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_search.py @@ -0,0 +1,352 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query search", + is_preview=True, +) +class Search(AAZCommand): + """Search a list of queries defined within a log analytics query pack according to given search properties. + + :example: Search queries in a query pack + az monitor log-analytics query-pack query search -g resourceGroupName --query-pack-name queryPackName --categories network --resource-types microsoft.insights/autoscalesettings --solutions networkmonitoring --tags version="[v2021-12-01]" + + :example: Search queries in a query pack without query body content + az monitor log-analytics query-pack query search -g resourceGroupName --query-pack-name queryPackName --categories network --resource-types microsoft.insights/autoscalesettings --solutions networkmonitoring --tags version="[v2021-12-01]" --include-body false + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries/search", "2019-09-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.include_body = AAZBoolArg( + options=["--include-body"], + help="Whether or not to return the body of each applicable query. If false, only return the query information. Default: true.", + ) + + # define Arg Group "SearchProperties" + + _args_schema = cls._args_schema + _args_schema.categories = AAZListArg( + options=["--categories"], + arg_group="SearchProperties", + help={"short-summary": "The related categories for the function.", "long-summary": "Supported value are: `security`, `network`, `management`, `virtualmachines`, `container`, `audit`, `desktopanalytics`, `workloads`, `resources`, `applications`, `monitor`, `databases`, `windowsvirtualdesktop` etc."}, + ) + _args_schema.resource_types = AAZListArg( + options=["--resource-types"], + arg_group="SearchProperties", + help="The related resource types for the function.", + ) + _args_schema.solutions = AAZListArg( + options=["--solutions"], + arg_group="SearchProperties", + help="The related Log Analytics solutions for the function.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="SearchProperties", + help="Tags associated with the query.", + ) + + categories = cls._args_schema.categories + categories.Element = AAZStrArg() + + resource_types = cls._args_schema.resource_types + resource_types.Element = AAZStrArg() + + solutions = cls._args_schema.solutions + solutions.Element = AAZStrArg() + + tags = cls._args_schema.tags + tags.Element = AAZListArg() + + _element = cls._args_schema.tags.Element + _element.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesSearch(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class QueriesSearch(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.OperationalInsights/queryPacks/{queryPackName}/queries/search", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "includeBody", self.ctx.args.include_body, + ), + **self.serialize_query_param( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("related", AAZObjectType) + _builder.set_prop("tags", AAZDictType, ".tags") + + related = _builder.get(".related") + if related is not None: + related.set_prop("categories", AAZListType, ".categories") + related.set_prop("resourceTypes", AAZListType, ".resource_types") + related.set_prop("solutions", AAZListType, ".solutions") + + categories = _builder.get(".related.categories") + if categories is not None: + categories.set_elements(AAZStrType, ".") + + resource_types = _builder.get(".related.resourceTypes") + if resource_types is not None: + resource_types.set_elements(AAZStrType, ".") + + solutions = _builder.get(".related.solutions") + if solutions is not None: + solutions.set_elements(AAZStrType, ".") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZListType, ".") + + _elements = _builder.get(".tags{}") + if _elements is not None: + _elements.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.author = AAZStrType( + flags={"read_only": True}, + ) + properties.body = AAZStrType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.id = AAZStrType( + flags={"read_only": True}, + ) + properties.related = AAZObjectType() + properties.tags = AAZDictType() + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + related = cls._schema_on_200.value.Element.properties.related + related.categories = AAZListType() + related.resource_types = AAZListType( + serialized_name="resourceTypes", + ) + related.solutions = AAZListType() + + categories = cls._schema_on_200.value.Element.properties.related.categories + categories.Element = AAZStrType() + + resource_types = cls._schema_on_200.value.Element.properties.related.resource_types + resource_types.Element = AAZStrType() + + solutions = cls._schema_on_200.value.Element.properties.related.solutions + solutions.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.properties.tags + tags.Element = AAZListType() + + _element = cls._schema_on_200.value.Element.properties.tags.Element + _element.Element = AAZStrType() + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Search"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_show.py new file mode 100644 index 00000000000..0ee7113bf01 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_show.py @@ -0,0 +1,261 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query show", + is_preview=True, +) +class Show(AAZCommand): + """Show a specific query defined within a log analytics query pack. + + :example: Show a query in a query pack + az monitor log-analytics query-pack query show --query-id 112c6b1f-5a86-4f01-a2d7-efb8e31f930f -g resourceGroup --query-pack-name queryPackName + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries/{}", "2019-09-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.query_id = AAZStrArg( + options=["-n", "--name", "--query-id"], + help="The id name of a specific query defined in the log analytics query pack. It must be of type GUID.", + required=True, + id_part="child_name_1", + ) + _args_schema.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesGet(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 QueriesGet(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.OperationalInsights/queryPacks/{queryPackName}/queries/{id}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "id", self.ctx.args.query_id, + required=True, + ), + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.author = AAZStrType( + flags={"read_only": True}, + ) + properties.body = AAZStrType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.id = AAZStrType( + flags={"read_only": True}, + ) + properties.related = AAZObjectType() + properties.tags = AAZDictType() + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + related = cls._schema_on_200.properties.related + related.categories = AAZListType() + related.resource_types = AAZListType( + serialized_name="resourceTypes", + ) + related.solutions = AAZListType() + + categories = cls._schema_on_200.properties.related.categories + categories.Element = AAZStrType() + + resource_types = cls._schema_on_200.properties.related.resource_types + resource_types.Element = AAZStrType() + + solutions = cls._schema_on_200.properties.related.solutions + solutions.Element = AAZStrType() + + tags = cls._schema_on_200.properties.tags + tags.Element = AAZListType() + + _element = cls._schema_on_200.properties.tags.Element + _element.Element = AAZStrType() + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_update.py new file mode 100644 index 00000000000..8ddc7fe9462 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/query_pack/query/_update.py @@ -0,0 +1,528 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics query-pack query update", + is_preview=True, +) +class Update(AAZCommand): + """Update a specific query within a log analytics query pack. + + :example: Update a query in a query pack + az monitor log-analytics query-pack query update --query-id 112c6b1f-5a86-4f01-a2d7-efb8e31f930f -g resourceGroup --query-pack-name queryPackName --body "heartbeat | take 20" --categories [2]=databases --tags version[0]=null + """ + + _aaz_info = { + "version": "2019-09-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/querypacks/{}/queries/{}", "2019-09-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.query_id = AAZStrArg( + options=["-n", "--name", "--query-id"], + help="The id name of a specific query defined in the log analytics query pack. It must be of type GUID.", + required=True, + id_part="child_name_1", + ) + _args_schema.query_pack_name = AAZStrArg( + options=["--query-pack-name"], + help="The name of the log analytics query pack.", + required=True, + id_part="name", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.body = AAZStrArg( + options=["--body"], + arg_group="Properties", + help="Content of the query.", + ) + _args_schema.description = AAZStrArg( + options=["--description"], + arg_group="Properties", + help="Description of the query.", + nullable=True, + ) + _args_schema.display_name = AAZStrArg( + options=["--display-name"], + arg_group="Properties", + help="Unique display name for your query within the query pack.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Properties", + help="Tags associated with the query.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZListArg( + nullable=True, + ) + + _element = cls._args_schema.tags.Element + _element.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Related" + + _args_schema = cls._args_schema + _args_schema.categories = AAZListArg( + options=["--categories"], + arg_group="Related", + help={"short-summary": "The related categories for the function.", "long-summary": "Supported value are: `security`, `network`, `management`, `virtualmachines`, `container`, `audit`, `desktopanalytics`, `workloads`, `resources`, `applications`, `monitor`, `databases`, `windowsvirtualdesktop` etc."}, + nullable=True, + ) + _args_schema.resource_types = AAZListArg( + options=["--resource-types"], + arg_group="Related", + help="The related resource types for the function.", + nullable=True, + ) + _args_schema.solutions = AAZListArg( + options=["--solutions"], + arg_group="Related", + help="The related Log Analytics solutions for the function.", + nullable=True, + ) + + categories = cls._args_schema.categories + categories.Element = AAZStrArg( + nullable=True, + ) + + resource_types = cls._args_schema.resource_types + resource_types.Element = AAZStrArg( + nullable=True, + ) + + solutions = cls._args_schema.solutions + solutions.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.QueriesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.QueriesPut(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class QueriesGet(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.OperationalInsights/queryPacks/{queryPackName}/queries/{id}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "id", self.ctx.args.query_id, + required=True, + ), + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-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() + _build_schema_log_analytics_query_pack_query_read(cls._schema_on_200) + + return cls._schema_on_200 + + class QueriesPut(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.OperationalInsights/queryPacks/{queryPackName}/queries/{id}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "id", self.ctx.args.query_id, + required=True, + ), + **self.serialize_url_param( + "queryPackName", self.ctx.args.query_pack_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( + "api-version", "2019-09-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _build_schema_log_analytics_query_pack_query_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("body", AAZStrType, ".body", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("displayName", AAZStrType, ".display_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("related", AAZObjectType) + properties.set_prop("tags", AAZDictType, ".tags") + + related = _builder.get(".properties.related") + if related is not None: + related.set_prop("categories", AAZListType, ".categories") + related.set_prop("resourceTypes", AAZListType, ".resource_types") + related.set_prop("solutions", AAZListType, ".solutions") + + categories = _builder.get(".properties.related.categories") + if categories is not None: + categories.set_elements(AAZStrType, ".") + + resource_types = _builder.get(".properties.related.resourceTypes") + if resource_types is not None: + resource_types.set_elements(AAZStrType, ".") + + solutions = _builder.get(".properties.related.solutions") + if solutions is not None: + solutions.set_elements(AAZStrType, ".") + + tags = _builder.get(".properties.tags") + if tags is not None: + tags.set_elements(AAZListType, ".") + + _elements = _builder.get(".properties.tags{}") + if _elements is not None: + _elements.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_log_analytics_query_pack_query_read = None + + +def _build_schema_log_analytics_query_pack_query_read(_schema): + global _schema_log_analytics_query_pack_query_read + if _schema_log_analytics_query_pack_query_read is not None: + _schema.id = _schema_log_analytics_query_pack_query_read.id + _schema.name = _schema_log_analytics_query_pack_query_read.name + _schema.properties = _schema_log_analytics_query_pack_query_read.properties + _schema.system_data = _schema_log_analytics_query_pack_query_read.system_data + _schema.type = _schema_log_analytics_query_pack_query_read.type + return + + _schema_log_analytics_query_pack_query_read = AAZObjectType() + + log_analytics_query_pack_query_read = _schema_log_analytics_query_pack_query_read + log_analytics_query_pack_query_read.id = AAZStrType( + flags={"read_only": True}, + ) + log_analytics_query_pack_query_read.name = AAZStrType( + flags={"read_only": True}, + ) + log_analytics_query_pack_query_read.properties = AAZObjectType( + flags={"required": True}, + ) + log_analytics_query_pack_query_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + log_analytics_query_pack_query_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_log_analytics_query_pack_query_read.properties + properties.author = AAZStrType( + flags={"read_only": True}, + ) + properties.body = AAZStrType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.id = AAZStrType( + flags={"read_only": True}, + ) + properties.related = AAZObjectType() + properties.tags = AAZDictType() + properties.time_created = AAZStrType( + serialized_name="timeCreated", + flags={"read_only": True}, + ) + properties.time_modified = AAZStrType( + serialized_name="timeModified", + flags={"read_only": True}, + ) + + related = _schema_log_analytics_query_pack_query_read.properties.related + related.categories = AAZListType() + related.resource_types = AAZListType( + serialized_name="resourceTypes", + ) + related.solutions = AAZListType() + + categories = _schema_log_analytics_query_pack_query_read.properties.related.categories + categories.Element = AAZStrType() + + resource_types = _schema_log_analytics_query_pack_query_read.properties.related.resource_types + resource_types.Element = AAZStrType() + + solutions = _schema_log_analytics_query_pack_query_read.properties.related.solutions + solutions.Element = AAZStrType() + + tags = _schema_log_analytics_query_pack_query_read.properties.tags + tags.Element = AAZListType() + + _element = _schema_log_analytics_query_pack_query_read.properties.tags.Element + _element.Element = AAZStrType() + + system_data = _schema_log_analytics_query_pack_query_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + _schema.id = _schema_log_analytics_query_pack_query_read.id + _schema.name = _schema_log_analytics_query_pack_query_read.name + _schema.properties = _schema_log_analytics_query_pack_query_read.properties + _schema.system_data = _schema_log_analytics_query_pack_query_read.system_data + _schema.type = _schema_log_analytics_query_pack_query_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__cmd_group.py new file mode 100644 index 00000000000..55a8fec9a84 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__cmd_group.py @@ -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 log-analytics workspace", +) +class __CMDGroup(AAZCommandGroup): + """Manage Azure log analytics workspace + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__init__.py new file mode 100644 index 00000000000..2a09dda8590 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/__init__.py @@ -0,0 +1,26 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._failback import * +from ._failover import * +from ._get_schema import * +from ._get_shared_keys import * +from ._list import * +from ._list_available_service_tier import * +from ._list_deleted_workspaces import * +from ._list_link_target import * +from ._list_management_groups import * +from ._list_usages import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_create.py new file mode 100644 index 00000000000..eac0bc64e11 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_create.py @@ -0,0 +1,519 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace create", +) +class Create(AAZCommand): + """Create a workspace instance + + :example: Create a workspace instance + az monitor log-analytics workspace create -g MyResourceGroup -n MyWorkspace + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Identity" + + _args_schema = cls._args_schema + _args_schema.identity_type = AAZStrArg( + options=["--type", "--identity-type"], + arg_group="Identity", + help="Type of managed service identity.", + enum={"None": "None", "SystemAssigned": "SystemAssigned", "UserAssigned": "UserAssigned"}, + ) + _args_schema.user_assigned = AAZDictArg( + options=["--user-assigned"], + arg_group="Identity", + help="The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.", + ) + + user_assigned = cls._args_schema.user_assigned + user_assigned.Element = AAZObjectArg( + blank={}, + ) + + # define Arg Group "Parameters" + + _args_schema = cls._args_schema + _args_schema.location = AAZResourceLocationArg( + arg_group="Parameters", + help="The geo-location where the resource lives", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Parameters", + help="Resource tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.ingestion_access = AAZStrArg( + options=["--ingestion-access"], + arg_group="Properties", + help="The public network access type to access workspace ingestion.", + default="Enabled", + enum={"Disabled": "Disabled", "Enabled": "Enabled"}, + ) + _args_schema.query_access = AAZStrArg( + options=["--query-access"], + arg_group="Properties", + help="The public network access type to access workspace query.", + default="Enabled", + enum={"Disabled": "Disabled", "Enabled": "Enabled"}, + ) + _args_schema.retention_time = AAZIntArg( + options=["--retention-time"], + arg_group="Properties", + help="The workspace data retention in days. Allowed values are per pricing plan. See pricing tiers documentation for details.", + default=30, + nullable=True, + ) + _args_schema.quota = AAZFloatArg( + options=["--quota"], + arg_group="Properties", + help="The workspace daily quota for ingestion in gigabytes. The minimum value is 0.023 and default is -1 which means unlimited.", + ) + + # define Arg Group "Replication" + + _args_schema = cls._args_schema + _args_schema.replication_enabled = AAZBoolArg( + options=["--replication-enabled"], + arg_group="Replication", + help="Specifies whether the replication is enabled or not. When true, workspace configuration and data is replicated to the specified location. If replication is been enabled, location must be provided.", + ) + _args_schema.replication_location = AAZStrArg( + options=["--replication-location"], + arg_group="Replication", + help="The location of the replication.", + ) + + # define Arg Group "Sku" + + _args_schema = cls._args_schema + _args_schema.capacity_reservation_level = AAZIntArg( + options=["--level", "--capacity-reservation-level"], + arg_group="Sku", + help="The capacity reservation level for this workspace, when CapacityReservation sku is selected. The maximum value is 1000 and must be in multiples of 100. If you want to increase the limit, please contact LAIngestionRate@microsoft.com.", + enum={"100": 100, "1000": 1000, "10000": 10000, "200": 200, "2000": 2000, "25000": 25000, "300": 300, "400": 400, "500": 500, "5000": 5000, "50000": 50000}, + ) + _args_schema.sku_name = AAZStrArg( + options=["--sku", "--sku-name"], + arg_group="Sku", + help="The name of the SKU.", + default="PerGB2018", + enum={"CapacityReservation": "CapacityReservation", "Free": "Free", "LACluster": "LACluster", "PerGB2018": "PerGB2018", "PerNode": "PerNode", "Premium": "Premium", "Standalone": "Standalone", "Standard": "Standard"}, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.WorkspacesCreateOrUpdate(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 WorkspacesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + identity = _builder.get(".identity") + if identity is not None: + identity.set_prop("type", AAZStrType, ".identity_type", typ_kwargs={"flags": {"required": True}}) + identity.set_prop("userAssignedIdentities", AAZDictType, ".user_assigned") + + user_assigned_identities = _builder.get(".identity.userAssignedIdentities") + if user_assigned_identities is not None: + user_assigned_identities.set_elements(AAZObjectType, ".") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("publicNetworkAccessForIngestion", AAZStrType, ".ingestion_access") + properties.set_prop("publicNetworkAccessForQuery", AAZStrType, ".query_access") + properties.set_prop("replication", AAZObjectType) + properties.set_prop("retentionInDays", AAZIntType, ".retention_time", typ_kwargs={"nullable": True}) + properties.set_prop("sku", AAZObjectType) + properties.set_prop("workspaceCapping", AAZObjectType) + + replication = _builder.get(".properties.replication") + if replication is not None: + replication.set_prop("enabled", AAZBoolType, ".replication_enabled") + replication.set_prop("location", AAZStrType, ".replication_location") + + sku = _builder.get(".properties.sku") + if sku is not None: + sku.set_prop("capacityReservationLevel", AAZIntType, ".capacity_reservation_level") + sku.set_prop("name", AAZStrType, ".sku_name", typ_kwargs={"flags": {"required": True}}) + + workspace_capping = _builder.get(".properties.workspaceCapping") + if workspace_capping is not None: + workspace_capping.set_prop("dailyQuotaGb", AAZFloatType, ".quota") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.etag = AAZStrType() + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.identity = AAZIdentityObjectType() + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200_201.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200_201.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = cls._schema_on_200_201.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = cls._schema_on_200_201.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = cls._schema_on_200_201.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = cls._schema_on_200_201.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200_201.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200_201.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200_201.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_delete.py new file mode 100644 index 00000000000..28af7952543 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_delete.py @@ -0,0 +1,180 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Deletes a workspace resource. + + The name is kept for 14 days and cannot be used for another workspace. To remove the workspace completely and release the name, use the --force flag. + + :example: Soft delete a workspace instance. + az monitor log-analytics workspace delete --resource-group MyResourceGroup --workspace-name MyWorkspace + + :example: Completely delete a workspace instance. + az monitor log-analytics workspace delete --force --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + _args_schema.force = AAZBoolArg( + options=["-f", "--force"], + help="Deletes the workspace without the recovery option. A workspace that was deleted with this flag cannot be recovered.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.WorkspacesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class WorkspacesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "force", self.ctx.args.force, + ), + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failback.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failback.py new file mode 100644 index 00000000000..3eb8b35a663 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failback.py @@ -0,0 +1,155 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace failback", +) +class Failback(AAZCommand): + """Deactivates failover for the specified workspace.The failback operation is asynchronous and can take up to 30 minutes to complete.The status of the operation can be checked using the operationId returned in the response. + + :example: Deactive failover for specified workspace + az monitor log-analytics workspace failback --resource-group oiautorest6685 --workspace-name oiautorest6685 + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/failback", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.WorkspacesFailback(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class WorkspacesFailback(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/failback", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +class _FailbackHelper: + """Helper class for Failback""" + + +__all__ = ["Failback"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failover.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failover.py new file mode 100644 index 00000000000..bee7993ca68 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_failover.py @@ -0,0 +1,166 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace failover", +) +class Failover(AAZCommand): + """Activates failover for the specified workspace.The specified replication location must match the location of the enabled replication for this workspace.The failover operation is asynchronous and can take up to 30 minutes to complete.The status of the operation can be checked using the operationId returned in the response. + + :example: Activates failover for the specified workspace + az monitor log-analytics workspace failover --resource-group oiautorest6685 --location eastus --workspace-name oiautorest6685 + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/locations/{}/workspaces/{}/failover", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.location = AAZResourceLocationArg( + required=True, + id_part="name", + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="child_name_1", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.WorkspacesFailover(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class WorkspacesFailover(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/locations/{location}/workspaces/{workspaceName}/failover", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "location", self.ctx.args.location, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +class _FailoverHelper: + """Helper class for Failover""" + + +__all__ = ["Failover"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_schema.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_schema.py new file mode 100644 index 00000000000..5a03829e992 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_schema.py @@ -0,0 +1,256 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace get-schema", +) +class GetSchema(AAZCommand): + """Get the schema for a given workspace. + + Schema represents the internal structure of the workspace, which can be used during the query. + For more information, visit: https://learn.microsoft.com/en-us/rest/api/loganalytics/workspace-schema/get + + :example: Get the schema for a given workspace. + az monitor log-analytics workspace get-schema --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/schema", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SchemaGet(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 SchemaGet(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.OperationalInsights/workspaces/{workspaceName}/schema", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.metadata = AAZObjectType() + _schema_on_200.value = AAZListType() + + metadata = cls._schema_on_200.metadata + metadata.aggregated_grouping_fields = AAZStrType( + serialized_name="aggregatedGroupingFields", + ) + metadata.aggregated_value_field = AAZStrType( + serialized_name="aggregatedValueField", + ) + metadata.core_summaries = AAZListType( + serialized_name="coreSummaries", + ) + metadata.e_tag = AAZStrType( + serialized_name="eTag", + ) + metadata.id = AAZStrType() + metadata.last_updated = AAZStrType( + serialized_name="lastUpdated", + ) + metadata.max = AAZIntType() + metadata.request_id = AAZStrType( + serialized_name="requestId", + ) + metadata.request_time = AAZIntType( + serialized_name="requestTime", + ) + metadata.result_type = AAZStrType( + serialized_name="resultType", + ) + metadata.schema = AAZObjectType() + metadata.sort = AAZListType() + metadata.start_time = AAZStrType( + serialized_name="startTime", + ) + metadata.status = AAZStrType() + metadata.sum = AAZIntType() + metadata.top = AAZIntType() + metadata.total = AAZIntType() + + core_summaries = cls._schema_on_200.metadata.core_summaries + core_summaries.Element = AAZObjectType() + + _element = cls._schema_on_200.metadata.core_summaries.Element + _element.number_of_documents = AAZIntType( + serialized_name="numberOfDocuments", + flags={"required": True}, + ) + _element.status = AAZStrType() + + schema = cls._schema_on_200.metadata.schema + schema.name = AAZStrType() + schema.version = AAZIntType() + + sort = cls._schema_on_200.metadata.sort + sort.Element = AAZObjectType() + + _element = cls._schema_on_200.metadata.sort.Element + _element.name = AAZStrType() + _element.order = AAZStrType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.display_name = AAZStrType( + serialized_name="displayName", + ) + _element.facet = AAZBoolType( + flags={"required": True}, + ) + _element.indexed = AAZBoolType( + flags={"required": True}, + ) + _element.name = AAZStrType() + _element.owner_type = AAZListType( + serialized_name="ownerType", + ) + _element.stored = AAZBoolType( + flags={"required": True}, + ) + _element.type = AAZStrType() + + owner_type = cls._schema_on_200.value.Element.owner_type + owner_type.Element = AAZStrType() + + return cls._schema_on_200 + + +class _GetSchemaHelper: + """Helper class for GetSchema""" + + +__all__ = ["GetSchema"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_shared_keys.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_shared_keys.py new file mode 100644 index 00000000000..9bbf3da9c4e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_get_shared_keys.py @@ -0,0 +1,174 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace get-shared-keys", +) +class GetSharedKeys(AAZCommand): + """Get the shared keys for a workspace. + + :example: Get the shared keys for a workspace. + az monitor log-analytics workspace get-shared-keys --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/sharedkeys", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SharedKeysGetSharedKeys(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 SharedKeysGetSharedKeys(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.OperationalInsights/workspaces/{workspaceName}/sharedKeys", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.primary_shared_key = AAZStrType( + serialized_name="primarySharedKey", + ) + _schema_on_200.secondary_shared_key = AAZStrType( + serialized_name="secondarySharedKey", + ) + + return cls._schema_on_200 + + +class _GetSharedKeysHelper: + """Helper class for GetSharedKeys""" + + +__all__ = ["GetSharedKeys"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list.py new file mode 100644 index 00000000000..8574f3d71ca --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list.py @@ -0,0 +1,603 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list", +) +class List(AAZCommand): + """Get a list of workspaces under a resource group or a subscription. + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.operationalinsights/workspaces", "2025-02-01"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces", "2025-02-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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + condition_1 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + if condition_0: + self.WorkspacesList(ctx=self.ctx)() + if condition_1: + self.WorkspacesListByResourceGroup(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.value, client_flatten=True) + return result + + class WorkspacesList(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}/providers/Microsoft.OperationalInsights/workspaces", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.etag = AAZStrType() + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = cls._schema_on_200.value.Element.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = cls._schema_on_200.value.Element.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = cls._schema_on_200.value.Element.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.value.Element.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class WorkspacesListByResourceGroup(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.OperationalInsights/workspaces", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2025-02-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.etag = AAZStrType() + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.identity = AAZIdentityObjectType() + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.value.Element.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.value.Element.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = cls._schema_on_200.value.Element.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = cls._schema_on_200.value.Element.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = cls._schema_on_200.value.Element.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.value.Element.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_available_service_tier.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_available_service_tier.py new file mode 100644 index 00000000000..752c2f0a8a3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_available_service_tier.py @@ -0,0 +1,196 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list-available-service-tier", +) +class ListAvailableServiceTier(AAZCommand): + """List the available service tiers for the workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/availableservicetiers", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.AvailableServiceTiersListByWorkspace(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 AvailableServiceTiersListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/availableServiceTiers", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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 = AAZListType() + + _schema_on_200 = cls._schema_on_200 + _schema_on_200.Element = AAZObjectType() + + _element = cls._schema_on_200.Element + _element.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + flags={"read_only": True}, + ) + _element.default_retention = AAZIntType( + serialized_name="defaultRetention", + flags={"read_only": True}, + ) + _element.enabled = AAZBoolType( + flags={"read_only": True}, + ) + _element.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + _element.maximum_retention = AAZIntType( + serialized_name="maximumRetention", + flags={"read_only": True}, + ) + _element.minimum_retention = AAZIntType( + serialized_name="minimumRetention", + flags={"read_only": True}, + ) + _element.service_tier = AAZStrType( + serialized_name="serviceTier", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +class _ListAvailableServiceTierHelper: + """Helper class for ListAvailableServiceTier""" + + +__all__ = ["ListAvailableServiceTier"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_deleted_workspaces.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_deleted_workspaces.py new file mode 100644 index 00000000000..05316266dca --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_deleted_workspaces.py @@ -0,0 +1,560 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list-deleted-workspaces", +) +class ListDeletedWorkspaces(AAZCommand): + """Get a list of deleted workspaces that can be recovered in a subscription or a resource group. + + :example: Get a list of deleted workspaces that can be recovered in a resource group + az monitor log-analytics workspace list-deleted-workspaces --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2021-12-01-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.operationalinsights/deletedworkspaces", "2021-12-01-preview"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/deletedworkspaces", "2021-12-01-preview"], + ] + } + + 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.DeletedWorkspacesListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.DeletedWorkspacesList(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.value, client_flatten=True) + return result + + class DeletedWorkspacesListByResourceGroup(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.OperationalInsights/deletedWorkspaces", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2021-12-01-preview", + 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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.e_tag = AAZStrType( + serialized_name="eTag", + ) + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.features = AAZObjectType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + features = cls._schema_on_200.value.Element.properties.features + features.cluster_resource_id = AAZStrType( + serialized_name="clusterResourceId", + nullable=True, + ) + features.disable_local_auth = AAZBoolType( + serialized_name="disableLocalAuth", + nullable=True, + ) + features.enable_data_export = AAZBoolType( + serialized_name="enableDataExport", + nullable=True, + ) + features.enable_log_access_using_only_resource_permissions = AAZBoolType( + serialized_name="enableLogAccessUsingOnlyResourcePermissions", + nullable=True, + ) + features.immediate_purge_data_on30_days = AAZBoolType( + serialized_name="immediatePurgeDataOn30Days", + nullable=True, + ) + + private_link_scoped_resources = cls._schema_on_200.value.Element.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType( + flags={"read_only": True}, + ) + + _element = cls._schema_on_200.value.Element.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.value.Element.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class DeletedWorkspacesList(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}/providers/Microsoft.OperationalInsights/deletedWorkspaces", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2021-12-01-preview", + 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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.e_tag = AAZStrType( + serialized_name="eTag", + ) + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.features = AAZObjectType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + features = cls._schema_on_200.value.Element.properties.features + features.cluster_resource_id = AAZStrType( + serialized_name="clusterResourceId", + nullable=True, + ) + features.disable_local_auth = AAZBoolType( + serialized_name="disableLocalAuth", + nullable=True, + ) + features.enable_data_export = AAZBoolType( + serialized_name="enableDataExport", + nullable=True, + ) + features.enable_log_access_using_only_resource_permissions = AAZBoolType( + serialized_name="enableLogAccessUsingOnlyResourcePermissions", + nullable=True, + ) + features.immediate_purge_data_on30_days = AAZBoolType( + serialized_name="immediatePurgeDataOn30Days", + nullable=True, + ) + + private_link_scoped_resources = cls._schema_on_200.value.Element.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType( + flags={"read_only": True}, + ) + + _element = cls._schema_on_200.value.Element.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"read_only": True}, + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.value.Element.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.value.Element.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + flags={"read_only": True}, + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + flags={"read_only": True}, + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + flags={"read_only": True}, + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + flags={"read_only": True}, + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + flags={"read_only": True}, + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + flags={"read_only": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListDeletedWorkspacesHelper: + """Helper class for ListDeletedWorkspaces""" + + +__all__ = ["ListDeletedWorkspaces"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_link_target.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_link_target.py new file mode 100644 index 00000000000..7b86e6cbd98 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_link_target.py @@ -0,0 +1,155 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list-link-target", +) +class ListLinkTarget(AAZCommand): + """List a list of workspaces which the current user has administrator privileges and are not associated with an Azure Subscription. + """ + + _aaz_info = { + "version": "2015-03-20", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.operationalinsights/linktargets", "2015-03-20"], + ] + } + + 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 "" + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesListLinkTargets(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 WorkspacesListLinkTargets(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}/providers/Microsoft.OperationalInsights/linkTargets", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2015-03-20", + 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 = AAZListType() + + _schema_on_200 = cls._schema_on_200 + _schema_on_200.Element = AAZObjectType() + + _element = cls._schema_on_200.Element + _element.account_name = AAZStrType( + serialized_name="accountName", + ) + _element.customer_id = AAZStrType( + serialized_name="customerId", + ) + _element.location = AAZStrType() + _element.workspace_name = AAZStrType( + serialized_name="workspaceName", + ) + + return cls._schema_on_200 + + +class _ListLinkTargetHelper: + """Helper class for ListLinkTarget""" + + +__all__ = ["ListLinkTarget"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_management_groups.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_management_groups.py new file mode 100644 index 00000000000..cabc297e18b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_management_groups.py @@ -0,0 +1,193 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list-management-groups", +) +class ListManagementGroups(AAZCommand): + """Get a list of management groups connected to a workspace. + + :example: Get a list of management groups connected to a workspace. + az monitor log-analytics workspace list-management-groups --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/managementgroups", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.ManagementGroupsList(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.value, client_flatten=True) + return result + + class ManagementGroupsList(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.OperationalInsights/workspaces/{workspaceName}/managementGroups", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created = AAZStrType() + properties.data_received = AAZStrType( + serialized_name="dataReceived", + ) + properties.id = AAZStrType() + properties.is_gateway = AAZBoolType( + serialized_name="isGateway", + ) + properties.name = AAZStrType() + properties.server_count = AAZIntType( + serialized_name="serverCount", + ) + properties.sku = AAZStrType() + properties.version = AAZStrType() + + return cls._schema_on_200 + + +class _ListManagementGroupsHelper: + """Helper class for ListManagementGroups""" + + +__all__ = ["ListManagementGroups"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_usages.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_usages.py new file mode 100644 index 00000000000..00990bd0492 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_list_usages.py @@ -0,0 +1,192 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace list-usages", +) +class ListUsages(AAZCommand): + """Get a list of usage metrics for a workspace. + + :example: Get a list of usage metrics for a workspace. + az monitor log-analytics workspace list-usages --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/usages", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.UsagesList(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.value, client_flatten=True) + return result + + class UsagesList(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.OperationalInsights/workspaces/{workspaceName}/usages", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.current_value = AAZFloatType( + serialized_name="currentValue", + ) + _element.limit = AAZFloatType() + _element.name = AAZObjectType() + _element.next_reset_time = AAZStrType( + serialized_name="nextResetTime", + ) + _element.quota_period = AAZStrType( + serialized_name="quotaPeriod", + ) + _element.unit = AAZStrType() + + name = cls._schema_on_200.value.Element.name + name.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + name.value = AAZStrType() + + return cls._schema_on_200 + + +class _ListUsagesHelper: + """Helper class for ListUsages""" + + +__all__ = ["ListUsages"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_show.py new file mode 100644 index 00000000000..afaafea1e15 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_show.py @@ -0,0 +1,349 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace show", +) +class Show(AAZCommand): + """Show a workspace instance. + + :example: Show a workspace instance. + az monitor log-analytics workspace show --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(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 WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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.etag = AAZStrType() + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = cls._schema_on_200.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = cls._schema_on_200.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = cls._schema_on_200.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_update.py new file mode 100644 index 00000000000..6321198f06a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_update.py @@ -0,0 +1,669 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace update", +) +class Update(AAZCommand): + """Update a workspace instance. + + :example: Update a workspace instance. + az monitor log-analytics workspace update --resource-group myresourcegroup --retention-time 30 --workspace-name myworkspace + + :example: Update the defaultDataCollectionRuleResourceId of the workspace + az monitor log-analytics workspace update --resource-group myresourcegroup --workspace-name myworkspace --data-collection-rule "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dcrName}". + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + AZ_SUPPORT_GENERIC_UPDATE = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Identity" + + _args_schema = cls._args_schema + _args_schema.identity_type = AAZStrArg( + options=["--type", "--identity-type"], + arg_group="Identity", + help="Type of managed service identity.", + enum={"None": "None", "SystemAssigned": "SystemAssigned", "UserAssigned": "UserAssigned"}, + ) + _args_schema.user_assigned = AAZDictArg( + options=["--user-assigned"], + arg_group="Identity", + help="The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.", + nullable=True, + ) + + user_assigned = cls._args_schema.user_assigned + user_assigned.Element = AAZObjectArg( + nullable=True, + blank={}, + ) + + # define Arg Group "Parameters" + + _args_schema = cls._args_schema + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Parameters", + help="Resource tags.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.data_collection_rule = AAZStrArg( + options=["--data-collection-rule"], + arg_group="Properties", + help="The resource ID of the default Data Collection Rule to use for this workspace. Expected format is - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dcrName}.", + nullable=True, + ) + _args_schema.ingestion_access = AAZStrArg( + options=["--ingestion-access"], + arg_group="Properties", + help="The public network access type to access workspace ingestion.", + nullable=True, + enum={"Disabled": "Disabled", "Enabled": "Enabled"}, + ) + _args_schema.query_access = AAZStrArg( + options=["--query-access"], + arg_group="Properties", + help="The public network access type to access workspace query.", + nullable=True, + enum={"Disabled": "Disabled", "Enabled": "Enabled"}, + ) + _args_schema.retention_time = AAZIntArg( + options=["--retention-time"], + arg_group="Properties", + help="The workspace data retention in days. Allowed values are per pricing plan. See pricing tiers documentation for details.", + nullable=True, + ) + _args_schema.quota = AAZFloatArg( + options=["--quota"], + arg_group="Properties", + help="The workspace daily quota for ingestion in gigabytes. The minimum value is 0.023 and default is -1 which means unlimited.", + nullable=True, + ) + + # define Arg Group "Replication" + + _args_schema = cls._args_schema + _args_schema.replication_enabled = AAZBoolArg( + options=["--replication-enabled"], + arg_group="Replication", + help="Specifies whether the replication is enabled or not. When true, workspace configuration and data is replicated to the specified location. If replication is been enabled, location must be provided.", + nullable=True, + ) + + # define Arg Group "Sku" + + _args_schema = cls._args_schema + _args_schema.capacity_reservation_level = AAZIntArg( + options=["--level", "--capacity-reservation-level"], + arg_group="Sku", + help="The capacity reservation level for this workspace, when CapacityReservation sku is selected. The maximum value is 1000 and must be in multiples of 100. If you want to increase the limit, please contact LAIngestionRate@microsoft.com.", + nullable=True, + enum={"100": 100, "1000": 1000, "10000": 10000, "200": 200, "2000": 2000, "25000": 25000, "300": 300, "400": 400, "500": 500, "5000": 5000, "50000": 50000}, + ) + _args_schema.sku_name = AAZStrArg( + options=["--sku", "--sku-name"], + arg_group="Sku", + help="The name of the SKU.", + enum={"CapacityReservation": "CapacityReservation", "Free": "Free", "LACluster": "LACluster", "PerGB2018": "PerGB2018", "PerNode": "PerNode", "Premium": "Premium", "Standalone": "Standalone", "Standard": "Standard"}, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + yield self.WorkspacesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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() + _UpdateHelper._build_schema_workspace_read(cls._schema_on_200) + + return cls._schema_on_200 + + class WorkspacesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_workspace_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("identity", AAZIdentityObjectType) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + identity = _builder.get(".identity") + if identity is not None: + identity.set_prop("type", AAZStrType, ".identity_type", typ_kwargs={"flags": {"required": True}}) + identity.set_prop("userAssignedIdentities", AAZDictType, ".user_assigned") + + user_assigned_identities = _builder.get(".identity.userAssignedIdentities") + if user_assigned_identities is not None: + user_assigned_identities.set_elements(AAZObjectType, ".") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("defaultDataCollectionRuleResourceId", AAZStrType, ".data_collection_rule") + properties.set_prop("publicNetworkAccessForIngestion", AAZStrType, ".ingestion_access") + properties.set_prop("publicNetworkAccessForQuery", AAZStrType, ".query_access") + properties.set_prop("replication", AAZObjectType) + properties.set_prop("retentionInDays", AAZIntType, ".retention_time", typ_kwargs={"nullable": True}) + properties.set_prop("sku", AAZObjectType) + properties.set_prop("workspaceCapping", AAZObjectType) + + replication = _builder.get(".properties.replication") + if replication is not None: + replication.set_prop("enabled", AAZBoolType, ".replication_enabled") + + sku = _builder.get(".properties.sku") + if sku is not None: + sku.set_prop("capacityReservationLevel", AAZIntType, ".capacity_reservation_level") + sku.set_prop("name", AAZStrType, ".sku_name", typ_kwargs={"flags": {"required": True}}) + + workspace_capping = _builder.get(".properties.workspaceCapping") + if workspace_capping is not None: + workspace_capping.set_prop("dailyQuotaGb", AAZFloatType, ".quota") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_workspace_read = None + + @classmethod + def _build_schema_workspace_read(cls, _schema): + if cls._schema_workspace_read is not None: + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + return + + cls._schema_workspace_read = _schema_workspace_read = AAZObjectType() + + workspace_read = _schema_workspace_read + workspace_read.etag = AAZStrType() + workspace_read.id = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.identity = AAZIdentityObjectType() + workspace_read.location = AAZStrType( + flags={"required": True}, + ) + workspace_read.name = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + workspace_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + workspace_read.tags = AAZDictType() + workspace_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_workspace_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_workspace_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = _schema_workspace_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_workspace_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = _schema_workspace_read.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = _schema_workspace_read.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = _schema_workspace_read.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = _schema_workspace_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_workspace_read.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = _schema_workspace_read.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = _schema_workspace_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = _schema_workspace_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_wait.py new file mode 100644 index 00000000000..3770b076036 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/_wait.py @@ -0,0 +1,345 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(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=False) + return result + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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.etag = AAZStrType() + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.identity = AAZIdentityObjectType() + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = cls._schema_on_200.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = cls._schema_on_200.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = cls._schema_on_200.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = cls._schema_on_200.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = cls._schema_on_200.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = cls._schema_on_200.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = cls._schema_on_200.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = cls._schema_on_200.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__cmd_group.py new file mode 100644 index 00000000000..1616dc217b1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__cmd_group.py @@ -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 log-analytics workspace data-export", +) +class __CMDGroup(AAZCommandGroup): + """Manage data export ruls for log analytics workspace. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_create.py new file mode 100644 index 00000000000..d4410374b39 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_create.py @@ -0,0 +1,301 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace data-export create", +) +class Create(AAZCommand): + """Create a data export rule for a given workspace. + + For more information, see + https://learn.microsoft.com/azure/azure-monitor/platform/logs-data-export + + :example: Create a data export rule for a given workspace. + az monitor log-analytics workspace data-export create -g MyRG --workspace-name MyWS -n MyDataExport --destination --enable -t + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/dataexports/{}", "2020-08-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.data_export_name = AAZStrArg( + options=["-n", "--name", "--data-export-name"], + help="The data export rule name.", + required=True, + id_part="child_name_1", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Destination" + + _args_schema = cls._args_schema + _args_schema.event_hub_name = AAZStrArg( + options=["--event-hub-name"], + arg_group="Destination", + help="Optional. Allows to define an Event Hub name. Not applicable when destination is Storage Account.", + ) + _args_schema.destination = AAZStrArg( + options=["--destination"], + arg_group="Destination", + help="The destination resource ID. It should be a storage account, an event hub namespace. If event hub namespace is provided without --event-hub-name, event hub would be created for each table automatically.", + required=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.enable = AAZBoolArg( + options=["--enable"], + arg_group="Properties", + help="Active when enabled.", + ) + _args_schema.tables = AAZListArg( + options=["-t", "--tables"], + arg_group="Properties", + help="An array of tables to export.", + required=True, + ) + + tables = cls._args_schema.tables + tables.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DataExportsCreateOrUpdate(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 DataExportsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/dataExports/{dataExportName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataExportName", self.ctx.args.data_export_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("destination", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("enable", AAZBoolType, ".enable") + properties.set_prop("tableNames", AAZListType, ".tables", typ_kwargs={"flags": {"required": True}}) + + destination = _builder.get(".properties.destination") + if destination is not None: + destination.set_prop("metaData", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + destination.set_prop("resourceId", AAZStrType, ".destination", typ_kwargs={"flags": {"required": True}}) + + meta_data = _builder.get(".properties.destination.metaData") + if meta_data is not None: + meta_data.set_prop("eventHubName", AAZStrType, ".event_hub_name") + + table_names = _builder.get(".properties.tableNames") + if table_names is not None: + table_names.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + ) + properties.data_export_id = AAZStrType( + serialized_name="dataExportId", + ) + properties.destination = AAZObjectType( + flags={"required": True}, + ) + properties.enable = AAZBoolType() + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + ) + properties.table_names = AAZListType( + serialized_name="tableNames", + flags={"required": True}, + ) + + destination = cls._schema_on_200_201.properties.destination + destination.meta_data = AAZObjectType( + serialized_name="metaData", + flags={"client_flatten": True}, + ) + destination.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + destination.type = AAZStrType( + flags={"read_only": True}, + ) + + meta_data = cls._schema_on_200_201.properties.destination.meta_data + meta_data.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + + table_names = cls._schema_on_200_201.properties.table_names + table_names.Element = AAZStrType() + + return cls._schema_on_200_201 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_delete.py new file mode 100644 index 00000000000..172db49f8a7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_delete.py @@ -0,0 +1,142 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace data-export delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a data export rule for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/dataexports/{}", "2020-08-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.data_export_name = AAZStrArg( + options=["-n", "--name", "--data-export-name"], + help="The data export rule name.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DataExportsDelete(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class DataExportsDelete(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.OperationalInsights/workspaces/{workspaceName}/dataExports/{dataExportName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataExportName", self.ctx.args.data_export_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_list.py new file mode 100644 index 00000000000..6297e4d147b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_list.py @@ -0,0 +1,219 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace data-export list", +) +class List(AAZCommand): + """List all data export ruleses for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/dataexports", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DataExportsListByWorkspace(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.value, client_flatten=True) + return result + + class DataExportsListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/dataExports", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + ) + properties.data_export_id = AAZStrType( + serialized_name="dataExportId", + ) + properties.destination = AAZObjectType( + flags={"required": True}, + ) + properties.enable = AAZBoolType() + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + ) + properties.table_names = AAZListType( + serialized_name="tableNames", + flags={"required": True}, + ) + + destination = cls._schema_on_200.value.Element.properties.destination + destination.meta_data = AAZObjectType( + serialized_name="metaData", + flags={"client_flatten": True}, + ) + destination.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + destination.type = AAZStrType( + flags={"read_only": True}, + ) + + meta_data = cls._schema_on_200.value.Element.properties.destination.meta_data + meta_data.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + + table_names = cls._schema_on_200.value.Element.properties.table_names + table_names.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_show.py new file mode 100644 index 00000000000..c5bd98e4235 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_show.py @@ -0,0 +1,224 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace data-export show", +) +class Show(AAZCommand): + """Show a data export rule for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/dataexports/{}", "2020-08-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.data_export_name = AAZStrArg( + options=["-n", "--name", "--data-export-name"], + help="The data export rule name.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DataExportsGet(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 DataExportsGet(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.OperationalInsights/workspaces/{workspaceName}/dataExports/{dataExportName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataExportName", self.ctx.args.data_export_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + ) + properties.data_export_id = AAZStrType( + serialized_name="dataExportId", + ) + properties.destination = AAZObjectType( + flags={"required": True}, + ) + properties.enable = AAZBoolType() + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + ) + properties.table_names = AAZListType( + serialized_name="tableNames", + flags={"required": True}, + ) + + destination = cls._schema_on_200.properties.destination + destination.meta_data = AAZObjectType( + serialized_name="metaData", + flags={"client_flatten": True}, + ) + destination.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + destination.type = AAZStrType( + flags={"read_only": True}, + ) + + meta_data = cls._schema_on_200.properties.destination.meta_data + meta_data.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + + table_names = cls._schema_on_200.properties.table_names + table_names.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_update.py new file mode 100644 index 00000000000..d7a44bceeee --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/data_export/_update.py @@ -0,0 +1,442 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace data-export update", +) +class Update(AAZCommand): + """Update a data export rule for a given workspace. + + For more information, see + https://learn.microsoft.com/azure/azure-monitor/platform/logs-data-export + + :example: Update a data export rule for a given workspace. + az monitor log-analytics workspace data-export update -g MyRG --workspace-name MyWS -n MyDataExport --destination -t
--enable false + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/dataexports/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.data_export_name = AAZStrArg( + options=["-n", "--name", "--data-export-name"], + help="The data export rule name.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Destination" + + _args_schema = cls._args_schema + _args_schema.event_hub_name = AAZStrArg( + options=["--event-hub-name"], + arg_group="Destination", + help="Optional. Allows to define an Event Hub name. Not applicable when destination is Storage Account.", + nullable=True, + ) + _args_schema.destination = AAZStrArg( + options=["--destination"], + arg_group="Destination", + help="The destination resource ID. It should be a storage account, an event hub namespace. If event hub namespace is provided without --event-hub-name, event hub would be created for each table automatically.", + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.enable = AAZBoolArg( + options=["--enable"], + arg_group="Properties", + help="Active when enabled.", + nullable=True, + ) + _args_schema.tables = AAZListArg( + options=["-t", "--tables"], + arg_group="Properties", + help="An array of tables to export.", + ) + + tables = cls._args_schema.tables + tables.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.DataExportsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.DataExportsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class DataExportsGet(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.OperationalInsights/workspaces/{workspaceName}/dataExports/{dataExportName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataExportName", self.ctx.args.data_export_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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() + _build_schema_data_export_read(cls._schema_on_200) + + return cls._schema_on_200 + + class DataExportsCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/dataExports/{dataExportName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataExportName", self.ctx.args.data_export_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _build_schema_data_export_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("destination", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("enable", AAZBoolType, ".enable") + properties.set_prop("tableNames", AAZListType, ".tables", typ_kwargs={"flags": {"required": True}}) + + destination = _builder.get(".properties.destination") + if destination is not None: + destination.set_prop("metaData", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + destination.set_prop("resourceId", AAZStrType, ".destination", typ_kwargs={"flags": {"required": True}}) + + meta_data = _builder.get(".properties.destination.metaData") + if meta_data is not None: + meta_data.set_prop("eventHubName", AAZStrType, ".event_hub_name") + + table_names = _builder.get(".properties.tableNames") + if table_names is not None: + table_names.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_data_export_read = None + + +def _build_schema_data_export_read(_schema): + global _schema_data_export_read + if _schema_data_export_read is not None: + _schema.id = _schema_data_export_read.id + _schema.name = _schema_data_export_read.name + _schema.properties = _schema_data_export_read.properties + _schema.type = _schema_data_export_read.type + return + + _schema_data_export_read = AAZObjectType() + + data_export_read = _schema_data_export_read + data_export_read.id = AAZStrType( + flags={"read_only": True}, + ) + data_export_read.name = AAZStrType( + flags={"read_only": True}, + ) + data_export_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + data_export_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_data_export_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + ) + properties.data_export_id = AAZStrType( + serialized_name="dataExportId", + ) + properties.destination = AAZObjectType( + flags={"required": True}, + ) + properties.enable = AAZBoolType() + properties.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + ) + properties.table_names = AAZListType( + serialized_name="tableNames", + flags={"required": True}, + ) + + destination = _schema_data_export_read.properties.destination + destination.meta_data = AAZObjectType( + serialized_name="metaData", + flags={"client_flatten": True}, + ) + destination.resource_id = AAZStrType( + serialized_name="resourceId", + flags={"required": True}, + ) + destination.type = AAZStrType( + flags={"read_only": True}, + ) + + meta_data = _schema_data_export_read.properties.destination.meta_data + meta_data.event_hub_name = AAZStrType( + serialized_name="eventHubName", + ) + + table_names = _schema_data_export_read.properties.table_names + table_names.Element = AAZStrType() + + _schema.id = _schema_data_export_read.id + _schema.name = _schema_data_export_read.name + _schema.properties = _schema_data_export_read.properties + _schema.type = _schema_data_export_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__cmd_group.py new file mode 100644 index 00000000000..387cefc0004 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__cmd_group.py @@ -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 log-analytics workspace identity", +) +class __CMDGroup(AAZCommandGroup): + """Manage Identity + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py new file mode 100644 index 00000000000..3a074471e35 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py @@ -0,0 +1,15 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._assign import * +from ._remove import * +from ._show import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_assign.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_assign.py new file mode 100644 index 00000000000..c44ae22ab31 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_assign.py @@ -0,0 +1,552 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace identity assign", +) +class Assign(AAZCommand): + """Assign the user or system managed identities. + + :example: Add a system assigned managed identity to an existing workspace + az monitor log-analytics workspace identity assign --name workspace --resource-group rg --system-assigned + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01", "identity"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Parameters.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="Parameters.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="Parameters.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + yield self.WorkspacesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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() + _AssignHelper._build_schema_workspace_read(cls._schema_on_200) + + return cls._schema_on_200 + + class WorkspacesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _AssignHelper._build_schema_workspace_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "assign"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "assign"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _AssignHelper: + """Helper class for Assign""" + + _schema_workspace_read = None + + @classmethod + def _build_schema_workspace_read(cls, _schema): + if cls._schema_workspace_read is not None: + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + return + + cls._schema_workspace_read = _schema_workspace_read = AAZObjectType() + + workspace_read = _schema_workspace_read + workspace_read.etag = AAZStrType() + workspace_read.id = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.identity = AAZIdentityObjectType() + workspace_read.location = AAZStrType( + flags={"required": True}, + ) + workspace_read.name = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + workspace_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + workspace_read.tags = AAZDictType() + workspace_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_workspace_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_workspace_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = _schema_workspace_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_workspace_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = _schema_workspace_read.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = _schema_workspace_read.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = _schema_workspace_read.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = _schema_workspace_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_workspace_read.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = _schema_workspace_read.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = _schema_workspace_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = _schema_workspace_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + + +__all__ = ["Assign"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_remove.py new file mode 100644 index 00000000000..1860d579953 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_remove.py @@ -0,0 +1,549 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace identity remove", +) +class Remove(AAZCommand): + """Remove the user or system managed identities. + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01", "identity"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Parameters.identity" + + _args_schema = cls._args_schema + _args_schema.mi_system_assigned = AAZStrArg( + options=["--system-assigned", "--mi-system-assigned"], + arg_group="Parameters.identity", + help="Set the system managed identity.", + blank="True", + ) + _args_schema.mi_user_assigned = AAZListArg( + options=["--user-assigned", "--mi-user-assigned"], + arg_group="Parameters.identity", + help="Set the user managed identities.", + blank=[], + ) + + mi_user_assigned = cls._args_schema.mi_user_assigned + mi_user_assigned.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + yield self.WorkspacesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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() + _RemoveHelper._build_schema_workspace_read(cls._schema_on_200) + + return cls._schema_on_200 + + class WorkspacesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _RemoveHelper._build_schema_workspace_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZIdentityObjectType + ) + _builder.set_prop("userAssigned", AAZListType, ".mi_user_assigned", typ_kwargs={"flags": {"action": "remove"}}) + _builder.set_prop("systemAssigned", AAZStrType, ".mi_system_assigned", typ_kwargs={"flags": {"action": "remove"}}) + + user_assigned = _builder.get(".userAssigned") + if user_assigned is not None: + user_assigned.set_elements(AAZStrType, ".") + + return _instance_value + + +class _RemoveHelper: + """Helper class for Remove""" + + _schema_workspace_read = None + + @classmethod + def _build_schema_workspace_read(cls, _schema): + if cls._schema_workspace_read is not None: + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + return + + cls._schema_workspace_read = _schema_workspace_read = AAZObjectType() + + workspace_read = _schema_workspace_read + workspace_read.etag = AAZStrType() + workspace_read.id = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.identity = AAZIdentityObjectType() + workspace_read.location = AAZStrType( + flags={"required": True}, + ) + workspace_read.name = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + workspace_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + workspace_read.tags = AAZDictType() + workspace_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_workspace_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_workspace_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = _schema_workspace_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_workspace_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = _schema_workspace_read.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = _schema_workspace_read.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = _schema_workspace_read.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = _schema_workspace_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_workspace_read.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = _schema_workspace_read.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = _schema_workspace_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = _schema_workspace_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + + +__all__ = ["Remove"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_show.py new file mode 100644 index 00000000000..1a3ac1e4dd9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_show.py @@ -0,0 +1,386 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace identity show", +) +class Show(AAZCommand): + """Show the details of managed identities. + """ + + _aaz_info = { + "version": "2025-02-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01", "identity"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self.SubresourceSelector(ctx=self.ctx, name="subresource") + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(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.selectors.subresource.required(), client_flatten=True) + return result + + class SubresourceSelector(AAZJsonSelector): + + def _get(self): + result = self.ctx.vars.instance + return result.identity + + def _set(self, value): + result = self.ctx.vars.instance + result.identity = value + return + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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() + _ShowHelper._build_schema_workspace_read(cls._schema_on_200) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_workspace_read = None + + @classmethod + def _build_schema_workspace_read(cls, _schema): + if cls._schema_workspace_read is not None: + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + return + + cls._schema_workspace_read = _schema_workspace_read = AAZObjectType() + + workspace_read = _schema_workspace_read + workspace_read.etag = AAZStrType() + workspace_read.id = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.identity = AAZIdentityObjectType() + workspace_read.location = AAZStrType( + flags={"required": True}, + ) + workspace_read.name = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + workspace_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + workspace_read.tags = AAZDictType() + workspace_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_workspace_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_workspace_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = _schema_workspace_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_workspace_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = _schema_workspace_read.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = _schema_workspace_read.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = _schema_workspace_read.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = _schema_workspace_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_workspace_read.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = _schema_workspace_read.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = _schema_workspace_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = _schema_workspace_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_wait.py new file mode 100644 index 00000000000..45244e47638 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/identity/_wait.py @@ -0,0 +1,374 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace identity wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}", "2025-02-01", "identity"], + ] + } + + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--name", "--workspace-name"], + help="Name of the Log Analytics Workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.WorkspacesGet(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=False) + return result + + class WorkspacesGet(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.OperationalInsights/workspaces/{workspaceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2025-02-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() + _WaitHelper._build_schema_workspace_read(cls._schema_on_200) + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + _schema_workspace_read = None + + @classmethod + def _build_schema_workspace_read(cls, _schema): + if cls._schema_workspace_read is not None: + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + return + + cls._schema_workspace_read = _schema_workspace_read = AAZObjectType() + + workspace_read = _schema_workspace_read + workspace_read.etag = AAZStrType() + workspace_read.id = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.identity = AAZIdentityObjectType() + workspace_read.location = AAZStrType( + flags={"required": True}, + ) + workspace_read.name = AAZStrType( + flags={"read_only": True}, + ) + workspace_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + workspace_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + workspace_read.tags = AAZDictType() + workspace_read.type = AAZStrType( + flags={"read_only": True}, + ) + + identity = _schema_workspace_read.identity + identity.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + identity.tenant_id = AAZStrType( + serialized_name="tenantId", + flags={"read_only": True}, + ) + identity.type = AAZStrType( + flags={"required": True}, + ) + identity.user_assigned_identities = AAZDictType( + serialized_name="userAssignedIdentities", + ) + + user_assigned_identities = _schema_workspace_read.identity.user_assigned_identities + user_assigned_identities.Element = AAZObjectType() + + _element = _schema_workspace_read.identity.user_assigned_identities.Element + _element.client_id = AAZStrType( + serialized_name="clientId", + flags={"read_only": True}, + ) + _element.principal_id = AAZStrType( + serialized_name="principalId", + flags={"read_only": True}, + ) + + properties = _schema_workspace_read.properties + properties.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + properties.customer_id = AAZStrType( + serialized_name="customerId", + flags={"read_only": True}, + ) + properties.default_data_collection_rule_resource_id = AAZStrType( + serialized_name="defaultDataCollectionRuleResourceId", + ) + properties.failover = AAZObjectType() + properties.features = AAZFreeFormDictType() + properties.force_cmk_for_query = AAZBoolType( + serialized_name="forceCmkForQuery", + ) + properties.modified_date = AAZStrType( + serialized_name="modifiedDate", + flags={"read_only": True}, + ) + properties.private_link_scoped_resources = AAZListType( + serialized_name="privateLinkScopedResources", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.public_network_access_for_ingestion = AAZStrType( + serialized_name="publicNetworkAccessForIngestion", + ) + properties.public_network_access_for_query = AAZStrType( + serialized_name="publicNetworkAccessForQuery", + ) + properties.replication = AAZObjectType() + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + nullable=True, + ) + properties.sku = AAZObjectType() + properties.workspace_capping = AAZObjectType( + serialized_name="workspaceCapping", + ) + + failover = _schema_workspace_read.properties.failover + failover.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + failover.state = AAZStrType( + flags={"read_only": True}, + ) + + private_link_scoped_resources = _schema_workspace_read.properties.private_link_scoped_resources + private_link_scoped_resources.Element = AAZObjectType() + + _element = _schema_workspace_read.properties.private_link_scoped_resources.Element + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.scope_id = AAZStrType( + serialized_name="scopeId", + ) + + replication = _schema_workspace_read.properties.replication + replication.created_date = AAZStrType( + serialized_name="createdDate", + flags={"read_only": True}, + ) + replication.enabled = AAZBoolType() + replication.last_modified_date = AAZStrType( + serialized_name="lastModifiedDate", + flags={"read_only": True}, + ) + replication.location = AAZStrType() + replication.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + sku = _schema_workspace_read.properties.sku + sku.capacity_reservation_level = AAZIntType( + serialized_name="capacityReservationLevel", + ) + sku.last_sku_update = AAZStrType( + serialized_name="lastSkuUpdate", + flags={"read_only": True}, + ) + sku.name = AAZStrType( + flags={"required": True}, + ) + + workspace_capping = _schema_workspace_read.properties.workspace_capping + workspace_capping.daily_quota_gb = AAZFloatType( + serialized_name="dailyQuotaGb", + ) + workspace_capping.data_ingestion_status = AAZStrType( + serialized_name="dataIngestionStatus", + flags={"read_only": True}, + ) + workspace_capping.quota_next_reset_time = AAZStrType( + serialized_name="quotaNextResetTime", + flags={"read_only": True}, + ) + + system_data = _schema_workspace_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + tags = _schema_workspace_read.tags + tags.Element = AAZStrType() + + _schema.etag = cls._schema_workspace_read.etag + _schema.id = cls._schema_workspace_read.id + _schema.identity = cls._schema_workspace_read.identity + _schema.location = cls._schema_workspace_read.location + _schema.name = cls._schema_workspace_read.name + _schema.properties = cls._schema_workspace_read.properties + _schema.system_data = cls._schema_workspace_read.system_data + _schema.tags = cls._schema_workspace_read.tags + _schema.type = cls._schema_workspace_read.type + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__cmd_group.py new file mode 100644 index 00000000000..5ecf353c73a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__cmd_group.py @@ -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. +# +# Code generated by aaz-dev-tools +# -------------------------------------------------------------------------------------------- + +# pylint: skip-file +# flake8: noqa + +from azure.cli.core.aaz import * + + +@register_command_group( + "monitor log-analytics workspace linked-service", +) +class __CMDGroup(AAZCommandGroup): + """Manage linked service for log analytics workspace. + + Linked services is used to define a relation from the workspace to another Azure resource. Log Analytics and Azure resources then leverage this connection in their operations. Example uses of Linked Services in Log Analytics workspace are Automation account and workspace association to CMK. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py new file mode 100644 index 00000000000..db73033039b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_create.py new file mode 100644 index 00000000000..1ae15504916 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_create.py @@ -0,0 +1,264 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service create", +) +class Create(AAZCommand): + """Create a linked service. + + :example: Create a linked service. + az monitor log-analytics workspace linked-service create -g MyResourceGroup -n cluster --workspace-name MyWorkspace --write-access-resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MyResourceGroup/providers/Microsoft.OperationalInsights/clusters/MyCluster + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.linked_service_name = AAZStrArg( + options=["-n", "--name", "--linked-service-name"], + help="Name of the linkedServices resource. Supported values: cluster, automation.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Resource tags.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.resource_id = AAZStrArg( + options=["--resource-id"], + arg_group="Properties", + help="The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require read access", + ) + _args_schema.write_access_resource_id = AAZStrArg( + options=["--write-access-resource-id"], + arg_group="Properties", + help="The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require write access", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.LinkedServicesCreateOrUpdate(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 LinkedServicesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("resourceId", AAZStrType, ".resource_id") + properties.set_prop("writeAccessResourceId", AAZStrType, ".write_access_resource_id") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_delete.py new file mode 100644 index 00000000000..6d2090537cf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_delete.py @@ -0,0 +1,232 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a linked service. + + :example: Delete a linked service. + az monitor log-analytics workspace linked-service delete -g MyResourceGroup -n cluster --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.linked_service_name = AAZStrArg( + options=["-n", "--name", "--linked-service-name"], + help="Name of the linkedServices resource. Supported values: cluster, automation.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.LinkedServicesDelete(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 LinkedServicesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + def on_204(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_list.py new file mode 100644 index 00000000000..cdfeeec69fe --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_list.py @@ -0,0 +1,197 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service list", +) +class List(AAZCommand): + """Get all the linked services in a workspace. + + :example: Get all the linked services in a workspace. + az monitor log-analytics workspace linked-service list -g MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedServicesListByWorkspace(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.value, client_flatten=True) + return result + + class LinkedServicesListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/linkedServices", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_show.py new file mode 100644 index 00000000000..4233dca802c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_show.py @@ -0,0 +1,202 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service show", +) +class Show(AAZCommand): + """Show the properties of a linked service. + + :example: Show the properties of a linked service. + az monitor log-analytics workspace linked-service show -g MyResourceGroup -n cluster --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices/{}", "2020-08-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.linked_service_name = AAZStrArg( + options=["-n", "--name", "--linked-service-name"], + help="Name of the linkedServices resource. Supported values: cluster, automation.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedServicesGet(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 LinkedServicesGet(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.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_update.py new file mode 100644 index 00000000000..4d72ae2aee1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_update.py @@ -0,0 +1,415 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service update", +) +class Update(AAZCommand): + """Update a linked service. + + :example: Update a linked service. + az monitor log-analytics workspace linked-service update -g MyResourceGroup -n cluster --workspace-name MyWorkspace --write-access-resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/MyResourceGroup/providers/Microsoft.OperationalInsights/clusters/MyCluster + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + AZ_SUPPORT_GENERIC_UPDATE = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.linked_service_name = AAZStrArg( + options=["-n", "--name", "--linked-service-name"], + help="Name of the linkedServices resource. Supported values: cluster, automation.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Resource tags.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.resource_id = AAZStrArg( + options=["--resource-id"], + arg_group="Properties", + help="The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require read access", + nullable=True, + ) + _args_schema.write_access_resource_id = AAZStrArg( + options=["--write-access-resource-id"], + arg_group="Properties", + help="The resource id of the resource that will be linked to the workspace. This should be used for linking resources which require write access", + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedServicesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + yield self.LinkedServicesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class LinkedServicesGet(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.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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() + _build_schema_linked_service_read(cls._schema_on_200) + + return cls._schema_on_200 + + class LinkedServicesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _build_schema_linked_service_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("resourceId", AAZStrType, ".resource_id") + properties.set_prop("writeAccessResourceId", AAZStrType, ".write_access_resource_id") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_linked_service_read = None + + +def _build_schema_linked_service_read(_schema): + global _schema_linked_service_read + if _schema_linked_service_read is not None: + _schema.id = _schema_linked_service_read.id + _schema.name = _schema_linked_service_read.name + _schema.properties = _schema_linked_service_read.properties + _schema.tags = _schema_linked_service_read.tags + _schema.type = _schema_linked_service_read.type + return + + _schema_linked_service_read = AAZObjectType() + + linked_service_read = _schema_linked_service_read + linked_service_read.id = AAZStrType( + flags={"read_only": True}, + ) + linked_service_read.name = AAZStrType( + flags={"read_only": True}, + ) + linked_service_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + linked_service_read.tags = AAZDictType() + linked_service_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_linked_service_read.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = _schema_linked_service_read.tags + tags.Element = AAZStrType() + + _schema.id = _schema_linked_service_read.id + _schema.name = _schema_linked_service_read.name + _schema.properties = _schema_linked_service_read.properties + _schema.tags = _schema_linked_service_read.tags + _schema.type = _schema_linked_service_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_wait.py new file mode 100644 index 00000000000..101b0aaf1a7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_service/_wait.py @@ -0,0 +1,198 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-service wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedservices/{}", "2020-08-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.linked_service_name = AAZStrArg( + options=["-n", "--name", "--linked-service-name"], + help="Name of the linkedServices resource. Supported values: cluster, automation.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedServicesGet(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=False) + return result + + class LinkedServicesGet(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.OperationalInsights/workspaces/{workspaceName}/linkedServices/{linkedServiceName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "linkedServiceName", self.ctx.args.linked_service_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + ) + properties.resource_id = AAZStrType( + serialized_name="resourceId", + ) + properties.write_access_resource_id = AAZStrType( + serialized_name="writeAccessResourceId", + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__cmd_group.py new file mode 100644 index 00000000000..e8eb0ad598f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__cmd_group.py @@ -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 log-analytics workspace linked-storage", +) +class __CMDGroup(AAZCommandGroup): + """Manage linked storage account for log analytics workspace. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_create.py new file mode 100644 index 00000000000..6dcc41b90d3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_create.py @@ -0,0 +1,239 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-storage create", +) +class Create(AAZCommand): + """Create some linked storage accounts for log analytics workspace. + + :example: Create two linked storage accounts for a log analytics workspace using the name of the storage account. + az monitor log-analytics workspace linked-storage create --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts StorageAccount1 StorageAccount2 + + :example: Create one linked storage accounts for a log analytics workspace using the resource id of the storage account. + az monitor log-analytics workspace linked-storage create --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace --storage-accounts /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.Storage/storageAccounts/cli000001 + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedstorageaccounts/{}", "2020-08-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.data_source_type = AAZStrArg( + options=["--type", "--data-source-type"], + help="Data source type for the linked storage account.", + required=True, + id_part="child_name_1", + enum={"Alerts": "Alerts", "AzureWatson": "AzureWatson", "CustomLogs": "CustomLogs", "Ingestion": "Ingestion", "Query": "Query"}, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.storage_accounts = AAZListArg( + options=["--storage-accounts"], + arg_group="Properties", + help="List of Name or ID of Azure Storage Account.", + required=True, + ) + + storage_accounts = cls._args_schema.storage_accounts + storage_accounts.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedStorageAccountsCreateOrUpdate(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 LinkedStorageAccountsCreateOrUpdate(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataSourceType", self.ctx.args.data_source_type, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("storageAccountIds", AAZListType, ".storage_accounts", typ_kwargs={"flags": {"required": True}}) + + storage_account_ids = _builder.get(".properties.storageAccountIds") + if storage_account_ids is not None: + storage_account_ids.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.data_source_type = AAZStrType( + serialized_name="dataSourceType", + flags={"read_only": True}, + ) + properties.storage_account_ids = AAZListType( + serialized_name="storageAccountIds", + flags={"required": True}, + ) + + storage_account_ids = cls._schema_on_200.properties.storage_account_ids + storage_account_ids.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_delete.py new file mode 100644 index 00000000000..e6655935c0c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_delete.py @@ -0,0 +1,146 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-storage delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete all linked storage accounts with specific data source type for log analytics workspace. + + :example: Delete all linked storage accounts with a specific type for a log analytics workspace + az monitor log-analytics workspace linked-storage delete --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedstorageaccounts/{}", "2020-08-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.data_source_type = AAZStrArg( + options=["--type", "--data-source-type"], + help="Data source type for the linked storage account.", + required=True, + id_part="child_name_1", + enum={"Alerts": "Alerts", "AzureWatson": "AzureWatson", "CustomLogs": "CustomLogs", "Ingestion": "Ingestion", "Query": "Query"}, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedStorageAccountsDelete(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class LinkedStorageAccountsDelete(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataSourceType", self.ctx.args.data_source_type, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_list.py new file mode 100644 index 00000000000..69fd4f9daf3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_list.py @@ -0,0 +1,195 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-storage list", +) +class List(AAZCommand): + """List all linked storage accounts for a log analytics workspace. + + :example: List all linked storage accounts for a log analytics workspace. + az monitor log-analytics workspace linked-storage list --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedstorageaccounts", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedStorageAccountsListByWorkspace(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.value, client_flatten=True) + return result + + class LinkedStorageAccountsListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.data_source_type = AAZStrType( + serialized_name="dataSourceType", + flags={"read_only": True}, + ) + properties.storage_account_ids = AAZListType( + serialized_name="storageAccountIds", + flags={"required": True}, + ) + + storage_account_ids = cls._schema_on_200.value.Element.properties.storage_account_ids + storage_account_ids.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_show.py new file mode 100644 index 00000000000..9d9fc37105f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_show.py @@ -0,0 +1,201 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace linked-storage show", +) +class Show(AAZCommand): + """Show all linked storage accounts with specific data source type for a log analytics workspace. + + :example: Show all linked storage accounts with a specific type for a log analytics workspace + az monitor log-analytics workspace linked-storage show --type AzureWatson -g MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedstorageaccounts/{}", "2020-08-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.data_source_type = AAZStrArg( + options=["--type", "--data-source-type"], + help="Data source type for the linked storage account.", + required=True, + id_part="child_name_1", + enum={"Alerts": "Alerts", "AzureWatson": "AzureWatson", "CustomLogs": "CustomLogs", "Ingestion": "Ingestion", "Query": "Query"}, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedStorageAccountsGet(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 LinkedStorageAccountsGet(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataSourceType", self.ctx.args.data_source_type, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.data_source_type = AAZStrType( + serialized_name="dataSourceType", + flags={"read_only": True}, + ) + properties.storage_account_ids = AAZListType( + serialized_name="storageAccountIds", + flags={"required": True}, + ) + + storage_account_ids = cls._schema_on_200.properties.storage_account_ids + storage_account_ids.Element = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_update.py new file mode 100644 index 00000000000..7a98aafdedf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/linked_storage/_update.py @@ -0,0 +1,375 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Update(AAZCommand): + """Update a link relation between current workspace and a group of storage accounts of a specific data source type. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/linkedstorageaccounts/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.data_source_type = AAZStrArg( + options=["--type", "--data-source-type"], + help="Data source type for the linked storage account.", + required=True, + id_part="child_name_1", + enum={"Alerts": "Alerts", "AzureWatson": "AzureWatson", "CustomLogs": "CustomLogs", "Ingestion": "Ingestion", "Query": "Query"}, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["-n", "--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.storage_accounts = AAZListArg( + options=["--storage-accounts"], + arg_group="Properties", + help="List of Name or ID of Azure Storage Account.", + ) + + storage_accounts = cls._args_schema.storage_accounts + storage_accounts.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LinkedStorageAccountsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.LinkedStorageAccountsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class LinkedStorageAccountsGet(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataSourceType", self.ctx.args.data_source_type, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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() + _build_schema_linked_storage_accounts_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class LinkedStorageAccountsCreateOrUpdate(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.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "dataSourceType", self.ctx.args.data_source_type, + 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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _build_schema_linked_storage_accounts_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("storageAccountIds", AAZListType, ".storage_accounts", typ_kwargs={"flags": {"required": True}}) + + storage_account_ids = _builder.get(".properties.storageAccountIds") + if storage_account_ids is not None: + storage_account_ids.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_linked_storage_accounts_resource_read = None + + +def _build_schema_linked_storage_accounts_resource_read(_schema): + global _schema_linked_storage_accounts_resource_read + if _schema_linked_storage_accounts_resource_read is not None: + _schema.id = _schema_linked_storage_accounts_resource_read.id + _schema.name = _schema_linked_storage_accounts_resource_read.name + _schema.properties = _schema_linked_storage_accounts_resource_read.properties + _schema.type = _schema_linked_storage_accounts_resource_read.type + return + + _schema_linked_storage_accounts_resource_read = AAZObjectType() + + linked_storage_accounts_resource_read = _schema_linked_storage_accounts_resource_read + linked_storage_accounts_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + linked_storage_accounts_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + linked_storage_accounts_resource_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + linked_storage_accounts_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_linked_storage_accounts_resource_read.properties + properties.data_source_type = AAZStrType( + serialized_name="dataSourceType", + flags={"read_only": True}, + ) + properties.storage_account_ids = AAZListType( + serialized_name="storageAccountIds", + flags={"required": True}, + ) + + storage_account_ids = _schema_linked_storage_accounts_resource_read.properties.storage_account_ids + storage_account_ids.Element = AAZStrType() + + _schema.id = _schema_linked_storage_accounts_resource_read.id + _schema.name = _schema_linked_storage_accounts_resource_read.name + _schema.properties = _schema_linked_storage_accounts_resource_read.properties + _schema.type = _schema_linked_storage_accounts_resource_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__cmd_group.py new file mode 100644 index 00000000000..6c2798de80e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__cmd_group.py @@ -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 log-analytics workspace pack", +) +class __CMDGroup(AAZCommandGroup): + """Manage intelligent packs for log analytics workspace. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py new file mode 100644 index 00000000000..edd1a889c3c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._disable import * +from ._enable import * +from ._list import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_disable.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_disable.py new file mode 100644 index 00000000000..060ec6079a1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_disable.py @@ -0,0 +1,142 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace pack disable", +) +class Disable(AAZCommand): + """Disable an intelligence pack for a given workspace. + + :example: Disable an intelligence pack for a given workspace. + az monitor log-analytics workspace pack disable --name MyIntelligencePack --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/intelligencepacks/{}/disable", "2020-08-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.intelligence_pack_name = AAZStrArg( + options=["-n", "--name", "--intelligence-pack-name"], + help="The name of the intelligence pack to be enabled.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.IntelligencePacksDisable(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class IntelligencePacksDisable(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.OperationalInsights/workspaces/{workspaceName}/intelligencePacks/{intelligencePackName}/Disable", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "intelligencePackName", self.ctx.args.intelligence_pack_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +__all__ = ["Disable"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_enable.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_enable.py new file mode 100644 index 00000000000..b9902c2d0be --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_enable.py @@ -0,0 +1,142 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace pack enable", +) +class Enable(AAZCommand): + """Enable an intelligence pack for a given workspace. + + :example: Enable an intelligence pack for a given workspace. + az monitor log-analytics workspace pack enable --name MyIntelligencePack --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/intelligencepacks/{}/enable", "2020-08-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.intelligence_pack_name = AAZStrArg( + options=["-n", "--name", "--intelligence-pack-name"], + help="The name of the intelligence pack to be enabled.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.IntelligencePacksEnable(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class IntelligencePacksEnable(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.OperationalInsights/workspaces/{workspaceName}/intelligencePacks/{intelligencePackName}/Enable", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "intelligencePackName", self.ctx.args.intelligence_pack_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, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +__all__ = ["Enable"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_list.py new file mode 100644 index 00000000000..fbdb08eaca7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/pack/_list.py @@ -0,0 +1,172 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace pack list", +) +class List(AAZCommand): + """List all the intelligence packs possible and whether they are enabled or disabled for a given workspace. + + :example: List all the intelligence packs possible and whether they are enabled or disabled for a given workspace. + az monitor log-analytics workspace pack list --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/intelligencepacks", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.IntelligencePacksList(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 IntelligencePacksList(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.OperationalInsights/workspaces/{workspaceName}/intelligencePacks", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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 = AAZListType() + + _schema_on_200 = cls._schema_on_200 + _schema_on_200.Element = AAZObjectType() + + _element = cls._schema_on_200.Element + _element.display_name = AAZStrType( + serialized_name="displayName", + ) + _element.enabled = AAZBoolType() + _element.name = AAZStrType() + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__cmd_group.py new file mode 100644 index 00000000000..fab9b23652e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__cmd_group.py @@ -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 log-analytics workspace saved-search", +) +class __CMDGroup(AAZCommandGroup): + """Manage saved search for log analytics workspace. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_create.py new file mode 100644 index 00000000000..cd3e2861328 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_create.py @@ -0,0 +1,308 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Create(AAZCommand): + """Create a saved search for a given workspace. + + :example: Create a saved search for a given workspace. + az monitor log-analytics workspace saved-search create -g MyRG --workspace-name MyWS -n MySavedSearch --category Test1 --display-name TestSavedSearch -q "AzureActivity | summarize count() by bin(TimeGenerated, 1h)" --fa myfun --fp "a:string = value" + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/savedsearches/{}", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.saved_search_name = AAZStrArg( + options=["-n", "--name", "--saved-search-name"], + help="Name of the saved search and it's unique in a given workspace.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Parameters" + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.category = AAZStrArg( + options=["--category"], + arg_group="Properties", + help="The category of the saved search. This helps the user to find a saved search faster. ", + required=True, + ) + _args_schema.display_name = AAZStrArg( + options=["--display-name"], + arg_group="Properties", + help="Saved search display name.", + required=True, + ) + _args_schema.func_alias = AAZStrArg( + options=["--fa", "--func-alias"], + arg_group="Properties", + help="Function Aliases are short names given to Saved Searches so they can be easily referenced in query. They are required for Computer Groups.", + ) + _args_schema.func_param = AAZStrArg( + options=["--fp", "--func-param"], + arg_group="Properties", + help="The optional function parameters if query serves as a function. Value should be in the following format: 'param-name1:type1 = default_value1, param-name2:type2 = default_value2'. For more examples and proper syntax please refer to https://learn.microsoft.com/azure/kusto/query/functions/user-defined-functions.", + ) + _args_schema.saved_query = AAZStrArg( + options=["-q", "--saved-query"], + arg_group="Properties", + help="The query expression for the saved search.", + required=True, + ) + _args_schema.tags = AAZListArg( + options=["--tags"], + arg_group="Properties", + help="The tags attached to the saved search.", + ) + _args_schema.version = AAZIntArg( + options=["--version"], + arg_group="Properties", + help="The version number of the query language. The current version is 2 and is the default.", + ) + + tags = cls._args_schema.tags + tags.Element = AAZObjectArg() + + _element = cls._args_schema.tags.Element + _element.name = AAZStrArg( + options=["name"], + help="The tag name.", + required=True, + ) + _element.value = AAZStrArg( + options=["value"], + help="The tag value.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SavedSearchesCreateOrUpdate(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 SavedSearchesCreateOrUpdate(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.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "savedSearchId", self.ctx.args.saved_search_name, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("category", AAZStrType, ".category", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("displayName", AAZStrType, ".display_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("functionAlias", AAZStrType, ".func_alias") + properties.set_prop("functionParameters", AAZStrType, ".func_param") + properties.set_prop("query", AAZStrType, ".saved_query", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("tags", AAZListType, ".tags") + properties.set_prop("version", AAZIntType, ".version") + + tags = _builder.get(".properties.tags") + if tags is not None: + tags.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.tags[]") + if _elements is not None: + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("value", AAZStrType, ".value", typ_kwargs={"flags": {"required": True}}) + + return self.serialize_content(_content_value) + + 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.etag = AAZStrType() + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.category = AAZStrType( + flags={"required": True}, + ) + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.function_alias = AAZStrType( + serialized_name="functionAlias", + ) + properties.function_parameters = AAZStrType( + serialized_name="functionParameters", + ) + properties.query = AAZStrType( + flags={"required": True}, + ) + properties.tags = AAZListType() + properties.version = AAZIntType() + + tags = cls._schema_on_200.properties.tags + tags.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.tags.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.value = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_delete.py new file mode 100644 index 00000000000..5bd4568a7fb --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_delete.py @@ -0,0 +1,142 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace saved-search delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a saved search for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/savedsearches/{}", "2020-08-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.saved_search_name = AAZStrArg( + options=["-n", "--name", "--saved-search-name"], + help="Name of the saved search and it's unique in a given workspace.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SavedSearchesDelete(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + class SavedSearchesDelete(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.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "savedSearchId", self.ctx.args.saved_search_name, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_list.py new file mode 100644 index 00000000000..8488b54ba9c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_list.py @@ -0,0 +1,211 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace saved-search list", +) +class List(AAZCommand): + """List all saved searches for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/savedsearches", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SavedSearchesListByWorkspace(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.value, client_flatten=True) + return result + + class SavedSearchesListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/savedSearches", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.etag = AAZStrType() + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.category = AAZStrType( + flags={"required": True}, + ) + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.function_alias = AAZStrType( + serialized_name="functionAlias", + ) + properties.function_parameters = AAZStrType( + serialized_name="functionParameters", + ) + properties.query = AAZStrType( + flags={"required": True}, + ) + properties.tags = AAZListType() + properties.version = AAZIntType() + + tags = cls._schema_on_200.value.Element.properties.tags + tags.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.tags.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.value = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_show.py new file mode 100644 index 00000000000..e5f8e1dbab3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_show.py @@ -0,0 +1,216 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace saved-search show", +) +class Show(AAZCommand): + """Show a saved search for a given workspace. + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/savedsearches/{}", "2020-08-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.saved_search_name = AAZStrArg( + options=["-n", "--name", "--saved-search-name"], + help="Name of the saved search and it's unique in a given workspace.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SavedSearchesGet(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 SavedSearchesGet(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.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "savedSearchId", self.ctx.args.saved_search_name, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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.etag = AAZStrType() + _schema_on_200.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.category = AAZStrType( + flags={"required": True}, + ) + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.function_alias = AAZStrType( + serialized_name="functionAlias", + ) + properties.function_parameters = AAZStrType( + serialized_name="functionParameters", + ) + properties.query = AAZStrType( + flags={"required": True}, + ) + properties.tags = AAZListType() + properties.version = AAZIntType() + + tags = cls._schema_on_200.properties.tags + tags.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.tags.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.value = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_update.py new file mode 100644 index 00000000000..7c337c55976 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/saved_search/_update.py @@ -0,0 +1,455 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Update(AAZCommand): + """Update a saved search for a given workspace. + + :example: Update a saved search for a given workspace. + az monitor log-analytics workspace saved-search update -g MyRG --workspace-name MyWS -n MySavedSearch --category Test1 --display-name TestSavedSearch -q "AzureActivity | summarize count() by bin(TimeGenerated, 1h)" --fa myfun --fp "a:string = value" + """ + + _aaz_info = { + "version": "2020-08-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/savedsearches/{}", "2020-08-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.saved_search_name = AAZStrArg( + options=["-n", "--name", "--saved-search-name"], + help="Name of the saved search and it's unique in a given workspace.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Parameters" + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.category = AAZStrArg( + options=["--category"], + arg_group="Properties", + help="The category of the saved search. This helps the user to find a saved search faster. ", + ) + _args_schema.display_name = AAZStrArg( + options=["--display-name"], + arg_group="Properties", + help="Saved search display name.", + ) + _args_schema.func_alias = AAZStrArg( + options=["--fa", "--func-alias"], + arg_group="Properties", + help="Function Aliases are short names given to Saved Searches so they can be easily referenced in query. They are required for Computer Groups.", + nullable=True, + ) + _args_schema.func_param = AAZStrArg( + options=["--fp", "--func-param"], + arg_group="Properties", + help="The optional function parameters if query serves as a function. Value should be in the following format: 'param-name1:type1 = default_value1, param-name2:type2 = default_value2'. For more examples and proper syntax please refer to https://learn.microsoft.com/azure/kusto/query/functions/user-defined-functions.", + nullable=True, + ) + _args_schema.saved_query = AAZStrArg( + options=["-q", "--saved-query"], + arg_group="Properties", + help="The query expression for the saved search.", + ) + _args_schema.tags = AAZListArg( + options=["--tags"], + arg_group="Properties", + help="The tags attached to the saved search.", + nullable=True, + ) + _args_schema.version = AAZIntArg( + options=["--version"], + arg_group="Properties", + help="The version number of the query language. The current version is 2 and is the default.", + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.tags.Element + _element.name = AAZStrArg( + options=["name"], + help="The tag name.", + ) + _element.value = AAZStrArg( + options=["value"], + help="The tag value.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.SavedSearchesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.SavedSearchesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + # @register_callback + def pre_operations(self): + pass + + # @register_callback + def post_operations(self): + pass + + # @register_callback + def pre_instance_update(self, instance): + pass + + # @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class SavedSearchesGet(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.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "savedSearchId", self.ctx.args.saved_search_name, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-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() + _build_schema_saved_search_read(cls._schema_on_200) + + return cls._schema_on_200 + + class SavedSearchesCreateOrUpdate(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.OperationalInsights/workspaces/{workspaceName}/savedSearches/{savedSearchId}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "savedSearchId", self.ctx.args.saved_search_name, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2020-08-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _build_schema_saved_search_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("category", AAZStrType, ".category", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("displayName", AAZStrType, ".display_name", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("functionAlias", AAZStrType, ".func_alias") + properties.set_prop("functionParameters", AAZStrType, ".func_param") + properties.set_prop("query", AAZStrType, ".saved_query", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("tags", AAZListType, ".tags") + properties.set_prop("version", AAZIntType, ".version") + + tags = _builder.get(".properties.tags") + if tags is not None: + tags.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.tags[]") + if _elements is not None: + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("value", AAZStrType, ".value", typ_kwargs={"flags": {"required": True}}) + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +_schema_saved_search_read = None + + +def _build_schema_saved_search_read(_schema): + global _schema_saved_search_read + if _schema_saved_search_read is not None: + _schema.etag = _schema_saved_search_read.etag + _schema.id = _schema_saved_search_read.id + _schema.name = _schema_saved_search_read.name + _schema.properties = _schema_saved_search_read.properties + _schema.type = _schema_saved_search_read.type + return + + _schema_saved_search_read = AAZObjectType() + + saved_search_read = _schema_saved_search_read + saved_search_read.etag = AAZStrType() + saved_search_read.id = AAZStrType( + flags={"read_only": True}, + ) + saved_search_read.name = AAZStrType( + flags={"read_only": True}, + ) + saved_search_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + saved_search_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_saved_search_read.properties + properties.category = AAZStrType( + flags={"required": True}, + ) + properties.display_name = AAZStrType( + serialized_name="displayName", + flags={"required": True}, + ) + properties.function_alias = AAZStrType( + serialized_name="functionAlias", + ) + properties.function_parameters = AAZStrType( + serialized_name="functionParameters", + ) + properties.query = AAZStrType( + flags={"required": True}, + ) + properties.tags = AAZListType() + properties.version = AAZIntType() + + tags = _schema_saved_search_read.properties.tags + tags.Element = AAZObjectType() + + _element = _schema_saved_search_read.properties.tags.Element + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.value = AAZStrType( + flags={"required": True}, + ) + + _schema.etag = _schema_saved_search_read.etag + _schema.id = _schema_saved_search_read.id + _schema.name = _schema_saved_search_read.name + _schema.properties = _schema_saved_search_read.properties + _schema.type = _schema_saved_search_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__cmd_group.py new file mode 100644 index 00000000000..9865c89c7bf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__cmd_group.py @@ -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 log-analytics workspace table", +) +class __CMDGroup(AAZCommandGroup): + """Manage tables for log analytics workspace. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__init__.py new file mode 100644 index 00000000000..eb0a528490b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/__init__.py @@ -0,0 +1,18 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._migrate import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_create.py new file mode 100644 index 00000000000..13a84648dd1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_create.py @@ -0,0 +1,593 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Create(AAZCommand): + """Create a Log Analytics workspace table. + + The name of custom log table needs to end with '_CL'. The name of search job table needs to end with '_SRCH'. The name of restore logs table needs to end with '_RST'. + + :example: Create a Log Analytics workspace custom log table. + az monitor log-analytics workspace table create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_CL --retention-time 45 --cols "[{name:MyColumn1,type:string},{name:TimeGenerated,type:datetime}]" + + :example: Create a Log Analytics workspace search result table. + az monitor log-analytics workspace table create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_SRCH --retention-time 45 --search-job "{query:'Heartbeat | where SourceSystem != '/'/ | project SourceSystem',limit:1000,start-search-time:'Sat, 28 Aug 2021 05:29:18 GMT',end-search-time:'Sat, 28 Aug 2021 08:29:18 GMT'}" + + :example: Create a Log Analytics workspace restore logs table. + az monitor log-analytics workspace table create --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_RST --restore-logs "{restore-source-table:MyTable,start-restore-time:'Sat, 28 Aug 2021 05:29:18 GMT',end-restore-time:'Sat, 28 Aug 2021 08:29:18 GMT'}" + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}", "2022-10-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.plan = AAZStrArg( + options=["--plan"], + arg_group="Properties", + help="Instruct the system how to handle and charge the logs ingested to this table.", + enum={"Analytics": "Analytics", "Basic": "Basic"}, + ) + _args_schema.restored_logs = AAZObjectArg( + options=["--restored-logs"], + arg_group="Properties", + help="Parameters of the restore operation that initiated this table.", + ) + _args_schema.retention_in_days = AAZIntArg( + options=["--retention-in-days"], + arg_group="Properties", + help="The table retention in days, between 4 and 730. Setting this property to -1 will default to the workspace retention.", + fmt=AAZIntArgFormat( + maximum=730, + minimum=4, + ), + ) + _args_schema.schema = AAZObjectArg( + options=["--schema"], + arg_group="Properties", + help="Table schema.", + ) + _args_schema.search_results = AAZObjectArg( + options=["--search-results"], + arg_group="Properties", + help="Parameters of the search job that initiated this table.", + ) + _args_schema.total_retention_in_days = AAZIntArg( + options=["--total-retention-in-days"], + arg_group="Properties", + help="The table total retention in days, between 4 and 4383. Setting this property to -1 will default to table retention.", + fmt=AAZIntArgFormat( + maximum=4383, + minimum=4, + ), + ) + + restored_logs = cls._args_schema.restored_logs + restored_logs.end_restore_time = AAZDateTimeArg( + options=["end-restore-time"], + help="The timestamp to end the restore by (UTC).", + ) + restored_logs.source_table = AAZStrArg( + options=["source-table"], + help="The table to restore data from.", + ) + restored_logs.start_restore_time = AAZDateTimeArg( + options=["start-restore-time"], + help="The timestamp to start the restore from (UTC).", + ) + + schema = cls._args_schema.schema + schema.columns = AAZListArg( + options=["columns"], + help="A list of table custom columns.", + ) + schema.description = AAZStrArg( + options=["description"], + help="Table description.", + ) + schema.display_name = AAZStrArg( + options=["display-name"], + help="Table display name.", + ) + schema.name = AAZStrArg( + options=["name"], + help="Table name.", + ) + + columns = cls._args_schema.schema.columns + columns.Element = AAZObjectArg() + + _element = cls._args_schema.schema.columns.Element + _element.data_type_hint = AAZStrArg( + options=["data-type-hint"], + help="Column data type logical hint.", + enum={"armPath": "armPath", "guid": "guid", "ip": "ip", "uri": "uri"}, + ) + _element.description = AAZStrArg( + options=["description"], + help="Column description.", + ) + _element.display_name = AAZStrArg( + options=["display-name"], + help="Column display name.", + ) + _element.name = AAZStrArg( + options=["name"], + help="Column name.", + ) + _element.type = AAZStrArg( + options=["type"], + help="Column data type.", + enum={"boolean": "boolean", "dateTime": "dateTime", "dynamic": "dynamic", "guid": "guid", "int": "int", "long": "long", "real": "real", "string": "string"}, + ) + + search_results = cls._args_schema.search_results + search_results.description = AAZStrArg( + options=["description"], + help="Search job Description.", + ) + search_results.end_search_time = AAZDateTimeArg( + options=["end-search-time"], + help="The timestamp to end the search by (UTC)", + ) + search_results.limit = AAZIntArg( + options=["limit"], + help="Limit the search job to return up to specified number of rows.", + ) + search_results.query = AAZStrArg( + options=["query"], + help="Search job query.", + ) + search_results.start_search_time = AAZDateTimeArg( + options=["start-search-time"], + help="The timestamp to start the search from (UTC)", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.TablesCreateOrUpdate(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 TablesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("plan", AAZStrType, ".plan") + properties.set_prop("restoredLogs", AAZObjectType, ".restored_logs") + properties.set_prop("retentionInDays", AAZIntType, ".retention_in_days") + properties.set_prop("schema", AAZObjectType, ".schema") + properties.set_prop("searchResults", AAZObjectType, ".search_results") + properties.set_prop("totalRetentionInDays", AAZIntType, ".total_retention_in_days") + + restored_logs = _builder.get(".properties.restoredLogs") + if restored_logs is not None: + restored_logs.set_prop("endRestoreTime", AAZStrType, ".end_restore_time") + restored_logs.set_prop("sourceTable", AAZStrType, ".source_table") + restored_logs.set_prop("startRestoreTime", AAZStrType, ".start_restore_time") + + schema = _builder.get(".properties.schema") + if schema is not None: + schema.set_prop("columns", AAZListType, ".columns") + schema.set_prop("description", AAZStrType, ".description") + schema.set_prop("displayName", AAZStrType, ".display_name") + schema.set_prop("name", AAZStrType, ".name") + + columns = _builder.get(".properties.schema.columns") + if columns is not None: + columns.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.schema.columns[]") + if _elements is not None: + _elements.set_prop("dataTypeHint", AAZStrType, ".data_type_hint") + _elements.set_prop("description", AAZStrType, ".description") + _elements.set_prop("displayName", AAZStrType, ".display_name") + _elements.set_prop("name", AAZStrType, ".name") + _elements.set_prop("type", AAZStrType, ".type") + + search_results = _builder.get(".properties.searchResults") + if search_results is not None: + search_results.set_prop("description", AAZStrType, ".description") + search_results.set_prop("endSearchTime", AAZStrType, ".end_search_time") + search_results.set_prop("limit", AAZIntType, ".limit") + search_results.set_prop("query", AAZStrType, ".query") + search_results.set_prop("startSearchTime", AAZStrType, ".start_search_time") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.archive_retention_in_days = AAZIntType( + serialized_name="archiveRetentionInDays", + flags={"read_only": True}, + ) + properties.last_plan_modified_date = AAZStrType( + serialized_name="lastPlanModifiedDate", + flags={"read_only": True}, + ) + properties.plan = AAZStrType() + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.restored_logs = AAZObjectType( + serialized_name="restoredLogs", + ) + properties.result_statistics = AAZObjectType( + serialized_name="resultStatistics", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + ) + properties.retention_in_days_as_default = AAZBoolType( + serialized_name="retentionInDaysAsDefault", + flags={"read_only": True}, + ) + properties.schema = AAZObjectType() + properties.search_results = AAZObjectType( + serialized_name="searchResults", + ) + properties.total_retention_in_days = AAZIntType( + serialized_name="totalRetentionInDays", + ) + properties.total_retention_in_days_as_default = AAZBoolType( + serialized_name="totalRetentionInDaysAsDefault", + flags={"read_only": True}, + ) + + restored_logs = cls._schema_on_200.properties.restored_logs + restored_logs.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + restored_logs.end_restore_time = AAZStrType( + serialized_name="endRestoreTime", + ) + restored_logs.source_table = AAZStrType( + serialized_name="sourceTable", + ) + restored_logs.start_restore_time = AAZStrType( + serialized_name="startRestoreTime", + ) + + result_statistics = cls._schema_on_200.properties.result_statistics + result_statistics.ingested_records = AAZIntType( + serialized_name="ingestedRecords", + flags={"read_only": True}, + ) + result_statistics.progress = AAZFloatType( + flags={"read_only": True}, + ) + result_statistics.scanned_gb = AAZFloatType( + serialized_name="scannedGb", + flags={"read_only": True}, + ) + + schema = cls._schema_on_200.properties.schema + schema.categories = AAZListType( + flags={"read_only": True}, + ) + schema.columns = AAZListType() + schema.description = AAZStrType() + schema.display_name = AAZStrType( + serialized_name="displayName", + ) + schema.labels = AAZListType( + flags={"read_only": True}, + ) + schema.name = AAZStrType() + schema.solutions = AAZListType( + flags={"read_only": True}, + ) + schema.source = AAZStrType( + flags={"read_only": True}, + ) + schema.standard_columns = AAZListType( + serialized_name="standardColumns", + flags={"read_only": True}, + ) + schema.table_sub_type = AAZStrType( + serialized_name="tableSubType", + flags={"read_only": True}, + ) + schema.table_type = AAZStrType( + serialized_name="tableType", + flags={"read_only": True}, + ) + + categories = cls._schema_on_200.properties.schema.categories + categories.Element = AAZStrType() + + columns = cls._schema_on_200.properties.schema.columns + columns.Element = AAZObjectType() + _CreateHelper._build_schema_column_read(columns.Element) + + labels = cls._schema_on_200.properties.schema.labels + labels.Element = AAZStrType() + + solutions = cls._schema_on_200.properties.schema.solutions + solutions.Element = AAZStrType() + + standard_columns = cls._schema_on_200.properties.schema.standard_columns + standard_columns.Element = AAZObjectType() + _CreateHelper._build_schema_column_read(standard_columns.Element) + + search_results = cls._schema_on_200.properties.search_results + search_results.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + search_results.description = AAZStrType() + search_results.end_search_time = AAZStrType( + serialized_name="endSearchTime", + ) + search_results.limit = AAZIntType() + search_results.query = AAZStrType() + search_results.source_table = AAZStrType( + serialized_name="sourceTable", + flags={"read_only": True}, + ) + search_results.start_search_time = AAZStrType( + serialized_name="startSearchTime", + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +class _CreateHelper: + """Helper class for Create""" + + _schema_column_read = None + + @classmethod + def _build_schema_column_read(cls, _schema): + if cls._schema_column_read is not None: + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + return + + cls._schema_column_read = _schema_column_read = AAZObjectType() + + column_read = _schema_column_read + column_read.data_type_hint = AAZStrType( + serialized_name="dataTypeHint", + ) + column_read.description = AAZStrType() + column_read.display_name = AAZStrType( + serialized_name="displayName", + ) + column_read.is_default_display = AAZBoolType( + serialized_name="isDefaultDisplay", + flags={"read_only": True}, + ) + column_read.is_hidden = AAZBoolType( + serialized_name="isHidden", + flags={"read_only": True}, + ) + column_read.name = AAZStrType() + column_read.type = AAZStrType() + + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_delete.py new file mode 100644 index 00000000000..af6c7689c65 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_delete.py @@ -0,0 +1,175 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table delete", + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a Log Analytics workspace table. + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}", "2022-10-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.TablesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class TablesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_list.py new file mode 100644 index 00000000000..a8d586c77af --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_list.py @@ -0,0 +1,388 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table list", +) +class List(AAZCommand): + """List all the tables for the given Log Analytics workspace. + + :example: List all the tables for the given Log Analytics workspace + az monitor log-analytics workspace table list --resource-group MyResourceGroup --workspace-name MyWorkspace + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables", "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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesListByWorkspace(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.value, client_flatten=True) + return result + + class TablesListByWorkspace(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.OperationalInsights/workspaces/{workspaceName}/tables", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.archive_retention_in_days = AAZIntType( + serialized_name="archiveRetentionInDays", + flags={"read_only": True}, + ) + properties.last_plan_modified_date = AAZStrType( + serialized_name="lastPlanModifiedDate", + flags={"read_only": True}, + ) + properties.plan = AAZStrType() + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.restored_logs = AAZObjectType( + serialized_name="restoredLogs", + ) + properties.result_statistics = AAZObjectType( + serialized_name="resultStatistics", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + ) + properties.retention_in_days_as_default = AAZBoolType( + serialized_name="retentionInDaysAsDefault", + flags={"read_only": True}, + ) + properties.schema = AAZObjectType() + properties.search_results = AAZObjectType( + serialized_name="searchResults", + ) + properties.total_retention_in_days = AAZIntType( + serialized_name="totalRetentionInDays", + ) + properties.total_retention_in_days_as_default = AAZBoolType( + serialized_name="totalRetentionInDaysAsDefault", + flags={"read_only": True}, + ) + + restored_logs = cls._schema_on_200.value.Element.properties.restored_logs + restored_logs.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + restored_logs.end_restore_time = AAZStrType( + serialized_name="endRestoreTime", + ) + restored_logs.source_table = AAZStrType( + serialized_name="sourceTable", + ) + restored_logs.start_restore_time = AAZStrType( + serialized_name="startRestoreTime", + ) + + result_statistics = cls._schema_on_200.value.Element.properties.result_statistics + result_statistics.ingested_records = AAZIntType( + serialized_name="ingestedRecords", + flags={"read_only": True}, + ) + result_statistics.progress = AAZFloatType( + flags={"read_only": True}, + ) + result_statistics.scanned_gb = AAZFloatType( + serialized_name="scannedGb", + flags={"read_only": True}, + ) + + schema = cls._schema_on_200.value.Element.properties.schema + schema.categories = AAZListType( + flags={"read_only": True}, + ) + schema.columns = AAZListType() + schema.description = AAZStrType() + schema.display_name = AAZStrType( + serialized_name="displayName", + ) + schema.labels = AAZListType( + flags={"read_only": True}, + ) + schema.name = AAZStrType() + schema.solutions = AAZListType( + flags={"read_only": True}, + ) + schema.source = AAZStrType( + flags={"read_only": True}, + ) + schema.standard_columns = AAZListType( + serialized_name="standardColumns", + flags={"read_only": True}, + ) + schema.table_sub_type = AAZStrType( + serialized_name="tableSubType", + flags={"read_only": True}, + ) + schema.table_type = AAZStrType( + serialized_name="tableType", + flags={"read_only": True}, + ) + + categories = cls._schema_on_200.value.Element.properties.schema.categories + categories.Element = AAZStrType() + + columns = cls._schema_on_200.value.Element.properties.schema.columns + columns.Element = AAZObjectType() + _ListHelper._build_schema_column_read(columns.Element) + + labels = cls._schema_on_200.value.Element.properties.schema.labels + labels.Element = AAZStrType() + + solutions = cls._schema_on_200.value.Element.properties.schema.solutions + solutions.Element = AAZStrType() + + standard_columns = cls._schema_on_200.value.Element.properties.schema.standard_columns + standard_columns.Element = AAZObjectType() + _ListHelper._build_schema_column_read(standard_columns.Element) + + search_results = cls._schema_on_200.value.Element.properties.search_results + search_results.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + search_results.description = AAZStrType() + search_results.end_search_time = AAZStrType( + serialized_name="endSearchTime", + ) + search_results.limit = AAZIntType() + search_results.query = AAZStrType() + search_results.source_table = AAZStrType( + serialized_name="sourceTable", + flags={"read_only": True}, + ) + search_results.start_search_time = AAZStrType( + serialized_name="startSearchTime", + ) + + system_data = cls._schema_on_200.value.Element.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_column_read = None + + @classmethod + def _build_schema_column_read(cls, _schema): + if cls._schema_column_read is not None: + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + return + + cls._schema_column_read = _schema_column_read = AAZObjectType() + + column_read = _schema_column_read + column_read.data_type_hint = AAZStrType( + serialized_name="dataTypeHint", + ) + column_read.description = AAZStrType() + column_read.display_name = AAZStrType( + serialized_name="displayName", + ) + column_read.is_default_display = AAZBoolType( + serialized_name="isDefaultDisplay", + flags={"read_only": True}, + ) + column_read.is_hidden = AAZBoolType( + serialized_name="isHidden", + flags={"read_only": True}, + ) + column_read.name = AAZStrType() + column_read.type = AAZStrType() + + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_migrate.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_migrate.py new file mode 100644 index 00000000000..284477fbb44 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_migrate.py @@ -0,0 +1,148 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table migrate", +) +class Migrate(AAZCommand): + """Migrate a Log Analytics table from support of the Data Collector API and Custom Fields features to support of Data Collection Rule-based Custom Logs. + + :example: Migrate a Log Analytics workspace table. + az monitor log-analytics workspace table migrate --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_CL + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}/migrate", "2022-10-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesMigrate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class TablesMigrate(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.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}/migrate", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +class _MigrateHelper: + """Helper class for Migrate""" + + +__all__ = ["Migrate"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_show.py new file mode 100644 index 00000000000..07ec3ac15ea --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_show.py @@ -0,0 +1,393 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table show", +) +class Show(AAZCommand): + """Get a Log Analytics workspace table. + + :example: Get a Log Analytics workspace table + az monitor log-analytics workspace table show --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}", "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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesGet(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 TablesGet(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.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.archive_retention_in_days = AAZIntType( + serialized_name="archiveRetentionInDays", + flags={"read_only": True}, + ) + properties.last_plan_modified_date = AAZStrType( + serialized_name="lastPlanModifiedDate", + flags={"read_only": True}, + ) + properties.plan = AAZStrType() + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.restored_logs = AAZObjectType( + serialized_name="restoredLogs", + ) + properties.result_statistics = AAZObjectType( + serialized_name="resultStatistics", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + ) + properties.retention_in_days_as_default = AAZBoolType( + serialized_name="retentionInDaysAsDefault", + flags={"read_only": True}, + ) + properties.schema = AAZObjectType() + properties.search_results = AAZObjectType( + serialized_name="searchResults", + ) + properties.total_retention_in_days = AAZIntType( + serialized_name="totalRetentionInDays", + ) + properties.total_retention_in_days_as_default = AAZBoolType( + serialized_name="totalRetentionInDaysAsDefault", + flags={"read_only": True}, + ) + + restored_logs = cls._schema_on_200.properties.restored_logs + restored_logs.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + restored_logs.end_restore_time = AAZStrType( + serialized_name="endRestoreTime", + ) + restored_logs.source_table = AAZStrType( + serialized_name="sourceTable", + ) + restored_logs.start_restore_time = AAZStrType( + serialized_name="startRestoreTime", + ) + + result_statistics = cls._schema_on_200.properties.result_statistics + result_statistics.ingested_records = AAZIntType( + serialized_name="ingestedRecords", + flags={"read_only": True}, + ) + result_statistics.progress = AAZFloatType( + flags={"read_only": True}, + ) + result_statistics.scanned_gb = AAZFloatType( + serialized_name="scannedGb", + flags={"read_only": True}, + ) + + schema = cls._schema_on_200.properties.schema + schema.categories = AAZListType( + flags={"read_only": True}, + ) + schema.columns = AAZListType() + schema.description = AAZStrType() + schema.display_name = AAZStrType( + serialized_name="displayName", + ) + schema.labels = AAZListType( + flags={"read_only": True}, + ) + schema.name = AAZStrType() + schema.solutions = AAZListType( + flags={"read_only": True}, + ) + schema.source = AAZStrType( + flags={"read_only": True}, + ) + schema.standard_columns = AAZListType( + serialized_name="standardColumns", + flags={"read_only": True}, + ) + schema.table_sub_type = AAZStrType( + serialized_name="tableSubType", + flags={"read_only": True}, + ) + schema.table_type = AAZStrType( + serialized_name="tableType", + flags={"read_only": True}, + ) + + categories = cls._schema_on_200.properties.schema.categories + categories.Element = AAZStrType() + + columns = cls._schema_on_200.properties.schema.columns + columns.Element = AAZObjectType() + _ShowHelper._build_schema_column_read(columns.Element) + + labels = cls._schema_on_200.properties.schema.labels + labels.Element = AAZStrType() + + solutions = cls._schema_on_200.properties.schema.solutions + solutions.Element = AAZStrType() + + standard_columns = cls._schema_on_200.properties.schema.standard_columns + standard_columns.Element = AAZObjectType() + _ShowHelper._build_schema_column_read(standard_columns.Element) + + search_results = cls._schema_on_200.properties.search_results + search_results.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + search_results.description = AAZStrType() + search_results.end_search_time = AAZStrType( + serialized_name="endSearchTime", + ) + search_results.limit = AAZIntType() + search_results.query = AAZStrType() + search_results.source_table = AAZStrType( + serialized_name="sourceTable", + flags={"read_only": True}, + ) + search_results.start_search_time = AAZStrType( + serialized_name="startSearchTime", + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_column_read = None + + @classmethod + def _build_schema_column_read(cls, _schema): + if cls._schema_column_read is not None: + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + return + + cls._schema_column_read = _schema_column_read = AAZObjectType() + + column_read = _schema_column_read + column_read.data_type_hint = AAZStrType( + serialized_name="dataTypeHint", + ) + column_read.description = AAZStrType() + column_read.display_name = AAZStrType( + serialized_name="displayName", + ) + column_read.is_default_display = AAZBoolType( + serialized_name="isDefaultDisplay", + flags={"read_only": True}, + ) + column_read.is_hidden = AAZBoolType( + serialized_name="isHidden", + flags={"read_only": True}, + ) + column_read.name = AAZStrType() + column_read.type = AAZStrType() + + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_update.py new file mode 100644 index 00000000000..09c69b0409a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_update.py @@ -0,0 +1,753 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Update(AAZCommand): + """Update a Log Analytics workspace table. + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}", "2022-10-01"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + AZ_SUPPORT_GENERIC_UPDATE = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.plan = AAZStrArg( + options=["--plan"], + arg_group="Properties", + help="Instruct the system how to handle and charge the logs ingested to this table.", + nullable=True, + enum={"Analytics": "Analytics", "Basic": "Basic"}, + ) + _args_schema.restored_logs = AAZObjectArg( + options=["--restored-logs"], + arg_group="Properties", + help="Parameters of the restore operation that initiated this table.", + nullable=True, + ) + _args_schema.retention_in_days = AAZIntArg( + options=["--retention-in-days"], + arg_group="Properties", + help="The table retention in days, between 4 and 730. Setting this property to -1 will default to the workspace retention.", + nullable=True, + fmt=AAZIntArgFormat( + maximum=730, + minimum=4, + ), + ) + _args_schema.schema = AAZObjectArg( + options=["--schema"], + arg_group="Properties", + help="Table schema.", + nullable=True, + ) + _args_schema.search_results = AAZObjectArg( + options=["--search-results"], + arg_group="Properties", + help="Parameters of the search job that initiated this table.", + nullable=True, + ) + _args_schema.total_retention_in_days = AAZIntArg( + options=["--total-retention-in-days"], + arg_group="Properties", + help="The table total retention in days, between 4 and 4383. Setting this property to -1 will default to table retention.", + nullable=True, + fmt=AAZIntArgFormat( + maximum=4383, + minimum=4, + ), + ) + + restored_logs = cls._args_schema.restored_logs + restored_logs.end_restore_time = AAZDateTimeArg( + options=["end-restore-time"], + help="The timestamp to end the restore by (UTC).", + nullable=True, + ) + restored_logs.source_table = AAZStrArg( + options=["source-table"], + help="The table to restore data from.", + nullable=True, + ) + restored_logs.start_restore_time = AAZDateTimeArg( + options=["start-restore-time"], + help="The timestamp to start the restore from (UTC).", + nullable=True, + ) + + schema = cls._args_schema.schema + schema.columns = AAZListArg( + options=["columns"], + help="A list of table custom columns.", + nullable=True, + ) + schema.description = AAZStrArg( + options=["description"], + help="Table description.", + nullable=True, + ) + schema.display_name = AAZStrArg( + options=["display-name"], + help="Table display name.", + nullable=True, + ) + schema.name = AAZStrArg( + options=["name"], + help="Table name.", + nullable=True, + ) + + columns = cls._args_schema.schema.columns + columns.Element = AAZObjectArg( + nullable=True, + ) + + _element = cls._args_schema.schema.columns.Element + _element.data_type_hint = AAZStrArg( + options=["data-type-hint"], + help="Column data type logical hint.", + nullable=True, + enum={"armPath": "armPath", "guid": "guid", "ip": "ip", "uri": "uri"}, + ) + _element.description = AAZStrArg( + options=["description"], + help="Column description.", + nullable=True, + ) + _element.display_name = AAZStrArg( + options=["display-name"], + help="Column display name.", + nullable=True, + ) + _element.name = AAZStrArg( + options=["name"], + help="Column name.", + nullable=True, + ) + _element.type = AAZStrArg( + options=["type"], + help="Column data type.", + nullable=True, + enum={"boolean": "boolean", "dateTime": "dateTime", "dynamic": "dynamic", "guid": "guid", "int": "int", "long": "long", "real": "real", "string": "string"}, + ) + + search_results = cls._args_schema.search_results + search_results.description = AAZStrArg( + options=["description"], + help="Search job Description.", + nullable=True, + ) + search_results.end_search_time = AAZDateTimeArg( + options=["end-search-time"], + help="The timestamp to end the search by (UTC)", + nullable=True, + ) + search_results.limit = AAZIntArg( + options=["limit"], + help="Limit the search job to return up to specified number of rows.", + nullable=True, + ) + search_results.query = AAZStrArg( + options=["query"], + help="Search job query.", + nullable=True, + ) + search_results.start_search_time = AAZDateTimeArg( + options=["start-search-time"], + help="The timestamp to start the search from (UTC)", + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + yield self.TablesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class TablesGet(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.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **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() + _UpdateHelper._build_schema_table_read(cls._schema_on_200) + + return cls._schema_on_200 + + class TablesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_table_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("plan", AAZStrType, ".plan") + properties.set_prop("restoredLogs", AAZObjectType, ".restored_logs") + properties.set_prop("retentionInDays", AAZIntType, ".retention_in_days") + properties.set_prop("schema", AAZObjectType, ".schema") + properties.set_prop("searchResults", AAZObjectType, ".search_results") + properties.set_prop("totalRetentionInDays", AAZIntType, ".total_retention_in_days") + + restored_logs = _builder.get(".properties.restoredLogs") + if restored_logs is not None: + restored_logs.set_prop("endRestoreTime", AAZStrType, ".end_restore_time") + restored_logs.set_prop("sourceTable", AAZStrType, ".source_table") + restored_logs.set_prop("startRestoreTime", AAZStrType, ".start_restore_time") + + schema = _builder.get(".properties.schema") + if schema is not None: + schema.set_prop("columns", AAZListType, ".columns") + schema.set_prop("description", AAZStrType, ".description") + schema.set_prop("displayName", AAZStrType, ".display_name") + schema.set_prop("name", AAZStrType, ".name") + + columns = _builder.get(".properties.schema.columns") + if columns is not None: + columns.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.schema.columns[]") + if _elements is not None: + _elements.set_prop("dataTypeHint", AAZStrType, ".data_type_hint") + _elements.set_prop("description", AAZStrType, ".description") + _elements.set_prop("displayName", AAZStrType, ".display_name") + _elements.set_prop("name", AAZStrType, ".name") + _elements.set_prop("type", AAZStrType, ".type") + + search_results = _builder.get(".properties.searchResults") + if search_results is not None: + search_results.set_prop("description", AAZStrType, ".description") + search_results.set_prop("endSearchTime", AAZStrType, ".end_search_time") + search_results.set_prop("limit", AAZIntType, ".limit") + search_results.set_prop("query", AAZStrType, ".query") + search_results.set_prop("startSearchTime", AAZStrType, ".start_search_time") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_column_read = None + + @classmethod + def _build_schema_column_read(cls, _schema): + if cls._schema_column_read is not None: + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + return + + cls._schema_column_read = _schema_column_read = AAZObjectType() + + column_read = _schema_column_read + column_read.data_type_hint = AAZStrType( + serialized_name="dataTypeHint", + ) + column_read.description = AAZStrType() + column_read.display_name = AAZStrType( + serialized_name="displayName", + ) + column_read.is_default_display = AAZBoolType( + serialized_name="isDefaultDisplay", + flags={"read_only": True}, + ) + column_read.is_hidden = AAZBoolType( + serialized_name="isHidden", + flags={"read_only": True}, + ) + column_read.name = AAZStrType() + column_read.type = AAZStrType() + + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + + _schema_table_read = None + + @classmethod + def _build_schema_table_read(cls, _schema): + if cls._schema_table_read is not None: + _schema.id = cls._schema_table_read.id + _schema.name = cls._schema_table_read.name + _schema.properties = cls._schema_table_read.properties + _schema.system_data = cls._schema_table_read.system_data + _schema.type = cls._schema_table_read.type + return + + cls._schema_table_read = _schema_table_read = AAZObjectType() + + table_read = _schema_table_read + table_read.id = AAZStrType( + flags={"read_only": True}, + ) + table_read.name = AAZStrType( + flags={"read_only": True}, + ) + table_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + table_read.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + table_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_table_read.properties + properties.archive_retention_in_days = AAZIntType( + serialized_name="archiveRetentionInDays", + flags={"read_only": True}, + ) + properties.last_plan_modified_date = AAZStrType( + serialized_name="lastPlanModifiedDate", + flags={"read_only": True}, + ) + properties.plan = AAZStrType() + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.restored_logs = AAZObjectType( + serialized_name="restoredLogs", + ) + properties.result_statistics = AAZObjectType( + serialized_name="resultStatistics", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + ) + properties.retention_in_days_as_default = AAZBoolType( + serialized_name="retentionInDaysAsDefault", + flags={"read_only": True}, + ) + properties.schema = AAZObjectType() + properties.search_results = AAZObjectType( + serialized_name="searchResults", + ) + properties.total_retention_in_days = AAZIntType( + serialized_name="totalRetentionInDays", + ) + properties.total_retention_in_days_as_default = AAZBoolType( + serialized_name="totalRetentionInDaysAsDefault", + flags={"read_only": True}, + ) + + restored_logs = _schema_table_read.properties.restored_logs + restored_logs.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + restored_logs.end_restore_time = AAZStrType( + serialized_name="endRestoreTime", + ) + restored_logs.source_table = AAZStrType( + serialized_name="sourceTable", + ) + restored_logs.start_restore_time = AAZStrType( + serialized_name="startRestoreTime", + ) + + result_statistics = _schema_table_read.properties.result_statistics + result_statistics.ingested_records = AAZIntType( + serialized_name="ingestedRecords", + flags={"read_only": True}, + ) + result_statistics.progress = AAZFloatType( + flags={"read_only": True}, + ) + result_statistics.scanned_gb = AAZFloatType( + serialized_name="scannedGb", + flags={"read_only": True}, + ) + + schema = _schema_table_read.properties.schema + schema.categories = AAZListType( + flags={"read_only": True}, + ) + schema.columns = AAZListType() + schema.description = AAZStrType() + schema.display_name = AAZStrType( + serialized_name="displayName", + ) + schema.labels = AAZListType( + flags={"read_only": True}, + ) + schema.name = AAZStrType() + schema.solutions = AAZListType( + flags={"read_only": True}, + ) + schema.source = AAZStrType( + flags={"read_only": True}, + ) + schema.standard_columns = AAZListType( + serialized_name="standardColumns", + flags={"read_only": True}, + ) + schema.table_sub_type = AAZStrType( + serialized_name="tableSubType", + flags={"read_only": True}, + ) + schema.table_type = AAZStrType( + serialized_name="tableType", + flags={"read_only": True}, + ) + + categories = _schema_table_read.properties.schema.categories + categories.Element = AAZStrType() + + columns = _schema_table_read.properties.schema.columns + columns.Element = AAZObjectType() + cls._build_schema_column_read(columns.Element) + + labels = _schema_table_read.properties.schema.labels + labels.Element = AAZStrType() + + solutions = _schema_table_read.properties.schema.solutions + solutions.Element = AAZStrType() + + standard_columns = _schema_table_read.properties.schema.standard_columns + standard_columns.Element = AAZObjectType() + cls._build_schema_column_read(standard_columns.Element) + + search_results = _schema_table_read.properties.search_results + search_results.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + search_results.description = AAZStrType() + search_results.end_search_time = AAZStrType( + serialized_name="endSearchTime", + ) + search_results.limit = AAZIntType() + search_results.query = AAZStrType() + search_results.source_table = AAZStrType( + serialized_name="sourceTable", + flags={"read_only": True}, + ) + search_results.start_search_time = AAZStrType( + serialized_name="startSearchTime", + ) + + system_data = _schema_table_read.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + _schema.id = cls._schema_table_read.id + _schema.name = cls._schema_table_read.name + _schema.properties = cls._schema_table_read.properties + _schema.system_data = cls._schema_table_read.system_data + _schema.type = cls._schema_table_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_wait.py new file mode 100644 index 00000000000..ee9946435bd --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/_wait.py @@ -0,0 +1,389 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}", "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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesGet(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=False) + return result + + class TablesGet(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.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.system_data = AAZObjectType( + serialized_name="systemData", + flags={"read_only": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.archive_retention_in_days = AAZIntType( + serialized_name="archiveRetentionInDays", + flags={"read_only": True}, + ) + properties.last_plan_modified_date = AAZStrType( + serialized_name="lastPlanModifiedDate", + flags={"read_only": True}, + ) + properties.plan = AAZStrType() + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + properties.restored_logs = AAZObjectType( + serialized_name="restoredLogs", + ) + properties.result_statistics = AAZObjectType( + serialized_name="resultStatistics", + ) + properties.retention_in_days = AAZIntType( + serialized_name="retentionInDays", + ) + properties.retention_in_days_as_default = AAZBoolType( + serialized_name="retentionInDaysAsDefault", + flags={"read_only": True}, + ) + properties.schema = AAZObjectType() + properties.search_results = AAZObjectType( + serialized_name="searchResults", + ) + properties.total_retention_in_days = AAZIntType( + serialized_name="totalRetentionInDays", + ) + properties.total_retention_in_days_as_default = AAZBoolType( + serialized_name="totalRetentionInDaysAsDefault", + flags={"read_only": True}, + ) + + restored_logs = cls._schema_on_200.properties.restored_logs + restored_logs.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + restored_logs.end_restore_time = AAZStrType( + serialized_name="endRestoreTime", + ) + restored_logs.source_table = AAZStrType( + serialized_name="sourceTable", + ) + restored_logs.start_restore_time = AAZStrType( + serialized_name="startRestoreTime", + ) + + result_statistics = cls._schema_on_200.properties.result_statistics + result_statistics.ingested_records = AAZIntType( + serialized_name="ingestedRecords", + flags={"read_only": True}, + ) + result_statistics.progress = AAZFloatType( + flags={"read_only": True}, + ) + result_statistics.scanned_gb = AAZFloatType( + serialized_name="scannedGb", + flags={"read_only": True}, + ) + + schema = cls._schema_on_200.properties.schema + schema.categories = AAZListType( + flags={"read_only": True}, + ) + schema.columns = AAZListType() + schema.description = AAZStrType() + schema.display_name = AAZStrType( + serialized_name="displayName", + ) + schema.labels = AAZListType( + flags={"read_only": True}, + ) + schema.name = AAZStrType() + schema.solutions = AAZListType( + flags={"read_only": True}, + ) + schema.source = AAZStrType( + flags={"read_only": True}, + ) + schema.standard_columns = AAZListType( + serialized_name="standardColumns", + flags={"read_only": True}, + ) + schema.table_sub_type = AAZStrType( + serialized_name="tableSubType", + flags={"read_only": True}, + ) + schema.table_type = AAZStrType( + serialized_name="tableType", + flags={"read_only": True}, + ) + + categories = cls._schema_on_200.properties.schema.categories + categories.Element = AAZStrType() + + columns = cls._schema_on_200.properties.schema.columns + columns.Element = AAZObjectType() + _WaitHelper._build_schema_column_read(columns.Element) + + labels = cls._schema_on_200.properties.schema.labels + labels.Element = AAZStrType() + + solutions = cls._schema_on_200.properties.schema.solutions + solutions.Element = AAZStrType() + + standard_columns = cls._schema_on_200.properties.schema.standard_columns + standard_columns.Element = AAZObjectType() + _WaitHelper._build_schema_column_read(standard_columns.Element) + + search_results = cls._schema_on_200.properties.search_results + search_results.azure_async_operation_id = AAZStrType( + serialized_name="azureAsyncOperationId", + flags={"read_only": True}, + ) + search_results.description = AAZStrType() + search_results.end_search_time = AAZStrType( + serialized_name="endSearchTime", + ) + search_results.limit = AAZIntType() + search_results.query = AAZStrType() + search_results.source_table = AAZStrType( + serialized_name="sourceTable", + flags={"read_only": True}, + ) + search_results.start_search_time = AAZStrType( + serialized_name="startSearchTime", + ) + + system_data = cls._schema_on_200.system_data + system_data.created_at = AAZStrType( + serialized_name="createdAt", + ) + system_data.created_by = AAZStrType( + serialized_name="createdBy", + ) + system_data.created_by_type = AAZStrType( + serialized_name="createdByType", + ) + system_data.last_modified_at = AAZStrType( + serialized_name="lastModifiedAt", + ) + system_data.last_modified_by = AAZStrType( + serialized_name="lastModifiedBy", + ) + system_data.last_modified_by_type = AAZStrType( + serialized_name="lastModifiedByType", + ) + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + _schema_column_read = None + + @classmethod + def _build_schema_column_read(cls, _schema): + if cls._schema_column_read is not None: + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + return + + cls._schema_column_read = _schema_column_read = AAZObjectType() + + column_read = _schema_column_read + column_read.data_type_hint = AAZStrType( + serialized_name="dataTypeHint", + ) + column_read.description = AAZStrType() + column_read.display_name = AAZStrType( + serialized_name="displayName", + ) + column_read.is_default_display = AAZBoolType( + serialized_name="isDefaultDisplay", + flags={"read_only": True}, + ) + column_read.is_hidden = AAZBoolType( + serialized_name="isHidden", + flags={"read_only": True}, + ) + column_read.name = AAZStrType() + column_read.type = AAZStrType() + + _schema.data_type_hint = cls._schema_column_read.data_type_hint + _schema.description = cls._schema_column_read.description + _schema.display_name = cls._schema_column_read.display_name + _schema.is_default_display = cls._schema_column_read.is_default_display + _schema.is_hidden = cls._schema_column_read.is_hidden + _schema.name = cls._schema_column_read.name + _schema.type = cls._schema_column_read.type + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__cmd_group.py new file mode 100644 index 00000000000..d38d8950dee --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__cmd_group.py @@ -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 log-analytics workspace table search-job", +) +class __CMDGroup(AAZCommandGroup): + """Manage tables for log analytics workspace search results table. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py new file mode 100644 index 00000000000..77a46665663 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py @@ -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 ._cancel import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py new file mode 100644 index 00000000000..d2fe015fef4 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py @@ -0,0 +1,148 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-analytics workspace table search-job cancel", +) +class Cancel(AAZCommand): + """Cancel a log analytics workspace search results table query run. + + :example: Cancel a log analytics workspace search results table query run. + az monitor log-analytics workspace table search-job cancel --resource-group MyResourceGroup --workspace-name MyWorkspace -n MyTable_SRCH + """ + + _aaz_info = { + "version": "2022-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/tables/{}/cancelsearch", "2022-10-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.table_name = AAZStrArg( + options=["-n", "--name", "--table-name"], + help="The name of the table.", + required=True, + id_part="child_name_1", + ) + _args_schema.workspace_name = AAZStrArg( + options=["--workspace-name"], + help="The name of the workspace.", + required=True, + id_part="name", + fmt=AAZStrArgFormat( + pattern="^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$", + max_length=63, + min_length=4, + ), + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.TablesCancelSearch(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class TablesCancelSearch(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.OperationalInsights/workspaces/{workspaceName}/tables/{tableName}/cancelSearch", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + **self.serialize_url_param( + "tableName", self.ctx.args.table_name, + required=True, + ), + **self.serialize_url_param( + "workspaceName", self.ctx.args.workspace_name, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2022-10-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +class _CancelHelper: + """Helper class for Cancel""" + + +__all__ = ["Cancel"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__cmd_group.py new file mode 100644 index 00000000000..cee38c157a2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__cmd_group.py @@ -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 log-profiles", +) +class __CMDGroup(AAZCommandGroup): + """Manage log profiles. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_create.py new file mode 100644 index 00000000000..d7d6f87cb3c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_create.py @@ -0,0 +1,302 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-profiles create", +) +class Create(AAZCommand): + """Create a log profile in Azure Monitoring REST API. + + :example: Create a log profile. (autogenerated) + az monitor log-profiles create --categories "Delete" --days 0 --enabled true --location westus2 --locations westus --name MyLogProfile --service-bus-rule-id "/subscriptions/{YOUR SUBSCRIPTION ID}/resourceGroups/{RESOURCE GROUP NAME}/providers/Microsoft.EventHub/namespaces/{EVENT HUB NAME SPACE}/authorizationrules/RootManageSharedAccessKey" + """ + + _aaz_info = { + "version": "2016-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/logprofiles/{}", "2016-03-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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the log profile.", + required=True, + ) + _args_schema.location = AAZResourceLocationArg( + help="Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=`.", + required=True, + ) + _args_schema.categories = AAZListArg( + options=["--categories"], + help="Space-separated categories of the logs. These categories are created as is convenient to the user. Some values are: 'Write', 'Delete', and/or 'Action.'", + required=True, + ) + _args_schema.locations = AAZListArg( + options=["--locations"], + help="Space-separated list of regions for which Activity Log events should be stored.", + required=True, + ) + _args_schema.service_bus_rule_id = AAZStrArg( + options=["--service-bus-rule-id"], + help="The service bus rule ID of the service bus namespace in which you would like to have Event Hubs created for streaming the Activity Log. The rule ID is of the format: '{service bus resource ID}/authorizationrules/{key name}'.", + ) + _args_schema.storage_account_id = AAZStrArg( + options=["--storage-account-id"], + help="the resource id of the storage account to which you would like to send the Activity Log.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.", + ) + + categories = cls._args_schema.categories + categories.Element = AAZStrArg() + + locations = cls._args_schema.locations + locations.Element = AAZStrArg() + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Retention Policy" + + _args_schema = cls._args_schema + _args_schema.days = AAZIntArg( + options=["--days"], + arg_group="Retention Policy", + help="the number of days for the retention in days. A value of 0 will retain the events indefinitely.", + required=True, + fmt=AAZIntArgFormat( + minimum=0, + ), + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + arg_group="Retention Policy", + help="Whether the retention policy is enabled. Allowed values: false, true.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LogProfilesCreateOrUpdate(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 LogProfilesCreateOrUpdate(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}/providers/Microsoft.Insights/logprofiles/{logProfileName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "logProfileName", self.ctx.args.name, + 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( + "api-version", "2016-03-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("categories", AAZListType, ".categories", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("locations", AAZListType, ".locations", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("retentionPolicy", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule_id") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account_id") + + categories = _builder.get(".properties.categories") + if categories is not None: + categories.set_elements(AAZStrType, ".") + + locations = _builder.get(".properties.locations") + if locations is not None: + locations.set_elements(AAZStrType, ".") + + retention_policy = _builder.get(".properties.retentionPolicy") + if retention_policy is not None: + retention_policy.set_prop("days", AAZIntType, ".days", typ_kwargs={"flags": {"required": True}}) + retention_policy.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.categories = AAZListType( + flags={"required": True}, + ) + properties.locations = AAZListType( + flags={"required": True}, + ) + properties.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + flags={"required": True}, + ) + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + + categories = cls._schema_on_200.properties.categories + categories.Element = AAZStrType() + + locations = cls._schema_on_200.properties.locations + locations.Element = AAZStrType() + + retention_policy = cls._schema_on_200.properties.retention_policy + retention_policy.days = AAZIntType( + flags={"required": True}, + ) + retention_policy.enabled = AAZBoolType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_delete.py new file mode 100644 index 00000000000..66351bcd182 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_delete.py @@ -0,0 +1,123 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-profiles delete", +) +class Delete(AAZCommand): + """Delete the log profile. + """ + + _aaz_info = { + "version": "2016-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/logprofiles/{}", "2016-03-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the log profile.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LogProfilesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class LogProfilesDelete(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}/providers/Microsoft.Insights/logprofiles/{logProfileName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "logProfileName", self.ctx.args.name, + 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( + "api-version", "2016-03-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_list.py new file mode 100644 index 00000000000..e8d587b68e3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_list.py @@ -0,0 +1,201 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-profiles list", +) +class List(AAZCommand): + """List the log profiles. + """ + + _aaz_info = { + "version": "2016-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/logprofiles", "2016-03-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 "" + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LogProfilesList(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.value, client_flatten=True) + return result + + class LogProfilesList(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}/providers/Microsoft.Insights/logprofiles", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2016-03-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.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.categories = AAZListType( + flags={"required": True}, + ) + properties.locations = AAZListType( + flags={"required": True}, + ) + properties.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + flags={"required": True}, + ) + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + + categories = cls._schema_on_200.value.Element.properties.categories + categories.Element = AAZStrType() + + locations = cls._schema_on_200.value.Element.properties.locations + locations.Element = AAZStrType() + + retention_policy = cls._schema_on_200.value.Element.properties.retention_policy + retention_policy.days = AAZIntType( + flags={"required": True}, + ) + retention_policy.enabled = AAZBoolType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_show.py new file mode 100644 index 00000000000..724e50ff717 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_show.py @@ -0,0 +1,205 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-profiles show", +) +class Show(AAZCommand): + """Get the log profile. + """ + + _aaz_info = { + "version": "2016-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/logprofiles/{}", "2016-03-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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the log profile.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LogProfilesGet(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 LogProfilesGet(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}/providers/Microsoft.Insights/logprofiles/{logProfileName}", + **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( + "logProfileName", self.ctx.args.name, + 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( + "api-version", "2016-03-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.categories = AAZListType( + flags={"required": True}, + ) + properties.locations = AAZListType( + flags={"required": True}, + ) + properties.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + flags={"required": True}, + ) + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + + categories = cls._schema_on_200.properties.categories + categories.Element = AAZStrType() + + locations = cls._schema_on_200.properties.locations + locations.Element = AAZStrType() + + retention_policy = cls._schema_on_200.properties.retention_policy + retention_policy.days = AAZIntType( + flags={"required": True}, + ) + retention_policy.enabled = AAZBoolType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_update.py new file mode 100644 index 00000000000..80731118f10 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/log_profiles/_update.py @@ -0,0 +1,438 @@ +# -------------------------------------------------------------------------------------------- +# 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 log-profiles update", +) +class Update(AAZCommand): + """Update a log profile in Azure Monitoring REST API. + """ + + _aaz_info = { + "version": "2016-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/logprofiles/{}", "2016-03-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="The name of the log profile.", + required=True, + id_part="name", + ) + _args_schema.categories = AAZListArg( + options=["--categories"], + help="Space-separated categories of the logs. These categories are created as is convenient to the user. Some values are: 'Write', 'Delete', and/or 'Action.'", + ) + _args_schema.locations = AAZListArg( + options=["--locations"], + help="Space-separated list of regions for which Activity Log events should be stored.", + ) + _args_schema.service_bus_rule_id = AAZStrArg( + options=["--service-bus-rule-id"], + help="The service bus rule ID of the service bus namespace in which you would like to have Event Hubs created for streaming the Activity Log. The rule ID is of the format: '{service bus resource ID}/authorizationrules/{key name}'.", + nullable=True, + ) + _args_schema.storage_account_id = AAZStrArg( + options=["--storage-account-id"], + help="the resource id of the storage account to which you would like to send the Activity Log.", + nullable=True, + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.", + nullable=True, + ) + + categories = cls._args_schema.categories + categories.Element = AAZStrArg( + nullable=True, + ) + + locations = cls._args_schema.locations + locations.Element = AAZStrArg( + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Retention Policy" + + _args_schema = cls._args_schema + _args_schema.days = AAZIntArg( + options=["--days"], + arg_group="Retention Policy", + help="the number of days for the retention in days. A value of 0 will retain the events indefinitely.", + fmt=AAZIntArgFormat( + minimum=0, + ), + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + arg_group="Retention Policy", + help="Whether the retention policy is enabled. Allowed values: false, true.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.LogProfilesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.LogProfilesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class LogProfilesGet(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}/providers/Microsoft.Insights/logprofiles/{logProfileName}", + **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( + "logProfileName", self.ctx.args.name, + 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( + "api-version", "2016-03-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() + _UpdateHelper._build_schema_log_profile_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class LogProfilesCreateOrUpdate(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}/providers/Microsoft.Insights/logprofiles/{logProfileName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "logProfileName", self.ctx.args.name, + 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( + "api-version", "2016-03-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_log_profile_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("categories", AAZListType, ".categories", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("locations", AAZListType, ".locations", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("retentionPolicy", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule_id") + properties.set_prop("storageAccountId", AAZStrType, ".storage_account_id") + + categories = _builder.get(".properties.categories") + if categories is not None: + categories.set_elements(AAZStrType, ".") + + locations = _builder.get(".properties.locations") + if locations is not None: + locations.set_elements(AAZStrType, ".") + + retention_policy = _builder.get(".properties.retentionPolicy") + if retention_policy is not None: + retention_policy.set_prop("days", AAZIntType, ".days", typ_kwargs={"flags": {"required": True}}) + retention_policy.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_log_profile_resource_read = None + + @classmethod + def _build_schema_log_profile_resource_read(cls, _schema): + if cls._schema_log_profile_resource_read is not None: + _schema.id = cls._schema_log_profile_resource_read.id + _schema.location = cls._schema_log_profile_resource_read.location + _schema.name = cls._schema_log_profile_resource_read.name + _schema.properties = cls._schema_log_profile_resource_read.properties + _schema.tags = cls._schema_log_profile_resource_read.tags + _schema.type = cls._schema_log_profile_resource_read.type + return + + cls._schema_log_profile_resource_read = _schema_log_profile_resource_read = AAZObjectType() + + log_profile_resource_read = _schema_log_profile_resource_read + log_profile_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + log_profile_resource_read.location = AAZStrType( + flags={"required": True}, + ) + log_profile_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + log_profile_resource_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + log_profile_resource_read.tags = AAZDictType() + log_profile_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_log_profile_resource_read.properties + properties.categories = AAZListType( + flags={"required": True}, + ) + properties.locations = AAZListType( + flags={"required": True}, + ) + properties.retention_policy = AAZObjectType( + serialized_name="retentionPolicy", + flags={"required": True}, + ) + properties.service_bus_rule_id = AAZStrType( + serialized_name="serviceBusRuleId", + ) + properties.storage_account_id = AAZStrType( + serialized_name="storageAccountId", + ) + + categories = _schema_log_profile_resource_read.properties.categories + categories.Element = AAZStrType() + + locations = _schema_log_profile_resource_read.properties.locations + locations.Element = AAZStrType() + + retention_policy = _schema_log_profile_resource_read.properties.retention_policy + retention_policy.days = AAZIntType( + flags={"required": True}, + ) + retention_policy.enabled = AAZBoolType( + flags={"required": True}, + ) + + tags = _schema_log_profile_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_log_profile_resource_read.id + _schema.location = cls._schema_log_profile_resource_read.location + _schema.name = cls._schema_log_profile_resource_read.name + _schema.properties = cls._schema_log_profile_resource_read.properties + _schema.tags = cls._schema_log_profile_resource_read.tags + _schema.type = cls._schema_log_profile_resource_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__cmd_group.py new file mode 100644 index 00000000000..f20e2e9dc95 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__cmd_group.py @@ -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 metrics", +) +class __CMDGroup(AAZCommandGroup): + """View Azure resource metrics. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__init__.py new file mode 100644 index 00000000000..92c07af8d7c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._list import * +from ._list_definitions import * +from ._list_namespaces import * +from ._list_sub import * +from ._list_sub_definitions import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list.py new file mode 100644 index 00000000000..07c11fc50d4 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list.py @@ -0,0 +1,302 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class List(AAZCommand): + """List the metric values for a resource. + """ + + _aaz_info = { + "version": "2018-01-01", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/metrics", "2018-01-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.resource_uri = AAZStrArg( + options=["--resource-uri"], + help="The identifier of the resource.", + required=True, + ) + _args_schema.aggregation = AAZStrArg( + options=["--aggregation"], + help="The list of aggregation types (comma separated) to retrieve.", + ) + _args_schema.filter = AAZStrArg( + options=["--filter"], + help="The **$filter** is used to reduce the set of metric data returned. Example: Metric contains metadata A, B and C. - Return all time series of C where A = a1 and B = b1 or b2 **$filter=A eq 'a1' and B eq 'b1' or B eq 'b2' and C eq '*'** - Invalid variant: **$filter=A eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series where A = a1 **$filter=A eq 'a1' and B eq '*' and C eq '*'**. Special case: When dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** Instead of using $filter= \"dim (test) 1 eq '*' \" use **$filter= \"dim %2528test%2529 1 eq '*' \"** When dimension name is **dim (test) 3** and dimension value is **dim3 (test) val** Instead of using $filter= \"dim (test) 3 eq 'dim3 (test) val' \" use **$filter= \"dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' \"**", + ) + _args_schema.interval = AAZDurationArg( + options=["--interval"], + help="The interval (i.e. timegrain) of the query.", + ) + _args_schema.metricnames = AAZStrArg( + options=["--metricnames"], + 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'**", + ) + _args_schema.metricnamespace = AAZStrArg( + options=["--metricnamespace"], + help="Metric namespace to query metric definitions for.", + ) + _args_schema.orderby = AAZStrArg( + options=["--orderby"], + help="The aggregation to use for sorting results and the direction of the sort. Only one order can be specified. Examples: sum asc.", + ) + _args_schema.result_type = AAZStrArg( + options=["--result-type"], + help="Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details.", + enum={"Data": "Data", "Metadata": "Metadata"}, + ) + _args_schema.timespan = AAZStrArg( + options=["--timespan"], + help="The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.", + ) + _args_schema.top = AAZIntArg( + options=["--top"], + help="The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricsList(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 MetricsList(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( + "/{resourceUri}/providers/Microsoft.Insights/metrics", + **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( + "resourceUri", self.ctx.args.resource_uri, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "$filter", self.ctx.args.filter, + ), + **self.serialize_query_param( + "aggregation", self.ctx.args.aggregation, + ), + **self.serialize_query_param( + "interval", self.ctx.args.interval, + ), + **self.serialize_query_param( + "metricnames", self.ctx.args.metricnames, + ), + **self.serialize_query_param( + "metricnamespace", self.ctx.args.metricnamespace, + ), + **self.serialize_query_param( + "orderby", self.ctx.args.orderby, + ), + **self.serialize_query_param( + "resultType", self.ctx.args.result_type, + ), + **self.serialize_query_param( + "timespan", self.ctx.args.timespan, + ), + **self.serialize_query_param( + "top", self.ctx.args.top, + ), + **self.serialize_query_param( + "api-version", "2018-01-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.cost = AAZIntType() + _schema_on_200.interval = AAZStrType() + _schema_on_200.namespace = AAZStrType() + _schema_on_200.resourceregion = AAZStrType() + _schema_on_200.timespan = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.display_description = AAZStrType( + serialized_name="displayDescription", + ) + _element.error_code = AAZStrType( + serialized_name="errorCode", + ) + _element.error_message = AAZStrType( + serialized_name="errorMessage", + ) + _element.id = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZObjectType( + flags={"required": True}, + ) + _ListHelper._build_schema_localizable_string_read(_element.name) + _element.timeseries = AAZListType( + flags={"required": True}, + ) + _element.type = AAZStrType( + flags={"required": True}, + ) + _element.unit = AAZStrType( + flags={"required": True}, + ) + + timeseries = cls._schema_on_200.value.Element.timeseries + timeseries.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element + _element.data = AAZListType() + _element.metadatavalues = AAZListType() + + data = cls._schema_on_200.value.Element.timeseries.Element.data + data.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element.data.Element + _element.average = AAZFloatType() + _element.count = AAZFloatType() + _element.maximum = AAZFloatType() + _element.minimum = AAZFloatType() + _element.time_stamp = AAZStrType( + serialized_name="timeStamp", + flags={"required": True}, + ) + _element.total = AAZFloatType() + + metadatavalues = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues + metadatavalues.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues.Element + _element.name = AAZObjectType() + _ListHelper._build_schema_localizable_string_read(_element.name) + _element.value = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_localizable_string_read = None + + @classmethod + def _build_schema_localizable_string_read(cls, _schema): + if cls._schema_localizable_string_read is not None: + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + return + + cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType() + + localizable_string_read = _schema_localizable_string_read + localizable_string_read.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + localizable_string_read.value = AAZStrType( + flags={"required": True}, + ) + + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_definitions.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_definitions.py new file mode 100644 index 00000000000..4444771973c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_definitions.py @@ -0,0 +1,228 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class ListDefinitions(AAZCommand): + """List the metric definitions for the resource. + """ + + _aaz_info = { + "version": "2018-01-01", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/metricdefinitions", "2018-01-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.resource_uri = AAZStrArg( + options=["--resource-uri"], + help="The identifier of the resource.", + required=True, + ) + _args_schema.metricnamespace = AAZStrArg( + options=["--metricnamespace"], + help="Metric namespace to query metric definitions for.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricDefinitionsList(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.value, client_flatten=True) + return result + + class MetricDefinitionsList(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( + "/{resourceUri}/providers/Microsoft.Insights/metricDefinitions", + **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( + "resourceUri", self.ctx.args.resource_uri, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "metricnamespace", self.ctx.args.metricnamespace, + ), + **self.serialize_query_param( + "api-version", "2018-01-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.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.category = AAZStrType() + _element.dimensions = AAZListType() + _element.display_description = AAZStrType( + serialized_name="displayDescription", + ) + _element.id = AAZStrType() + _element.is_dimension_required = AAZBoolType( + serialized_name="isDimensionRequired", + ) + _element.metric_availabilities = AAZListType( + serialized_name="metricAvailabilities", + ) + _element.metric_class = AAZStrType( + serialized_name="metricClass", + ) + _element.name = AAZObjectType() + _ListDefinitionsHelper._build_schema_localizable_string_read(_element.name) + _element.namespace = AAZStrType() + _element.primary_aggregation_type = AAZStrType( + serialized_name="primaryAggregationType", + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.supported_aggregation_types = AAZListType( + serialized_name="supportedAggregationTypes", + ) + _element.unit = AAZStrType() + + dimensions = cls._schema_on_200.value.Element.dimensions + dimensions.Element = AAZObjectType() + _ListDefinitionsHelper._build_schema_localizable_string_read(dimensions.Element) + + metric_availabilities = cls._schema_on_200.value.Element.metric_availabilities + metric_availabilities.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.metric_availabilities.Element + _element.retention = AAZStrType() + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + supported_aggregation_types = cls._schema_on_200.value.Element.supported_aggregation_types + supported_aggregation_types.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListDefinitionsHelper: + """Helper class for ListDefinitions""" + + _schema_localizable_string_read = None + + @classmethod + def _build_schema_localizable_string_read(cls, _schema): + if cls._schema_localizable_string_read is not None: + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + return + + cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType() + + localizable_string_read = _schema_localizable_string_read + localizable_string_read.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + localizable_string_read.value = AAZStrType( + flags={"required": True}, + ) + + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + + +__all__ = ["ListDefinitions"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_namespaces.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_namespaces.py new file mode 100644 index 00000000000..ac5eab9f8a3 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_namespaces.py @@ -0,0 +1,172 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class ListNamespaces(AAZCommand): + """List the metric namespaces for the resource. + """ + + _aaz_info = { + "version": "2017-12-01-preview", + "resources": [ + ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/metricnamespaces", "2017-12-01-preview"], + ] + } + + 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.resource_uri = AAZStrArg( + options=["--resource-uri"], + help="The identifier of the resource.", + required=True, + ) + _args_schema.start_time = AAZStrArg( + options=["--start-time"], + help="The ISO 8601 conform Date start time from which to query for metric namespaces.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricNamespacesList(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.value, client_flatten=True) + return result + + class MetricNamespacesList(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( + "/{resourceUri}/providers/microsoft.insights/metricNamespaces", + **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( + "resourceUri", self.ctx.args.resource_uri, + skip_quote=True, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "startTime", self.ctx.args.start_time, + ), + **self.serialize_query_param( + "api-version", "2017-12-01-preview", + 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.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.classification = AAZStrType() + _element.id = AAZStrType() + _element.name = AAZStrType() + _element.properties = AAZObjectType() + _element.type = AAZStrType() + + properties = cls._schema_on_200.value.Element.properties + properties.metric_namespace_name = AAZStrType( + serialized_name="metricNamespaceName", + ) + + return cls._schema_on_200 + + +class _ListNamespacesHelper: + """Helper class for ListNamespaces""" + + +__all__ = ["ListNamespaces"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub.py new file mode 100644 index 00000000000..3822c9d9401 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub.py @@ -0,0 +1,334 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics list-sub", +) +class ListSub(AAZCommand): + """Lists the metric data for a subscription. Parameters can be specified on the body. + """ + + _aaz_info = { + "version": "2023-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/metrics", "2023-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.region = AAZStrArg( + options=["--region"], + help="The region where the metrics you want reside.", + required=True, + ) + + # define Arg Group "Body" + + _args_schema = cls._args_schema + _args_schema.aggregation = AAZStrArg( + options=["--aggregation"], + arg_group="Body", + help="The list of aggregation types (comma separated) to retrieve.", + ) + _args_schema.auto_adjust_timegrain = AAZBoolArg( + options=["--auto-adjust-timegrain"], + arg_group="Body", + help="When set to true, if the timespan passed in is not supported by this metric, the API will return the result using the closest supported timespan. When set to false, an error is returned for invalid timespan parameters. Defaults to false.", + ) + _args_schema.filter = AAZStrArg( + options=["--filter"], + arg_group="Body", + help="The **$filter** is used to reduce the set of metric data returned.
Example:
Metric contains metadata A, B and C.
- Return all time series of C where A = a1 and B = b1 or b2
**$filter=A eq ΓÇÿa1ΓÇÖ and B eq ΓÇÿb1ΓÇÖ or B eq ΓÇÿb2ΓÇÖ and C eq ΓÇÿ*ΓÇÖ**
- Invalid variant:
**$filter=A eq ΓÇÿa1ΓÇÖ and B eq ΓÇÿb1ΓÇÖ and C eq ΓÇÿ*ΓÇÖ or B = ΓÇÿb2ΓÇÖ**
This is invalid because the logical or operator cannot separate two different metadata names.
- Return all time series where A = a1, B = b1 and C = c1:
**$filter=A eq ΓÇÿa1ΓÇÖ and B eq ΓÇÿb1ΓÇÖ and C eq ΓÇÿc1ΓÇÖ**
- Return all time series where A = a1
**$filter=A eq ΓÇÿa1ΓÇÖ and B eq ΓÇÿ*ΓÇÖ and C eq ΓÇÿ*ΓÇÖ**.", + ) + _args_schema.interval = AAZStrArg( + options=["--interval"], + arg_group="Body", + help="The interval (i.e. timegrain) of the query in ISO 8601 duration format. Defaults to PT1M. Special case for 'FULL' value that returns single datapoint for entire time span requested. *Examples: PT15M, PT1H, P1D, FULL*", + ) + _args_schema.metricnames = AAZStrArg( + options=["--metricnames"], + arg_group="Body", + help="The names of the metrics (comma separated) to retrieve.", + ) + _args_schema.metricnamespace = AAZStrArg( + options=["--metricnamespace"], + arg_group="Body", + help="Metric namespace where the metrics you want reside.", + ) + _args_schema.order_by = AAZStrArg( + options=["--order-by"], + arg_group="Body", + help="The aggregation to use for sorting results and the direction of the sort. Only one order can be specified. Examples: sum asc.", + ) + _args_schema.result_type = AAZStrArg( + options=["--result-type"], + arg_group="Body", + help="Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details.", + enum={"Data": "Data", "Metadata": "Metadata"}, + ) + _args_schema.roll_up_by = AAZStrArg( + options=["--roll-up-by"], + arg_group="Body", + help="Dimension name(s) to rollup results by. For example if you only want to see metric values with a filter like 'City eq Seattle or City eq Tacoma' but don't want to see separate values for each city, you can specify 'RollUpBy=City' to see the results for Seattle and Tacoma rolled up into one timeseries.", + ) + _args_schema.timespan = AAZStrArg( + options=["--timespan"], + arg_group="Body", + help="The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.", + ) + _args_schema.top = AAZIntArg( + options=["--top"], + arg_group="Body", + help="The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.", + ) + _args_schema.validate_dimensions = AAZBoolArg( + options=["--validate-dimensions"], + arg_group="Body", + help="When set to false, invalid filter parameter values will be ignored. When set to true, an error is returned for invalid filter parameters. Defaults to true.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricsListAtSubscriptionScopePost(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 MetricsListAtSubscriptionScopePost(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}/providers/Microsoft.Insights/metrics", + **self.url_parameters + ) + + @property + def method(self): + return "POST" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "region", self.ctx.args.region, + required=True, + ), + **self.serialize_query_param( + "api-version", "2023-10-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"client_flatten": True}} + ) + _builder.set_prop("aggregation", AAZStrType, ".aggregation") + _builder.set_prop("autoAdjustTimegrain", AAZBoolType, ".auto_adjust_timegrain") + _builder.set_prop("filter", AAZStrType, ".filter") + _builder.set_prop("interval", AAZStrType, ".interval") + _builder.set_prop("metricNames", AAZStrType, ".metricnames") + _builder.set_prop("metricNamespace", AAZStrType, ".metricnamespace") + _builder.set_prop("orderBy", AAZStrType, ".order_by") + _builder.set_prop("resultType", AAZStrType, ".result_type") + _builder.set_prop("rollUpBy", AAZStrType, ".roll_up_by") + _builder.set_prop("timespan", AAZStrType, ".timespan") + _builder.set_prop("top", AAZIntType, ".top") + _builder.set_prop("validateDimensions", AAZBoolType, ".validate_dimensions") + + return self.serialize_content(_content_value) + + 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.cost = AAZIntType() + _schema_on_200.interval = AAZStrType() + _schema_on_200.namespace = AAZStrType() + _schema_on_200.resourceregion = AAZStrType() + _schema_on_200.timespan = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.display_description = AAZStrType( + serialized_name="displayDescription", + ) + _element.error_code = AAZStrType( + serialized_name="errorCode", + ) + _element.error_message = AAZStrType( + serialized_name="errorMessage", + ) + _element.id = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZObjectType( + flags={"required": True}, + ) + _ListSubHelper._build_schema_localizable_string_read(_element.name) + _element.timeseries = AAZListType( + flags={"required": True}, + ) + _element.type = AAZStrType( + flags={"required": True}, + ) + _element.unit = AAZStrType( + flags={"required": True}, + ) + + timeseries = cls._schema_on_200.value.Element.timeseries + timeseries.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element + _element.data = AAZListType() + _element.metadatavalues = AAZListType() + + data = cls._schema_on_200.value.Element.timeseries.Element.data + data.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element.data.Element + _element.average = AAZFloatType() + _element.count = AAZFloatType() + _element.maximum = AAZFloatType() + _element.minimum = AAZFloatType() + _element.time_stamp = AAZStrType( + serialized_name="timeStamp", + flags={"required": True}, + ) + _element.total = AAZFloatType() + + metadatavalues = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues + metadatavalues.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues.Element + _element.name = AAZObjectType() + _ListSubHelper._build_schema_localizable_string_read(_element.name) + _element.value = AAZStrType() + + return cls._schema_on_200 + + +class _ListSubHelper: + """Helper class for ListSub""" + + _schema_localizable_string_read = None + + @classmethod + def _build_schema_localizable_string_read(cls, _schema): + if cls._schema_localizable_string_read is not None: + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + return + + cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType() + + localizable_string_read = _schema_localizable_string_read + localizable_string_read.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + localizable_string_read.value = AAZStrType( + flags={"required": True}, + ) + + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + + +__all__ = ["ListSub"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub_definitions.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub_definitions.py new file mode 100644 index 00000000000..a234360bcbc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/_list_sub_definitions.py @@ -0,0 +1,234 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics list-sub-definitions", +) +class ListSubDefinitions(AAZCommand): + """List the metric definitions for the subscription. + """ + + _aaz_info = { + "version": "2023-10-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/metricdefinitions", "2023-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.metricnamespace = AAZStrArg( + options=["--metricnamespace"], + help="Metric namespace where the metrics you want reside.", + ) + _args_schema.region = AAZStrArg( + options=["--region"], + help="The region where the metrics you want reside.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricDefinitionsListAtSubscriptionScope(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.value, client_flatten=True) + return result + + class MetricDefinitionsListAtSubscriptionScope(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}/providers/Microsoft.Insights/metricDefinitions", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "metricnamespace", self.ctx.args.metricnamespace, + ), + **self.serialize_query_param( + "region", self.ctx.args.region, + required=True, + ), + **self.serialize_query_param( + "api-version", "2023-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.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.category = AAZStrType() + _element.dimensions = AAZListType() + _element.display_description = AAZStrType( + serialized_name="displayDescription", + ) + _element.id = AAZStrType() + _element.is_dimension_required = AAZBoolType( + serialized_name="isDimensionRequired", + ) + _element.metric_availabilities = AAZListType( + serialized_name="metricAvailabilities", + ) + _element.metric_class = AAZStrType( + serialized_name="metricClass", + ) + _element.name = AAZObjectType() + _ListSubDefinitionsHelper._build_schema_localizable_string_read(_element.name) + _element.namespace = AAZStrType() + _element.primary_aggregation_type = AAZStrType( + serialized_name="primaryAggregationType", + ) + _element.resource_id = AAZStrType( + serialized_name="resourceId", + ) + _element.supported_aggregation_types = AAZListType( + serialized_name="supportedAggregationTypes", + ) + _element.unit = AAZStrType() + + dimensions = cls._schema_on_200.value.Element.dimensions + dimensions.Element = AAZObjectType() + _ListSubDefinitionsHelper._build_schema_localizable_string_read(dimensions.Element) + + metric_availabilities = cls._schema_on_200.value.Element.metric_availabilities + metric_availabilities.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.metric_availabilities.Element + _element.retention = AAZStrType() + _element.time_grain = AAZStrType( + serialized_name="timeGrain", + ) + + supported_aggregation_types = cls._schema_on_200.value.Element.supported_aggregation_types + supported_aggregation_types.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListSubDefinitionsHelper: + """Helper class for ListSubDefinitions""" + + _schema_localizable_string_read = None + + @classmethod + def _build_schema_localizable_string_read(cls, _schema): + if cls._schema_localizable_string_read is not None: + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + return + + cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType() + + localizable_string_read = _schema_localizable_string_read + localizable_string_read.localized_value = AAZStrType( + serialized_name="localizedValue", + ) + localizable_string_read.value = AAZStrType( + flags={"required": True}, + ) + + _schema.localized_value = cls._schema_localizable_string_read.localized_value + _schema.value = cls._schema_localizable_string_read.value + + +__all__ = ["ListSubDefinitions"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__cmd_group.py new file mode 100644 index 00000000000..f4ca96e3415 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__cmd_group.py @@ -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 metrics alert", +) +class __CMDGroup(AAZCommandGroup): + """Manage near-realtime metric alert rules. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__init__.py new file mode 100644 index 00000000000..c401f439385 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_create.py new file mode 100644 index 00000000000..18f45ed89ae --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_create.py @@ -0,0 +1,858 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Create(AAZCommand): + """Create a metric-based alert rule. + """ + + _aaz_info = { + "version": "2018-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts/{}", "2018-03-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the alert rule.", + required=True, + ) + + # define Arg Group "Parameters" + + _args_schema = cls._args_schema + _args_schema.location = AAZResourceLocationArg( + arg_group="Parameters", + help="Resource location", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + arg_group="Parameters", + help="Resource tags", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + + # define Arg Group "Properties" + + _args_schema = cls._args_schema + _args_schema.actions = AAZListArg( + options=["--actions"], + arg_group="Properties", + help="the array of actions that are performed when the alert rule becomes active, and when an alert condition is resolved.", + ) + _args_schema.auto_mitigate = AAZBoolArg( + options=["--auto-mitigate"], + arg_group="Properties", + help="the flag that indicates whether the alert should be auto resolved or not. The default is true.", + ) + _args_schema.criteria = AAZObjectArg( + options=["--criteria"], + arg_group="Properties", + help="defines the specific alert criteria information.", + required=True, + ) + _args_schema.description = AAZStrArg( + options=["--description"], + arg_group="Properties", + help="the description of the metric alert that will be included in the alert email.", + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + arg_group="Properties", + help="the flag that indicates whether the metric alert is enabled.", + required=True, + ) + _args_schema.evaluation_frequency = AAZDurationArg( + options=["--evaluation-frequency"], + arg_group="Properties", + help="how often the metric alert is evaluated represented in ISO 8601 duration format.", + required=True, + ) + _args_schema.scopes = AAZListArg( + options=["--scopes"], + arg_group="Properties", + help="the list of resource id's that this metric alert is scoped to.", + required=True, + ) + _args_schema.severity = AAZIntArg( + options=["--severity"], + arg_group="Properties", + help="Alert severity {0, 1, 2, 3, 4}", + required=True, + ) + _args_schema.target_resource_region = AAZStrArg( + options=["--target-resource-region"], + arg_group="Properties", + help="the region of the target resource(s) on which the alert is created/updated. Mandatory if the scope contains a subscription, resource group, or more than one resource.", + ) + _args_schema.target_resource_type = AAZStrArg( + options=["--target-resource-type"], + arg_group="Properties", + help="the resource type of the target resource(s) on which the alert is created/updated. Mandatory if the scope contains a subscription, resource group, or more than one resource.", + ) + _args_schema.window_size = AAZDurationArg( + options=["--window-size"], + arg_group="Properties", + help="the period of time (in ISO 8601 duration format) that is used to monitor alert activity based on the threshold.", + required=True, + ) + + actions = cls._args_schema.actions + actions.Element = AAZObjectArg() + + _element = cls._args_schema.actions.Element + _element.action_group_id = AAZStrArg( + options=["action-group-id"], + help="the id of the action group to use.", + ) + _element.web_hook_properties = AAZDictArg( + options=["web-hook-properties"], + help="This field allows specifying custom properties, which would be appended to the alert payload sent as input to the webhook.", + ) + + web_hook_properties = cls._args_schema.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrArg() + + criteria = cls._args_schema.criteria + criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria = AAZObjectArg( + options=["microsoft-azure-monitor-multiple-resource-multiple-metric-criteria"], + ) + criteria.microsoft_azure_monitor_single_resource_multiple_metric_criteria = AAZObjectArg( + options=["microsoft-azure-monitor-single-resource-multiple-metric-criteria"], + ) + criteria.microsoft_azure_monitor_webtest_location_availability_criteria = AAZObjectArg( + options=["microsoft-azure-monitor-webtest-location-availability-criteria"], + ) + + microsoft_azure_monitor_multiple_resource_multiple_metric_criteria = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria + microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of = AAZListArg( + options=["all-of"], + help="the list of multiple metric criteria for this 'all of' operation. ", + ) + + all_of = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of + all_of.Element = AAZObjectArg() + + _element = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of.Element + _element.dynamic_threshold_criterion = AAZObjectArg( + options=["dynamic-threshold-criterion"], + ) + _element.static_threshold_criterion = AAZObjectArg( + options=["static-threshold-criterion"], + ) + _element.dimensions = AAZListArg( + options=["dimensions"], + help="List of dimension conditions.", + ) + _element.metric_name = AAZStrArg( + options=["metric-name"], + help="Name of the metric.", + required=True, + ) + _element.metric_namespace = AAZStrArg( + options=["metric-namespace"], + help="Namespace of the metric.", + ) + _element.name = AAZStrArg( + options=["name"], + help="Name of the criteria.", + required=True, + ) + _element.skip_metric_validation = AAZBoolArg( + options=["skip-metric-validation"], + help="Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.", + ) + _element.time_aggregation = AAZStrArg( + options=["time-aggregation"], + help="the criteria time aggregation types.", + required=True, + enum={"Average": "Average", "Count": "Count", "Maximum": "Maximum", "Minimum": "Minimum", "Total": "Total"}, + ) + + dynamic_threshold_criterion = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of.Element.dynamic_threshold_criterion + dynamic_threshold_criterion.alert_sensitivity = AAZStrArg( + options=["alert-sensitivity"], + help="The extent of deviation required to trigger an alert. This will affect how tight the threshold is to the metric series pattern.", + required=True, + enum={"High": "High", "Low": "Low", "Medium": "Medium"}, + ) + dynamic_threshold_criterion.failing_periods = AAZObjectArg( + options=["failing-periods"], + help="The minimum number of violations required within the selected lookback time window required to raise an alert.", + required=True, + ) + dynamic_threshold_criterion.ignore_data_before = AAZDateTimeArg( + options=["ignore-data-before"], + help="Use this option to set the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format)", + ) + dynamic_threshold_criterion.operator = AAZStrArg( + options=["operator"], + help="The operator used to compare the metric value against the threshold.", + required=True, + enum={"GreaterOrLessThan": "GreaterOrLessThan", "GreaterThan": "GreaterThan", "LessThan": "LessThan"}, + ) + + failing_periods = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of.Element.dynamic_threshold_criterion.failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatArg( + options=["min-failing-periods-to-alert"], + help="The number of violations to trigger an alert. Should be smaller or equal to numberOfEvaluationPeriods.", + required=True, + ) + failing_periods.number_of_evaluation_periods = AAZFloatArg( + options=["number-of-evaluation-periods"], + help="The number of aggregated lookback points. The lookback time window is calculated based on the aggregation granularity (windowSize) and the selected number of aggregated points.", + required=True, + ) + + static_threshold_criterion = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of.Element.static_threshold_criterion + static_threshold_criterion.operator = AAZStrArg( + options=["operator"], + help="the criteria operator.", + required=True, + enum={"Equals": "Equals", "GreaterThan": "GreaterThan", "GreaterThanOrEqual": "GreaterThanOrEqual", "LessThan": "LessThan", "LessThanOrEqual": "LessThanOrEqual"}, + ) + static_threshold_criterion.threshold = AAZFloatArg( + options=["threshold"], + help="the criteria threshold value that activates the alert.", + required=True, + ) + + dimensions = cls._args_schema.criteria.microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of.Element.dimensions + dimensions.Element = AAZObjectArg() + cls._build_args_metric_dimension_create(dimensions.Element) + + microsoft_azure_monitor_single_resource_multiple_metric_criteria = cls._args_schema.criteria.microsoft_azure_monitor_single_resource_multiple_metric_criteria + microsoft_azure_monitor_single_resource_multiple_metric_criteria.all_of = AAZListArg( + options=["all-of"], + help="The list of metric criteria for this 'all of' operation. ", + ) + + all_of = cls._args_schema.criteria.microsoft_azure_monitor_single_resource_multiple_metric_criteria.all_of + all_of.Element = AAZObjectArg() + + _element = cls._args_schema.criteria.microsoft_azure_monitor_single_resource_multiple_metric_criteria.all_of.Element + _element.dimensions = AAZListArg( + options=["dimensions"], + help="List of dimension conditions.", + ) + _element.metric_name = AAZStrArg( + options=["metric-name"], + help="Name of the metric.", + required=True, + ) + _element.metric_namespace = AAZStrArg( + options=["metric-namespace"], + help="Namespace of the metric.", + ) + _element.name = AAZStrArg( + options=["name"], + help="Name of the criteria.", + required=True, + ) + _element.operator = AAZStrArg( + options=["operator"], + help="the criteria operator.", + required=True, + enum={"Equals": "Equals", "GreaterThan": "GreaterThan", "GreaterThanOrEqual": "GreaterThanOrEqual", "LessThan": "LessThan", "LessThanOrEqual": "LessThanOrEqual"}, + ) + _element.skip_metric_validation = AAZBoolArg( + options=["skip-metric-validation"], + help="Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric validation to be skipped.", + ) + _element.threshold = AAZFloatArg( + options=["threshold"], + help="the criteria threshold value that activates the alert.", + required=True, + ) + _element.time_aggregation = AAZStrArg( + options=["time-aggregation"], + help="the criteria time aggregation types.", + required=True, + enum={"Average": "Average", "Count": "Count", "Maximum": "Maximum", "Minimum": "Minimum", "Total": "Total"}, + ) + + dimensions = cls._args_schema.criteria.microsoft_azure_monitor_single_resource_multiple_metric_criteria.all_of.Element.dimensions + dimensions.Element = AAZObjectArg() + cls._build_args_metric_dimension_create(dimensions.Element) + + microsoft_azure_monitor_webtest_location_availability_criteria = cls._args_schema.criteria.microsoft_azure_monitor_webtest_location_availability_criteria + microsoft_azure_monitor_webtest_location_availability_criteria.component_id = AAZStrArg( + options=["component-id"], + help="The Application Insights resource Id.", + required=True, + ) + microsoft_azure_monitor_webtest_location_availability_criteria.failed_location_count = AAZFloatArg( + options=["failed-location-count"], + help="The number of failed locations.", + required=True, + ) + microsoft_azure_monitor_webtest_location_availability_criteria.web_test_id = AAZStrArg( + options=["web-test-id"], + help="The Application Insights web test Id.", + required=True, + ) + + scopes = cls._args_schema.scopes + scopes.Element = AAZStrArg() + return cls._args_schema + + _args_metric_dimension_create = None + + @classmethod + def _build_args_metric_dimension_create(cls, _schema): + if cls._args_metric_dimension_create is not None: + _schema.name = cls._args_metric_dimension_create.name + _schema.operator = cls._args_metric_dimension_create.operator + _schema.values = cls._args_metric_dimension_create.values + return + + cls._args_metric_dimension_create = AAZObjectArg() + + metric_dimension_create = cls._args_metric_dimension_create + metric_dimension_create.name = AAZStrArg( + options=["name"], + help="Name of the dimension.", + required=True, + ) + metric_dimension_create.operator = AAZStrArg( + options=["operator"], + help="the dimension operator. Only 'Include' and 'Exclude' are supported", + required=True, + ) + metric_dimension_create.values = AAZListArg( + options=["values"], + help="list of dimension values.", + required=True, + ) + + values = cls._args_metric_dimension_create.values + values.Element = AAZStrArg() + + _schema.name = cls._args_metric_dimension_create.name + _schema.operator = cls._args_metric_dimension_create.operator + _schema.values = cls._args_metric_dimension_create.values + + def _execute_operations(self): + self.pre_operations() + self.MetricAlertsCreateOrUpdate(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 MetricAlertsCreateOrUpdate(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/metricAlerts/{ruleName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "ruleName", self.ctx.args.name, + 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( + "api-version", "2018-03-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("actions", AAZListType, ".actions") + properties.set_prop("autoMitigate", AAZBoolType, ".auto_mitigate") + properties.set_prop("criteria", AAZObjectType, ".criteria", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("evaluationFrequency", AAZStrType, ".evaluation_frequency", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("severity", AAZIntType, ".severity", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("targetResourceRegion", AAZStrType, ".target_resource_region") + properties.set_prop("targetResourceType", AAZStrType, ".target_resource_type") + properties.set_prop("windowSize", AAZStrType, ".window_size", typ_kwargs={"flags": {"required": True}}) + + actions = _builder.get(".properties.actions") + if actions is not None: + actions.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.actions[]") + if _elements is not None: + _elements.set_prop("actionGroupId", AAZStrType, ".action_group_id") + _elements.set_prop("webHookProperties", AAZDictType, ".web_hook_properties") + + web_hook_properties = _builder.get(".properties.actions[].webHookProperties") + if web_hook_properties is not None: + web_hook_properties.set_elements(AAZStrType, ".") + + criteria = _builder.get(".properties.criteria") + if criteria is not None: + criteria.set_const("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria", AAZStrType, ".microsoft_azure_monitor_multiple_resource_multiple_metric_criteria", typ_kwargs={"flags": {"required": True}}) + criteria.set_const("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria", AAZStrType, ".microsoft_azure_monitor_single_resource_multiple_metric_criteria", typ_kwargs={"flags": {"required": True}}) + criteria.set_const("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria", AAZStrType, ".microsoft_azure_monitor_webtest_location_availability_criteria", typ_kwargs={"flags": {"required": True}}) + criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}") + if disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria is not None: + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.set_prop("allOf", AAZListType, ".microsoft_azure_monitor_multiple_resource_multiple_metric_criteria.all_of") + + all_of = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf") + if all_of is not None: + all_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf[]") + if _elements is not None: + _elements.set_const("criterionType", "DynamicThresholdCriterion", AAZStrType, ".dynamic_threshold_criterion", typ_kwargs={"flags": {"required": True}}) + _elements.set_const("criterionType", "StaticThresholdCriterion", AAZStrType, ".static_threshold_criterion", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("dimensions", AAZListType, ".dimensions") + _elements.set_prop("metricName", AAZStrType, ".metric_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("metricNamespace", AAZStrType, ".metric_namespace") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("skipMetricValidation", AAZBoolType, ".skip_metric_validation") + _elements.set_prop("timeAggregation", AAZStrType, ".time_aggregation", typ_kwargs={"flags": {"required": True}}) + _elements.discriminate_by("criterionType", "DynamicThresholdCriterion") + _elements.discriminate_by("criterionType", "StaticThresholdCriterion") + + dimensions = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf[].dimensions") + if dimensions is not None: + _CreateHelper._build_schema_metric_dimension_create(dimensions.set_elements(AAZObjectType, ".")) + + disc_dynamic_threshold_criterion = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf[]{criterionType:DynamicThresholdCriterion}") + if disc_dynamic_threshold_criterion is not None: + disc_dynamic_threshold_criterion.set_prop("alertSensitivity", AAZStrType, ".dynamic_threshold_criterion.alert_sensitivity", typ_kwargs={"flags": {"required": True}}) + disc_dynamic_threshold_criterion.set_prop("failingPeriods", AAZObjectType, ".dynamic_threshold_criterion.failing_periods", typ_kwargs={"flags": {"required": True}}) + disc_dynamic_threshold_criterion.set_prop("ignoreDataBefore", AAZStrType, ".dynamic_threshold_criterion.ignore_data_before") + disc_dynamic_threshold_criterion.set_prop("operator", AAZStrType, ".dynamic_threshold_criterion.operator", typ_kwargs={"flags": {"required": True}}) + + failing_periods = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf[]{criterionType:DynamicThresholdCriterion}.failingPeriods") + if failing_periods is not None: + failing_periods.set_prop("minFailingPeriodsToAlert", AAZFloatType, ".min_failing_periods_to_alert", typ_kwargs={"flags": {"required": True}}) + failing_periods.set_prop("numberOfEvaluationPeriods", AAZFloatType, ".number_of_evaluation_periods", typ_kwargs={"flags": {"required": True}}) + + disc_static_threshold_criterion = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria}.allOf[]{criterionType:StaticThresholdCriterion}") + if disc_static_threshold_criterion is not None: + disc_static_threshold_criterion.set_prop("operator", AAZStrType, ".static_threshold_criterion.operator", typ_kwargs={"flags": {"required": True}}) + disc_static_threshold_criterion.set_prop("threshold", AAZFloatType, ".static_threshold_criterion.threshold", typ_kwargs={"flags": {"required": True}}) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria}") + if disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria is not None: + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.set_prop("allOf", AAZListType, ".microsoft_azure_monitor_single_resource_multiple_metric_criteria.all_of") + + all_of = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria}.allOf") + if all_of is not None: + all_of.set_elements(AAZObjectType, ".") + + _elements = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria}.allOf[]") + if _elements is not None: + _elements.set_const("criterionType", "StaticThresholdCriterion", AAZStrType, ".", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("dimensions", AAZListType, ".dimensions") + _elements.set_prop("metricName", AAZStrType, ".metric_name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("metricNamespace", AAZStrType, ".metric_namespace") + _elements.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("skipMetricValidation", AAZBoolType, ".skip_metric_validation") + _elements.set_prop("threshold", AAZFloatType, ".threshold", typ_kwargs={"flags": {"required": True}}) + _elements.set_prop("timeAggregation", AAZStrType, ".time_aggregation", typ_kwargs={"flags": {"required": True}}) + + dimensions = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria}.allOf[].dimensions") + if dimensions is not None: + _CreateHelper._build_schema_metric_dimension_create(dimensions.set_elements(AAZObjectType, ".")) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = _builder.get(".properties.criteria{odata.type:Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria}") + if disc_microsoft__azure__monitor__webtest_location_availability_criteria is not None: + disc_microsoft__azure__monitor__webtest_location_availability_criteria.set_prop("componentId", AAZStrType, ".microsoft_azure_monitor_webtest_location_availability_criteria.component_id", typ_kwargs={"flags": {"required": True}}) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.set_prop("failedLocationCount", AAZFloatType, ".microsoft_azure_monitor_webtest_location_availability_criteria.failed_location_count", typ_kwargs={"flags": {"required": True}}) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.set_prop("webTestId", AAZStrType, ".microsoft_azure_monitor_webtest_location_availability_criteria.web_test_id", typ_kwargs={"flags": {"required": True}}) + + scopes = _builder.get(".properties.scopes") + if scopes is not None: + scopes.set_elements(AAZStrType, ".") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.actions = AAZListType() + properties.auto_mitigate = AAZBoolType( + serialized_name="autoMitigate", + ) + properties.criteria = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.evaluation_frequency = AAZStrType( + serialized_name="evaluationFrequency", + flags={"required": True}, + ) + properties.is_migrated = AAZBoolType( + serialized_name="isMigrated", + flags={"read_only": True}, + ) + properties.last_updated_time = AAZStrType( + serialized_name="lastUpdatedTime", + flags={"read_only": True}, + ) + properties.scopes = AAZListType( + flags={"required": True}, + ) + properties.severity = AAZIntType( + flags={"required": True}, + ) + properties.target_resource_region = AAZStrType( + serialized_name="targetResourceRegion", + ) + properties.target_resource_type = AAZStrType( + serialized_name="targetResourceType", + ) + properties.window_size = AAZStrType( + serialized_name="windowSize", + flags={"required": True}, + ) + + actions = cls._schema_on_200.properties.actions + actions.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.actions.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + ) + _element.web_hook_properties = AAZDictType( + serialized_name="webHookProperties", + ) + + web_hook_properties = cls._schema_on_200.properties.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrType() + + criteria = cls._schema_on_200.properties.criteria + criteria["odata.type"] = AAZStrType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _CreateHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_dynamic_threshold_criterion = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion") + disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType( + serialized_name="alertSensitivity", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.failing_periods = AAZObjectType( + serialized_name="failingPeriods", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType( + serialized_name="ignoreDataBefore", + ) + disc_dynamic_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + + failing_periods = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatType( + serialized_name="minFailingPeriodsToAlert", + flags={"required": True}, + ) + failing_periods.number_of_evaluation_periods = AAZFloatType( + serialized_name="numberOfEvaluationPeriods", + flags={"required": True}, + ) + + disc_static_threshold_criterion = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion") + disc_static_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + disc_static_threshold_criterion.threshold = AAZFloatType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.operator = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.threshold = AAZFloatType( + flags={"required": True}, + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _CreateHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType( + serialized_name="componentId", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType( + serialized_name="failedLocationCount", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType( + serialized_name="webTestId", + flags={"required": True}, + ) + + scopes = cls._schema_on_200.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _CreateHelper: + """Helper class for Create""" + + @classmethod + def _build_schema_metric_dimension_create(cls, _builder): + if _builder is None: + return + _builder.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("values", AAZListType, ".values", typ_kwargs={"flags": {"required": True}}) + + values = _builder.get(".values") + if values is not None: + values.set_elements(AAZStrType, ".") + + _schema_metric_dimension_read = None + + @classmethod + def _build_schema_metric_dimension_read(cls, _schema): + if cls._schema_metric_dimension_read is not None: + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + return + + cls._schema_metric_dimension_read = _schema_metric_dimension_read = AAZObjectType() + + metric_dimension_read = _schema_metric_dimension_read + metric_dimension_read.name = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.operator = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.values = AAZListType( + flags={"required": True}, + ) + + values = _schema_metric_dimension_read.values + values.Element = AAZStrType() + + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_delete.py new file mode 100644 index 00000000000..33c24bea42f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_delete.py @@ -0,0 +1,138 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics alert delete", +) +class Delete(AAZCommand): + """Delete a metrics-based alert rule. + + :example: Delete a metrics-based alert rule. + az monitor metrics alert delete --name MyAlertRule --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2018-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts/{}", "2018-03-01"], + ] + } + + def _handler(self, command_args): + super()._handler(command_args) + self._execute_operations() + return None + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the alert rule.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricAlertsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class MetricAlertsDelete(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) + if session.http_response.status_code in [204]: + return self.on_204(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "ruleName", self.ctx.args.name, + 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( + "api-version", "2018-03-01", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_list.py new file mode 100644 index 00000000000..368f9102904 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_list.py @@ -0,0 +1,692 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics alert list", +) +class List(AAZCommand): + """List metric-based alert rules. + + :example: List metric-based alert rules. + az monitor metrics alert list --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2018-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/metricalerts", "2018-03-01"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts", "2018-03-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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.MetricAlertsListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.MetricAlertsListBySubscription(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.value, client_flatten=True) + return result + + class MetricAlertsListByResourceGroup(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/metricAlerts", + **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( + "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( + "api-version", "2018-03-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.actions = AAZListType() + properties.auto_mitigate = AAZBoolType( + serialized_name="autoMitigate", + ) + properties.criteria = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.evaluation_frequency = AAZStrType( + serialized_name="evaluationFrequency", + flags={"required": True}, + ) + properties.is_migrated = AAZBoolType( + serialized_name="isMigrated", + flags={"read_only": True}, + ) + properties.last_updated_time = AAZStrType( + serialized_name="lastUpdatedTime", + flags={"read_only": True}, + ) + properties.scopes = AAZListType( + flags={"required": True}, + ) + properties.severity = AAZIntType( + flags={"required": True}, + ) + properties.target_resource_region = AAZStrType( + serialized_name="targetResourceRegion", + ) + properties.target_resource_type = AAZStrType( + serialized_name="targetResourceType", + ) + properties.window_size = AAZStrType( + serialized_name="windowSize", + flags={"required": True}, + ) + + actions = cls._schema_on_200.value.Element.properties.actions + actions.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.actions.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + ) + _element.web_hook_properties = AAZDictType( + serialized_name="webHookProperties", + ) + + web_hook_properties = cls._schema_on_200.value.Element.properties.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrType() + + criteria = cls._schema_on_200.value.Element.properties.criteria + criteria["odata.type"] = AAZStrType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ListHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_dynamic_threshold_criterion = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion") + disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType( + serialized_name="alertSensitivity", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.failing_periods = AAZObjectType( + serialized_name="failingPeriods", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType( + serialized_name="ignoreDataBefore", + ) + disc_dynamic_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + + failing_periods = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatType( + serialized_name="minFailingPeriodsToAlert", + flags={"required": True}, + ) + failing_periods.number_of_evaluation_periods = AAZFloatType( + serialized_name="numberOfEvaluationPeriods", + flags={"required": True}, + ) + + disc_static_threshold_criterion = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion") + disc_static_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + disc_static_threshold_criterion.threshold = AAZFloatType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.operator = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.threshold = AAZFloatType( + flags={"required": True}, + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ListHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType( + serialized_name="componentId", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType( + serialized_name="failedLocationCount", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType( + serialized_name="webTestId", + flags={"required": True}, + ) + + scopes = cls._schema_on_200.value.Element.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class MetricAlertsListBySubscription(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}/providers/Microsoft.Insights/metricAlerts", + **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( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2018-03-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.value = AAZListType() + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.actions = AAZListType() + properties.auto_mitigate = AAZBoolType( + serialized_name="autoMitigate", + ) + properties.criteria = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.evaluation_frequency = AAZStrType( + serialized_name="evaluationFrequency", + flags={"required": True}, + ) + properties.is_migrated = AAZBoolType( + serialized_name="isMigrated", + flags={"read_only": True}, + ) + properties.last_updated_time = AAZStrType( + serialized_name="lastUpdatedTime", + flags={"read_only": True}, + ) + properties.scopes = AAZListType( + flags={"required": True}, + ) + properties.severity = AAZIntType( + flags={"required": True}, + ) + properties.target_resource_region = AAZStrType( + serialized_name="targetResourceRegion", + ) + properties.target_resource_type = AAZStrType( + serialized_name="targetResourceType", + ) + properties.window_size = AAZStrType( + serialized_name="windowSize", + flags={"required": True}, + ) + + actions = cls._schema_on_200.value.Element.properties.actions + actions.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.actions.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + ) + _element.web_hook_properties = AAZDictType( + serialized_name="webHookProperties", + ) + + web_hook_properties = cls._schema_on_200.value.Element.properties.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrType() + + criteria = cls._schema_on_200.value.Element.properties.criteria + criteria["odata.type"] = AAZStrType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ListHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_dynamic_threshold_criterion = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion") + disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType( + serialized_name="alertSensitivity", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.failing_periods = AAZObjectType( + serialized_name="failingPeriods", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType( + serialized_name="ignoreDataBefore", + ) + disc_dynamic_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + + failing_periods = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatType( + serialized_name="minFailingPeriodsToAlert", + flags={"required": True}, + ) + failing_periods.number_of_evaluation_periods = AAZFloatType( + serialized_name="numberOfEvaluationPeriods", + flags={"required": True}, + ) + + disc_static_threshold_criterion = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion") + disc_static_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + disc_static_threshold_criterion.threshold = AAZFloatType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.operator = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.threshold = AAZFloatType( + flags={"required": True}, + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ListHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = cls._schema_on_200.value.Element.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType( + serialized_name="componentId", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType( + serialized_name="failedLocationCount", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType( + serialized_name="webTestId", + flags={"required": True}, + ) + + scopes = cls._schema_on_200.value.Element.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + _schema_metric_dimension_read = None + + @classmethod + def _build_schema_metric_dimension_read(cls, _schema): + if cls._schema_metric_dimension_read is not None: + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + return + + cls._schema_metric_dimension_read = _schema_metric_dimension_read = AAZObjectType() + + metric_dimension_read = _schema_metric_dimension_read + metric_dimension_read.name = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.operator = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.values = AAZListType( + flags={"required": True}, + ) + + values = _schema_metric_dimension_read.values + values.Element = AAZStrType() + + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_show.py new file mode 100644 index 00000000000..ffb61f7b3fe --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_show.py @@ -0,0 +1,402 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics alert show", +) +class Show(AAZCommand): + """Show a metrics-based alert rule. + + :example: Show a metrics-based alert rule. + az --name MyAlertRule --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2018-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts/{}", "2018-03-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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the alert rule.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.MetricAlertsGet(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 MetricAlertsGet(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/metricAlerts/{ruleName}", + **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( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "ruleName", self.ctx.args.name, + 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( + "api-version", "2018-03-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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.actions = AAZListType() + properties.auto_mitigate = AAZBoolType( + serialized_name="autoMitigate", + ) + properties.criteria = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.evaluation_frequency = AAZStrType( + serialized_name="evaluationFrequency", + flags={"required": True}, + ) + properties.is_migrated = AAZBoolType( + serialized_name="isMigrated", + flags={"read_only": True}, + ) + properties.last_updated_time = AAZStrType( + serialized_name="lastUpdatedTime", + flags={"read_only": True}, + ) + properties.scopes = AAZListType( + flags={"required": True}, + ) + properties.severity = AAZIntType( + flags={"required": True}, + ) + properties.target_resource_region = AAZStrType( + serialized_name="targetResourceRegion", + ) + properties.target_resource_type = AAZStrType( + serialized_name="targetResourceType", + ) + properties.window_size = AAZStrType( + serialized_name="windowSize", + flags={"required": True}, + ) + + actions = cls._schema_on_200.properties.actions + actions.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.actions.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + ) + _element.web_hook_properties = AAZDictType( + serialized_name="webHookProperties", + ) + + web_hook_properties = cls._schema_on_200.properties.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrType() + + criteria = cls._schema_on_200.properties.criteria + criteria["odata.type"] = AAZStrType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ShowHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_dynamic_threshold_criterion = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion") + disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType( + serialized_name="alertSensitivity", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.failing_periods = AAZObjectType( + serialized_name="failingPeriods", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType( + serialized_name="ignoreDataBefore", + ) + disc_dynamic_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + + failing_periods = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatType( + serialized_name="minFailingPeriodsToAlert", + flags={"required": True}, + ) + failing_periods.number_of_evaluation_periods = AAZFloatType( + serialized_name="numberOfEvaluationPeriods", + flags={"required": True}, + ) + + disc_static_threshold_criterion = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion") + disc_static_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + disc_static_threshold_criterion.threshold = AAZFloatType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.operator = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.threshold = AAZFloatType( + flags={"required": True}, + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + _ShowHelper._build_schema_metric_dimension_read(dimensions.Element) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = cls._schema_on_200.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType( + serialized_name="componentId", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType( + serialized_name="failedLocationCount", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType( + serialized_name="webTestId", + flags={"required": True}, + ) + + scopes = cls._schema_on_200.properties.scopes + scopes.Element = AAZStrType() + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + _schema_metric_dimension_read = None + + @classmethod + def _build_schema_metric_dimension_read(cls, _schema): + if cls._schema_metric_dimension_read is not None: + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + return + + cls._schema_metric_dimension_read = _schema_metric_dimension_read = AAZObjectType() + + metric_dimension_read = _schema_metric_dimension_read + metric_dimension_read.name = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.operator = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.values = AAZListType( + flags={"required": True}, + ) + + values = _schema_metric_dimension_read.values + values.Element = AAZStrType() + + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_update.py new file mode 100644 index 00000000000..1163c306c27 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/metrics/alert/_update.py @@ -0,0 +1,673 @@ +# -------------------------------------------------------------------------------------------- +# 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 metrics alert update", +) +class Update(AAZCommand): + """Update a metric-based alert rule. + + :example: Disable/Enable a metric-based alert rule. + az monitor metrics alert update --enabled false --name MyAlertRule --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2018-03-01", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts/{}", "2018-03-01"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the alert rule.", + required=True, + id_part="name", + ) + _args_schema.auto_mitigate = AAZBoolArg( + options=["--auto-mitigate"], + help="Automatically resolve the alert.", + nullable=True, + ) + _args_schema.description = AAZStrArg( + options=["--description"], + help="Free-text description of the rule.", + nullable=True, + ) + _args_schema.enabled = AAZBoolArg( + options=["--enabled"], + help="Whether the metric alert rule is enabled.", + ) + _args_schema.evaluation_frequency = AAZDurationArg( + options=["--evaluation-frequency"], + help="Frequency with which to evaluate the rule in `##h##m##s` format.", + ) + _args_schema.scopes = AAZListArg( + options=["--scopes"], + help="Space-separated list of scopes the rule applies to. The resources specified in this parameter must be of the same type and exist in the same location.", + ) + _args_schema.severity = AAZIntArg( + options=["--severity"], + help="Severity of the alert from 0 (critical) to 4 (verbose).", + ) + _args_schema.window_size = AAZDurationArg( + options=["--window-size"], + help="Time over which to aggregate metrics in `##h##m##s` format.", + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...].", + nullable=True, + ) + + scopes = cls._args_schema.scopes + scopes.Element = AAZStrArg( + nullable=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + + # define Arg Group "Properties" + return cls._args_schema + + _args_metric_dimension_update = None + + @classmethod + def _build_args_metric_dimension_update(cls, _schema): + if cls._args_metric_dimension_update is not None: + _schema.name = cls._args_metric_dimension_update.name + _schema.operator = cls._args_metric_dimension_update.operator + _schema.values = cls._args_metric_dimension_update.values + return + + cls._args_metric_dimension_update = AAZObjectArg( + nullable=True, + ) + + metric_dimension_update = cls._args_metric_dimension_update + metric_dimension_update.name = AAZStrArg( + options=["name"], + help="Name of the dimension.", + ) + metric_dimension_update.operator = AAZStrArg( + options=["operator"], + help="the dimension operator. Only 'Include' and 'Exclude' are supported", + ) + metric_dimension_update.values = AAZListArg( + options=["values"], + help="list of dimension values.", + ) + + values = cls._args_metric_dimension_update.values + values.Element = AAZStrArg( + nullable=True, + ) + + _schema.name = cls._args_metric_dimension_update.name + _schema.operator = cls._args_metric_dimension_update.operator + _schema.values = cls._args_metric_dimension_update.values + + def _execute_operations(self): + self.pre_operations() + self.MetricAlertsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.MetricAlertsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class MetricAlertsGet(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/metricAlerts/{ruleName}", + **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( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "ruleName", self.ctx.args.name, + 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( + "api-version", "2018-03-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() + _UpdateHelper._build_schema_metric_alert_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class MetricAlertsCreateOrUpdate(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/metricAlerts/{ruleName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "ODataV4Format" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "ruleName", self.ctx.args.name, + 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( + "api-version", "2018-03-01", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_metric_alert_resource_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("autoMitigate", AAZBoolType, ".auto_mitigate") + properties.set_prop("description", AAZStrType, ".description") + properties.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("evaluationFrequency", AAZStrType, ".evaluation_frequency", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("severity", AAZIntType, ".severity", typ_kwargs={"flags": {"required": True}}) + properties.set_prop("windowSize", AAZStrType, ".window_size", typ_kwargs={"flags": {"required": True}}) + + scopes = _builder.get(".properties.scopes") + if scopes is not None: + scopes.set_elements(AAZStrType, ".") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + @classmethod + def _build_schema_metric_dimension_update(cls, _builder): + if _builder is None: + return + _builder.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("values", AAZListType, ".values", typ_kwargs={"flags": {"required": True}}) + + values = _builder.get(".values") + if values is not None: + values.set_elements(AAZStrType, ".") + + _schema_metric_alert_resource_read = None + + @classmethod + def _build_schema_metric_alert_resource_read(cls, _schema): + if cls._schema_metric_alert_resource_read is not None: + _schema.id = cls._schema_metric_alert_resource_read.id + _schema.location = cls._schema_metric_alert_resource_read.location + _schema.name = cls._schema_metric_alert_resource_read.name + _schema.properties = cls._schema_metric_alert_resource_read.properties + _schema.tags = cls._schema_metric_alert_resource_read.tags + _schema.type = cls._schema_metric_alert_resource_read.type + return + + cls._schema_metric_alert_resource_read = _schema_metric_alert_resource_read = AAZObjectType() + + metric_alert_resource_read = _schema_metric_alert_resource_read + metric_alert_resource_read.id = AAZStrType( + flags={"read_only": True}, + ) + metric_alert_resource_read.location = AAZStrType( + flags={"required": True}, + ) + metric_alert_resource_read.name = AAZStrType( + flags={"read_only": True}, + ) + metric_alert_resource_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + metric_alert_resource_read.tags = AAZDictType() + metric_alert_resource_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_metric_alert_resource_read.properties + properties.actions = AAZListType() + properties.auto_mitigate = AAZBoolType( + serialized_name="autoMitigate", + ) + properties.criteria = AAZObjectType( + flags={"required": True}, + ) + properties.description = AAZStrType() + properties.enabled = AAZBoolType( + flags={"required": True}, + ) + properties.evaluation_frequency = AAZStrType( + serialized_name="evaluationFrequency", + flags={"required": True}, + ) + properties.is_migrated = AAZBoolType( + serialized_name="isMigrated", + flags={"read_only": True}, + ) + properties.last_updated_time = AAZStrType( + serialized_name="lastUpdatedTime", + flags={"read_only": True}, + ) + properties.scopes = AAZListType( + flags={"required": True}, + ) + properties.severity = AAZIntType( + flags={"required": True}, + ) + properties.target_resource_region = AAZStrType( + serialized_name="targetResourceRegion", + ) + properties.target_resource_type = AAZStrType( + serialized_name="targetResourceType", + ) + properties.window_size = AAZStrType( + serialized_name="windowSize", + flags={"required": True}, + ) + + actions = _schema_metric_alert_resource_read.properties.actions + actions.Element = AAZObjectType() + + _element = _schema_metric_alert_resource_read.properties.actions.Element + _element.action_group_id = AAZStrType( + serialized_name="actionGroupId", + ) + _element.web_hook_properties = AAZDictType( + serialized_name="webHookProperties", + ) + + web_hook_properties = _schema_metric_alert_resource_read.properties.actions.Element.web_hook_properties + web_hook_properties.Element = AAZStrType() + + criteria = _schema_metric_alert_resource_read.properties.criteria + criteria["odata.type"] = AAZStrType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + cls._build_schema_metric_dimension_read(dimensions.Element) + + disc_dynamic_threshold_criterion = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion") + disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType( + serialized_name="alertSensitivity", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.failing_periods = AAZObjectType( + serialized_name="failingPeriods", + flags={"required": True}, + ) + disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType( + serialized_name="ignoreDataBefore", + ) + disc_dynamic_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + + failing_periods = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods + failing_periods.min_failing_periods_to_alert = AAZFloatType( + serialized_name="minFailingPeriodsToAlert", + flags={"required": True}, + ) + failing_periods.number_of_evaluation_periods = AAZFloatType( + serialized_name="numberOfEvaluationPeriods", + flags={"required": True}, + ) + + disc_static_threshold_criterion = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion") + disc_static_threshold_criterion.operator = AAZStrType( + flags={"required": True}, + ) + disc_static_threshold_criterion.threshold = AAZFloatType( + flags={"required": True}, + ) + + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria") + disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType( + serialized_name="allOf", + ) + + all_of = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of + all_of.Element = AAZObjectType() + + _element = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element + _element.criterion_type = AAZStrType( + serialized_name="criterionType", + flags={"required": True}, + ) + _element.dimensions = AAZListType() + _element.metric_name = AAZStrType( + serialized_name="metricName", + flags={"required": True}, + ) + _element.metric_namespace = AAZStrType( + serialized_name="metricNamespace", + ) + _element.name = AAZStrType( + flags={"required": True}, + ) + _element.operator = AAZStrType( + flags={"required": True}, + ) + _element.skip_metric_validation = AAZBoolType( + serialized_name="skipMetricValidation", + ) + _element.threshold = AAZFloatType( + flags={"required": True}, + ) + _element.time_aggregation = AAZStrType( + serialized_name="timeAggregation", + flags={"required": True}, + ) + + dimensions = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions + dimensions.Element = AAZObjectType() + cls._build_schema_metric_dimension_read(dimensions.Element) + + disc_microsoft__azure__monitor__webtest_location_availability_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria") + disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType( + serialized_name="componentId", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType( + serialized_name="failedLocationCount", + flags={"required": True}, + ) + disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType( + serialized_name="webTestId", + flags={"required": True}, + ) + + scopes = _schema_metric_alert_resource_read.properties.scopes + scopes.Element = AAZStrType() + + tags = _schema_metric_alert_resource_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_metric_alert_resource_read.id + _schema.location = cls._schema_metric_alert_resource_read.location + _schema.name = cls._schema_metric_alert_resource_read.name + _schema.properties = cls._schema_metric_alert_resource_read.properties + _schema.tags = cls._schema_metric_alert_resource_read.tags + _schema.type = cls._schema_metric_alert_resource_read.type + + _schema_metric_dimension_read = None + + @classmethod + def _build_schema_metric_dimension_read(cls, _schema): + if cls._schema_metric_dimension_read is not None: + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + return + + cls._schema_metric_dimension_read = _schema_metric_dimension_read = AAZObjectType() + + metric_dimension_read = _schema_metric_dimension_read + metric_dimension_read.name = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.operator = AAZStrType( + flags={"required": True}, + ) + metric_dimension_read.values = AAZListType( + flags={"required": True}, + ) + + values = _schema_metric_dimension_read.values + values.Element = AAZStrType() + + _schema.name = cls._schema_metric_dimension_read.name + _schema.operator = cls._schema_metric_dimension_read.operator + _schema.values = cls._schema_metric_dimension_read.values + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__cmd_group.py new file mode 100644 index 00000000000..a58928ef427 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage monitor private link scope resource. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__init__.py new file mode 100644 index 00000000000..db73033039b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/__init__.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_create.py new file mode 100644 index 00000000000..feee5058acc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_create.py @@ -0,0 +1,271 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope create", + is_preview=True, +) +class Create(AAZCommand): + """Create a private link scope resource. + + :example: Create a private link scope resource. + az monitor private-link-scope create --name MyAzureMonitorPrivateLinkScope --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}", "2019-10-17-preview"], + ] + } + + 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.location = AAZResourceLocationArg( + help="Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=`.", + required=True, + fmt=AAZResourceLocationArgFormat( + resource_group_arg="resource_group", + ), + ) + _args_schema.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...].", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopesCreateOrUpdate(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 PrivateLinkScopesCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}}) + _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}}) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200_201.tags = AAZDictType() + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200_201.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200_201.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200_201.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = cls._schema_on_200_201.tags + tags.Element = AAZStrType() + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_delete.py new file mode 100644 index 00000000000..054593ac17e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_delete.py @@ -0,0 +1,164 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope delete", + is_preview=True, + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a monitor private link scope resource. + + :example: Delete a monitor private link scope resource. + az monitor private-link-scope delete --name MyAzureMonitorPrivateLinkScope --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.PrivateLinkScopesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class PrivateLinkScopesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_list.py new file mode 100644 index 00000000000..85dcd80efd8 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_list.py @@ -0,0 +1,405 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope list", + is_preview=True, +) +class List(AAZCommand): + """List all monitor private link scope resources. + + :example: List all monitor private link scope resources. + az monitor private-link-scope list --name MyAzureMonitorPrivateLinkScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/privatelinkscopes", "2019-10-17-preview"], + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg() + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + condition_0 = has_value(self.ctx.args.resource_group) and has_value(self.ctx.subscription_id) + condition_1 = has_value(self.ctx.subscription_id) and has_value(self.ctx.args.resource_group) is not True + if condition_0: + self.PrivateLinkScopesListByResourceGroup(ctx=self.ctx)() + if condition_1: + self.PrivateLinkScopesList(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class PrivateLinkScopesListByResourceGroup(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/privateLinkScopes", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **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( + "api-version", "2019-10-17-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.value.Element.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + class PrivateLinkScopesList(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}/providers/microsoft.insights/privateLinkScopes", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "subscriptionId", self.ctx.subscription_id, + required=True, + ), + } + return parameters + + @property + def query_parameters(self): + parameters = { + **self.serialize_query_param( + "api-version", "2019-10-17-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + ) + _schema_on_200.value = AAZListType( + flags={"required": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.location = AAZStrType( + flags={"required": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _element.tags = AAZDictType() + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.value.Element.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.value.Element.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.value.Element.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_show.py new file mode 100644 index 00000000000..663c135a244 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_show.py @@ -0,0 +1,238 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope show", + is_preview=True, +) +class Show(AAZCommand): + """Show a monitor private link scope resource. + + :example: Show a monitor private link scope resource. + az monitor private-link-scope show --name MyAzureMonitorPrivateLinkScope --resource-group MyResourceGroup + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}", "2019-10-17-preview"], + ] + } + + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopesGet(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 PrivateLinkScopesGet(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/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_update.py new file mode 100644 index 00000000000..ccc1dc1ffa9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_update.py @@ -0,0 +1,408 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope update", + is_preview=True, +) +class Update(AAZCommand): + """Update a monitor private link scope resource. + + :example: Update a monitor private link scope resource. + az monitor private-link-scope update --name MyAzureMonitorPrivateLinkScope --resource-group MyResourceGroup --tags foo=bar + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_GENERIC_UPDATE = True + + 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.tags = AAZDictArg( + options=["--tags"], + help="Space-separated tags: key[=value] [key[=value] ...].", + nullable=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + + tags = cls._args_schema.tags + tags.Element = AAZStrArg( + nullable=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopesGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + self.PrivateLinkScopesCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class PrivateLinkScopesGet(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/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + 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() + _UpdateHelper._build_schema_azure_monitor_private_link_scope_read(cls._schema_on_200) + + return cls._schema_on_200 + + class PrivateLinkScopesCreateOrUpdate(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, 201]: + return self.on_200_201(session) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + _UpdateHelper._build_schema_azure_monitor_private_link_scope_read(cls._schema_on_200_201) + + return cls._schema_on_200_201 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("tags", AAZDictType, ".tags") + + tags = _builder.get(".tags") + if tags is not None: + tags.set_elements(AAZStrType, ".") + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_azure_monitor_private_link_scope_read = None + + @classmethod + def _build_schema_azure_monitor_private_link_scope_read(cls, _schema): + if cls._schema_azure_monitor_private_link_scope_read is not None: + _schema.id = cls._schema_azure_monitor_private_link_scope_read.id + _schema.location = cls._schema_azure_monitor_private_link_scope_read.location + _schema.name = cls._schema_azure_monitor_private_link_scope_read.name + _schema.properties = cls._schema_azure_monitor_private_link_scope_read.properties + _schema.tags = cls._schema_azure_monitor_private_link_scope_read.tags + _schema.type = cls._schema_azure_monitor_private_link_scope_read.type + return + + cls._schema_azure_monitor_private_link_scope_read = _schema_azure_monitor_private_link_scope_read = AAZObjectType() + + azure_monitor_private_link_scope_read = _schema_azure_monitor_private_link_scope_read + azure_monitor_private_link_scope_read.id = AAZStrType( + flags={"read_only": True}, + ) + azure_monitor_private_link_scope_read.location = AAZStrType( + flags={"required": True}, + ) + azure_monitor_private_link_scope_read.name = AAZStrType( + flags={"read_only": True}, + ) + azure_monitor_private_link_scope_read.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + azure_monitor_private_link_scope_read.tags = AAZDictType() + azure_monitor_private_link_scope_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_azure_monitor_private_link_scope_read.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = _schema_azure_monitor_private_link_scope_read.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = _schema_azure_monitor_private_link_scope_read.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_azure_monitor_private_link_scope_read.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = _schema_azure_monitor_private_link_scope_read.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = _schema_azure_monitor_private_link_scope_read.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = _schema_azure_monitor_private_link_scope_read.tags + tags.Element = AAZStrType() + + _schema.id = cls._schema_azure_monitor_private_link_scope_read.id + _schema.location = cls._schema_azure_monitor_private_link_scope_read.location + _schema.name = cls._schema_azure_monitor_private_link_scope_read.name + _schema.properties = cls._schema_azure_monitor_private_link_scope_read.properties + _schema.tags = cls._schema_azure_monitor_private_link_scope_read.tags + _schema.type = cls._schema_azure_monitor_private_link_scope_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_wait.py new file mode 100644 index 00000000000..18a0c733693 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/_wait.py @@ -0,0 +1,233 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}", "2019-10-17-preview"], + ] + } + + 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopesGet(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=False) + return result + + class PrivateLinkScopesGet(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/privateLinkScopes/{scopeName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.location = AAZStrType( + flags={"required": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"required": True, "client_flatten": True}, + ) + _schema_on_200.tags = AAZDictType() + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.private_endpoint_connections = AAZListType( + serialized_name="privateEndpointConnections", + flags={"read_only": True}, + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint_connections = cls._schema_on_200.properties.private_endpoint_connections + private_endpoint_connections.Element = AAZObjectType() + + _element = cls._schema_on_200.properties.private_endpoint_connections.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties.private_endpoint_connections.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.properties.private_endpoint_connections.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + tags = cls._schema_on_200.tags + tags.Element = AAZStrType() + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__cmd_group.py new file mode 100644 index 00000000000..51676cfe96f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-endpoint-connection", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage private endpoint connection of a private link scope resource. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py new file mode 100644 index 00000000000..f32b66e3eeb --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._delete import * +from ._list import * +from ._show import * +from ._update import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py new file mode 100644 index 00000000000..46dcccf9864 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py @@ -0,0 +1,174 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-endpoint-connection delete", + is_preview=True, + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a private endpoint connection of a private link scope resource. + + :example: Delete a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection delete -n MyName -g MyResourceGroup --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privateendpointconnections/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the private endpoint connection associated with the private link scope.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.PrivateEndpointConnectionsDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class PrivateEndpointConnectionsDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "privateEndpointConnectionName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_list.py new file mode 100644 index 00000000000..391f64b53d2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_list.py @@ -0,0 +1,217 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-endpoint-connection list", + is_preview=True, +) +class List(AAZCommand): + """List all private endpoint connections on a private link scope. + + :example: List all private endpoint connections on a private link scope. + az monitor private-link-scope private-endpoint-connection list -g MyResourceGroup --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privateendpointconnections", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateEndpointConnectionsListByPrivateLinkScope(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class PrivateEndpointConnectionsListByPrivateLinkScope(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/privateLinkScopes/{scopeName}/privateEndpointConnections", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + flags={"read_only": True}, + ) + _schema_on_200.value = AAZListType( + flags={"read_only": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.value.Element.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.value.Element.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_show.py new file mode 100644 index 00000000000..b3d9a7c193c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_show.py @@ -0,0 +1,214 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-endpoint-connection show", + is_preview=True, +) +class Show(AAZCommand): + """Show a private endpoint connection of a private link scope resource. + + :example: Show a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection show -n MyName -g MyResourceGroup --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privateendpointconnections/{}", "2019-10-17-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the private endpoint connection associated with the private link scope.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateEndpointConnectionsGet(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 PrivateEndpointConnectionsGet(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/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "privateEndpointConnectionName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_update.py new file mode 100644 index 00000000000..bf26415ddce --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_update.py @@ -0,0 +1,407 @@ +# -------------------------------------------------------------------------------------------- +# 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 * + + +class Update(AAZCommand): + """Update a private endpoint connection with a given name. + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privateendpointconnections/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + AZ_SUPPORT_GENERIC_UPDATE = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the private endpoint connection associated with the private link scope.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + _args_schema.id = AAZStrArg( + options=["--id"], + help="ID of the private endpoint connection associated with the private link scope. Values from `az monitor private-link-scope show`.", + nullable=True, + ) + _args_schema.description = AAZStrArg( + options=["--description"], + help="Description of private link service connection.", + ) + _args_schema.status = AAZStrArg( + options=["--status"], + help="Status of private link service connection.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateEndpointConnectionsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.vars.instance) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.InstanceUpdateByGeneric(ctx=self.ctx)() + self.post_instance_update(self.ctx.vars.instance) + yield self.PrivateEndpointConnectionsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + @register_callback + def pre_instance_update(self, instance): + pass + + @register_callback + def post_instance_update(self, instance): + pass + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + class PrivateEndpointConnectionsGet(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/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "privateEndpointConnectionName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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() + _UpdateHelper._build_schema_private_endpoint_connection_read(cls._schema_on_200) + + return cls._schema_on_200 + + class PrivateEndpointConnectionsCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "privateEndpointConnectionName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + value=self.ctx.vars.instance, + ) + + return self.serialize_content(_content_value) + + 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() + _UpdateHelper._build_schema_private_endpoint_connection_read(cls._schema_on_200) + + return cls._schema_on_200 + + class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.vars.instance) + + def _update_instance(self, instance): + _instance_value, _builder = self.new_content_builder( + self.ctx.args, + value=instance, + typ=AAZObjectType + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("privateEndpoint", AAZObjectType) + properties.set_prop("privateLinkServiceConnectionState", AAZObjectType) + + private_endpoint = _builder.get(".properties.privateEndpoint") + if private_endpoint is not None: + private_endpoint.set_prop("id", AAZStrType, ".id") + + private_link_service_connection_state = _builder.get(".properties.privateLinkServiceConnectionState") + if private_link_service_connection_state is not None: + private_link_service_connection_state.set_prop("description", AAZStrType, ".description", typ_kwargs={"flags": {"required": True}}) + private_link_service_connection_state.set_prop("status", AAZStrType, ".status", typ_kwargs={"flags": {"required": True}}) + + return _instance_value + + class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation): + + def __call__(self, *args, **kwargs): + self._update_instance_by_generic( + self.ctx.vars.instance, + self.ctx.generic_update_args + ) + + +class _UpdateHelper: + """Helper class for Update""" + + _schema_private_endpoint_connection_read = None + + @classmethod + def _build_schema_private_endpoint_connection_read(cls, _schema): + if cls._schema_private_endpoint_connection_read is not None: + _schema.id = cls._schema_private_endpoint_connection_read.id + _schema.name = cls._schema_private_endpoint_connection_read.name + _schema.properties = cls._schema_private_endpoint_connection_read.properties + _schema.type = cls._schema_private_endpoint_connection_read.type + return + + cls._schema_private_endpoint_connection_read = _schema_private_endpoint_connection_read = AAZObjectType() + + private_endpoint_connection_read = _schema_private_endpoint_connection_read + private_endpoint_connection_read.id = AAZStrType( + flags={"read_only": True}, + ) + private_endpoint_connection_read.name = AAZStrType( + flags={"read_only": True}, + ) + private_endpoint_connection_read.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + private_endpoint_connection_read.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = _schema_private_endpoint_connection_read.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = _schema_private_endpoint_connection_read.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = _schema_private_endpoint_connection_read.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + _schema.id = cls._schema_private_endpoint_connection_read.id + _schema.name = cls._schema_private_endpoint_connection_read.name + _schema.properties = cls._schema_private_endpoint_connection_read.properties + _schema.type = cls._schema_private_endpoint_connection_read.type + + +__all__ = ["Update"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_wait.py new file mode 100644 index 00000000000..aae75ae95a6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_endpoint_connection/_wait.py @@ -0,0 +1,209 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-endpoint-connection wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privateendpointconnections/{}", "2019-10-17-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the private endpoint connection associated with the private link scope.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateEndpointConnectionsGet(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=False) + return result + + class PrivateEndpointConnectionsGet(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/privateLinkScopes/{scopeName}/privateEndpointConnections/{privateEndpointConnectionName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "privateEndpointConnectionName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.private_endpoint = AAZObjectType( + serialized_name="privateEndpoint", + ) + properties.private_link_service_connection_state = AAZObjectType( + serialized_name="privateLinkServiceConnectionState", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + private_endpoint = cls._schema_on_200.properties.private_endpoint + private_endpoint.id = AAZStrType() + + private_link_service_connection_state = cls._schema_on_200.properties.private_link_service_connection_state + private_link_service_connection_state.actions_required = AAZStrType( + serialized_name="actionsRequired", + flags={"read_only": True}, + ) + private_link_service_connection_state.description = AAZStrType( + flags={"required": True}, + ) + private_link_service_connection_state.status = AAZStrType( + flags={"required": True}, + ) + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__cmd_group.py new file mode 100644 index 00000000000..3776063f024 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-link-resource", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage private link resource of a private link scope resource. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py new file mode 100644 index 00000000000..2df85698253 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py @@ -0,0 +1,13 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._list import * +from ._show import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_list.py new file mode 100644 index 00000000000..493f328c801 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_list.py @@ -0,0 +1,203 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-link-resource list", + is_preview=True, +) +class List(AAZCommand): + """List all private link resources of a private link scope resource. + + :example: List all private link resources of a private link scope resource. + az monitor private-link-scope private-link-resource list --scope-name MyScope -g MyResourceGroup + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privatelinkresources", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkResourcesListByPrivateLinkScope(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class PrivateLinkResourcesListByPrivateLinkScope(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/privateLinkScopes/{scopeName}/privateLinkResources", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + flags={"read_only": True}, + ) + _schema_on_200.value = AAZListType( + flags={"read_only": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.group_id = AAZStrType( + serialized_name="groupId", + flags={"read_only": True}, + ) + properties.required_members = AAZListType( + serialized_name="requiredMembers", + flags={"read_only": True}, + ) + + required_members = cls._schema_on_200.value.Element.properties.required_members + required_members.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_show.py new file mode 100644 index 00000000000..0293b44dd80 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/private_link_resource/_show.py @@ -0,0 +1,200 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope private-link-resource show", + is_preview=True, +) +class Show(AAZCommand): + """Show a private link resource of a private link scope resource. + + :example: Show a private link resource of a private link scope resource. + az monitor private-link-scope scoped-resource show -n MyName -g MyResourceGroup --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/privatelinkresources/{}", "2019-10-17-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the private link resource.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkResourcesGet(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 PrivateLinkResourcesGet(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/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "groupName", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.group_id = AAZStrType( + serialized_name="groupId", + flags={"read_only": True}, + ) + properties.required_members = AAZListType( + serialized_name="requiredMembers", + flags={"read_only": True}, + ) + + required_members = cls._schema_on_200.properties.required_members + required_members.Element = AAZStrType() + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__cmd_group.py new file mode 100644 index 00000000000..d8a87bccf3b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__cmd_group.py @@ -0,0 +1,24 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource", + is_preview=True, +) +class __CMDGroup(AAZCommandGroup): + """Manage scoped resource of a private link scope resource. + """ + pass + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py new file mode 100644 index 00000000000..2d1a2078686 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------------------------- +# 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 ._create import * +from ._delete import * +from ._list import * +from ._show import * +from ._wait import * diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_create.py new file mode 100644 index 00000000000..3de635b3a3d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_create.py @@ -0,0 +1,233 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource create", + is_preview=True, +) +class Create(AAZCommand): + """Create a scoped resource for a private link scope resource. + + :example: Create a scoped resource for a private link scope resource. + az monitor private-link-scope scoped-resource create -g MyResourceGroup -n MyName --linked-resource MyID --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/scopedresources/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the assigned resource.", + required=True, + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + ) + _args_schema.linked_resource = AAZStrArg( + options=["--linked-resource"], + help="ARM resource ID of the linked resource. It should be one of log analytics workspace or application insights component.", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.PrivateLinkScopedResourcesCreateOrUpdate(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 PrivateLinkScopedResourcesCreateOrUpdate(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200, 201]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200_201, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "PUT" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + @property + def header_parameters(self): + parameters = { + **self.serialize_header_param( + "Content-Type", "application/json", + ), + **self.serialize_header_param( + "Accept", "application/json", + ), + } + return parameters + + @property + def content(self): + _content_value, _builder = self.new_content_builder( + self.ctx.args, + typ=AAZObjectType, + typ_kwargs={"flags": {"required": True, "client_flatten": True}} + ) + _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}}) + + properties = _builder.get(".properties") + if properties is not None: + properties.set_prop("linkedResourceId", AAZStrType, ".linked_resource") + + return self.serialize_content(_content_value) + + def on_200_201(self, session): + data = self.deserialize_http_content(session) + self.ctx.set_var( + "instance", + data, + schema_builder=self._build_schema_on_200_201 + ) + + _schema_on_200_201 = None + + @classmethod + def _build_schema_on_200_201(cls): + if cls._schema_on_200_201 is not None: + return cls._schema_on_200_201 + + cls._schema_on_200_201 = AAZObjectType() + + _schema_on_200_201 = cls._schema_on_200_201 + _schema_on_200_201.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200_201.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200_201.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200_201.properties + properties.linked_resource_id = AAZStrType( + serialized_name="linkedResourceId", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + return cls._schema_on_200_201 + + +class _CreateHelper: + """Helper class for Create""" + + +__all__ = ["Create"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_delete.py new file mode 100644 index 00000000000..8452223cc7e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_delete.py @@ -0,0 +1,174 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource delete", + is_preview=True, + confirmation="Are you sure you want to perform this operation?", +) +class Delete(AAZCommand): + """Delete a scoped resource of a private link scope resource. + + :example: Delete a scoped resource of a private link scope resource. + az monitor private-link-scope scoped-resource delete -g MyResourceGroup -n MyName --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/scopedresources/{}", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_NO_WAIT = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_lro_poller(self._execute_operations, None) + + _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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the assigned resource.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + yield self.PrivateLinkScopedResourcesDelete(ctx=self.ctx)() + self.post_operations() + + @register_callback + def pre_operations(self): + pass + + @register_callback + def post_operations(self): + pass + + class PrivateLinkScopedResourcesDelete(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 [202]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [200]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_200, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + if session.http_response.status_code in [204]: + return self.client.build_lro_polling( + self.ctx.args.no_wait, + session, + self.on_204, + self.on_error, + lro_options={"final-state-via": "azure-async-operation"}, + path_format_arguments=self.url_parameters, + ) + + return self.on_error(session.http_response) + + @property + def url(self): + return self.client.format_url( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/privateLinkScopes/{scopeName}/scopedResources/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "DELETE" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + required=True, + ), + } + return parameters + + def on_200(self, session): + pass + + def on_204(self, session): + pass + + +class _DeleteHelper: + """Helper class for Delete""" + + +__all__ = ["Delete"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_list.py new file mode 100644 index 00000000000..bae9feecce2 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_list.py @@ -0,0 +1,199 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource list", + is_preview=True, +) +class List(AAZCommand): + """List all scoped resource of a private link scope resource. + + :example: List all scoped resource of a private link scope resource. + az monitor private-link-scope scoped-resource list -g MyResourceGroup --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/scopedresources", "2019-10-17-preview"], + ] + } + + AZ_SUPPORT_PAGINATION = True + + def _handler(self, command_args): + super()._handler(command_args) + return self.build_paging(self._execute_operations, 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.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopedResourcesListByPrivateLinkScope(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.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + class PrivateLinkScopedResourcesListByPrivateLinkScope(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/privateLinkScopes/{scopeName}/scopedResources", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.next_link = AAZStrType( + serialized_name="nextLink", + flags={"read_only": True}, + ) + _schema_on_200.value = AAZListType( + flags={"read_only": True}, + ) + + value = cls._schema_on_200.value + value.Element = AAZObjectType() + + _element = cls._schema_on_200.value.Element + _element.id = AAZStrType( + flags={"read_only": True}, + ) + _element.name = AAZStrType( + flags={"read_only": True}, + ) + _element.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _element.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.value.Element.properties + properties.linked_resource_id = AAZStrType( + serialized_name="linkedResourceId", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +class _ListHelper: + """Helper class for List""" + + +__all__ = ["List"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_show.py new file mode 100644 index 00000000000..31d99e8c6c4 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_show.py @@ -0,0 +1,196 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource show", + is_preview=True, +) +class Show(AAZCommand): + """Show a scoped resource of a private link scope resource. + + :example: Show a scoped resource of a private link scope resource. + az monitor private-link-scope scoped-resource show -g MyResourceGroup -n MyName --scope-name MyScope + """ + + _aaz_info = { + "version": "2019-10-17-preview", + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/scopedresources/{}", "2019-10-17-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the assigned resource.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopedResourcesGet(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 PrivateLinkScopedResourcesGet(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/privateLinkScopes/{scopeName}/scopedResources/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.linked_resource_id = AAZStrType( + serialized_name="linkedResourceId", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +class _ShowHelper: + """Helper class for Show""" + + +__all__ = ["Show"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_wait.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_wait.py new file mode 100644 index 00000000000..d2fa3ab0552 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/aaz/latest/monitor/private_link_scope/scoped_resource/_wait.py @@ -0,0 +1,191 @@ +# -------------------------------------------------------------------------------------------- +# 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 private-link-scope scoped-resource wait", +) +class Wait(AAZWaitCommand): + """Place the CLI in a waiting state until a condition is met. + """ + + _aaz_info = { + "resources": [ + ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/privatelinkscopes/{}/scopedresources/{}", "2019-10-17-preview"], + ] + } + + 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.name = AAZStrArg( + options=["-n", "--name"], + help="Name of the assigned resource.", + required=True, + id_part="child_name_1", + ) + _args_schema.resource_group = AAZResourceGroupNameArg( + required=True, + ) + _args_schema.scope_name = AAZStrArg( + options=["--scope-name"], + help="Name of the Azure Monitor Private Link Scope.", + required=True, + id_part="name", + ) + return cls._args_schema + + def _execute_operations(self): + self.pre_operations() + self.PrivateLinkScopedResourcesGet(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=False) + return result + + class PrivateLinkScopedResourcesGet(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/privateLinkScopes/{scopeName}/scopedResources/{name}", + **self.url_parameters + ) + + @property + def method(self): + return "GET" + + @property + def error_format(self): + return "MgmtErrorFormat" + + @property + def url_parameters(self): + parameters = { + **self.serialize_url_param( + "name", self.ctx.args.name, + required=True, + ), + **self.serialize_url_param( + "resourceGroupName", self.ctx.args.resource_group, + required=True, + ), + **self.serialize_url_param( + "scopeName", self.ctx.args.scope_name, + 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( + "api-version", "2019-10-17-preview", + 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.id = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.name = AAZStrType( + flags={"read_only": True}, + ) + _schema_on_200.properties = AAZObjectType( + flags={"client_flatten": True}, + ) + _schema_on_200.type = AAZStrType( + flags={"read_only": True}, + ) + + properties = cls._schema_on_200.properties + properties.linked_resource_id = AAZStrType( + serialized_name="linkedResourceId", + ) + properties.provisioning_state = AAZStrType( + serialized_name="provisioningState", + flags={"read_only": True}, + ) + + return cls._schema_on_200 + + +class _WaitHelper: + """Helper class for Wait""" + + +__all__ = ["Wait"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/actions.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/actions.py new file mode 100644 index 00000000000..3fa7edeac98 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/actions.py @@ -0,0 +1,583 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, too-few-public-methods +import copy +import argparse + +from knack.arguments import CLIArgumentType +from knack.log import get_logger +from knack.util import CLIError +from azure.cli.command_modules.monitor._legacy.util import get_autoscale_scale_direction_map + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.aaz._arg import AAZCompoundTypeArg, AAZListType +from azure.cli.core.aaz._arg_fmt import AAZListArgFormat +from azure.cli.core.aaz._base import AAZUndefined, AAZBlankArgValue +from azure.cli.core.aaz._arg_action import AAZCompoundTypeArgAction, AAZArgActionOperations, \ + _ELEMENT_APPEND_KEY, AAZSimpleTypeArgAction +from azure.cli.core.aaz._help import AAZShowHelp +from azure.cli.core.aaz.exceptions import AAZInvalidValueError +from azure.cli.core.aaz._prompt import AAZPromptInput + +logger = get_logger(__name__) + + +def timezone_name_type(value): + from azure.cli.command_modules.monitor._legacy._autoscale_util import AUTOSCALE_TIMEZONES + zone = next((x['name'] for x in AUTOSCALE_TIMEZONES if x['name'].lower() == value.lower()), None) + if not zone: + raise InvalidArgumentValueError( + "Invalid time zone: '{}'. Run 'az monitor autoscale profile list-timezones' for values.".format(value)) + return zone + + +def timezone_offset_type(value): + + try: + hour, minute = str(value).split(':') + except ValueError: + hour = str(value) + minute = None + + hour = int(hour) + + if hour > 14 or hour < -12: + raise InvalidArgumentValueError('Offset out of range: -12 to +14') + + if 0 <= hour < 10: + value = '+0{}'.format(hour) + elif hour >= 10: + value = '+{}'.format(hour) + elif -10 < hour < 0: + value = '-0{}'.format(-1 * hour) + else: + value = str(hour) + if minute: + value = '{}:{}'.format(value, minute) + return value + + +def get_period_type(as_timedelta=False): + + def period_type(value): + + import re + + def _get_substring(indices): + if indices == tuple([-1, -1]): + return '' + return value[indices[0]: indices[1]] + + regex = r'(p)?(\d+y)?(\d+m)?(\d+d)?(t)?(\d+h)?(\d+m)?(\d+s)?' + match = re.match(regex, value.lower()) + match_len = match.span(0) + if match_len != tuple([0, len(value)]): + raise ValueError('PERIOD should be of the form "##h##m##s" or ISO8601') + # simply return value if a valid ISO8601 string is supplied + if match.span(1) != tuple([-1, -1]) and match.span(5) != tuple([-1, -1]): + return value + + # if shorthand is used, only support days, minutes, hours, seconds + # ensure M is interpretted as minutes + days = _get_substring(match.span(4)) + hours = _get_substring(match.span(6)) + minutes = _get_substring(match.span(7)) or _get_substring(match.span(3)) + seconds = _get_substring(match.span(8)) + + if as_timedelta: + from datetime import timedelta + return timedelta( + days=int(days[:-1]) if days else 0, + hours=int(hours[:-1]) if hours else 0, + minutes=int(minutes[:-1]) if minutes else 0, + seconds=int(seconds[:-1]) if seconds else 0 + ) + return 'P{}T{}{}{}'.format(days, minutes, hours, seconds).upper() + + return period_type + + +# pylint: disable=redefined-builtin +def get_date_midnight_type(help=None): + + help_string = help + ' ' if help else '' + accepted_formats = ['date (yyyy-mm-dd)', 'time (hh:mm:ss.xxxxx)', 'timezone (+/-hh:mm)'] + help_string = help_string + 'Format: ' + ' '.join(accepted_formats) + + # pylint: disable=too-few-public-methods + class DateAction(argparse.Action): + + def __call__(self, parser, namespace, values, option_string=None): + """ Parse a date value and return the ISO8601 string. """ + import dateutil.parser + import dateutil.tz + + value_string = ' '.join(values) + dt_val = None + try: + # attempt to parse ISO 8601 + dt_val = dateutil.parser.parse(value_string) + except ValueError: + pass + + # TODO: custom parsing attempts here + if not dt_val: + raise CLIError("Unable to parse: '{}'. Expected format: {}".format(value_string, help_string)) + if dt_val.tzinfo: + logger.warning('Timezone info will be ignored in %s.', value_string) + dt_val = dt_val.replace(tzinfo=dateutil.tz.tzutc()) + + # Issue warning if any supplied time will be ignored + if any([dt_val.hour, dt_val.minute, dt_val.second, dt_val.microsecond]): + logger.warning('Time info will be set to midnight UTC for %s.', value_string) + date_midnight = dt_val.replace(hour=0, minute=0, second=0, microsecond=0) + format_string = date_midnight.isoformat() + logger.info('Time info set to midnight UTC from %s to %s', value_string, format_string) + setattr(namespace, self.dest, format_string) + + return CLIArgumentType(action=DateAction, nargs='+', help=help_string) + + +# pylint: disable=protected-access, too-few-public-methods +class MetricAlertConditionAction(argparse._AppendAction): + + def __call__(self, parser, namespace, values, option_string=None): + # antlr4 is not available everywhere, restrict the import scope so that commands + # that do not need it don't fail when it is absent + import antlr4 + + from azure.cli.command_modules.monitor._legacy.grammar.metric_alert import ( + MetricAlertConditionLexer, MetricAlertConditionParser, MetricAlertConditionValidator) + + usage = 'usage error: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n' \ + ' [{=,!=,>,>=,<,<=} THRESHOLD]\n' \ + ' [{<,>,><} dynamic SENSITIVITY VIOLATION of EVALUATION [since DATETIME]]\n' \ + ' [where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n' \ + ' [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n' \ + ' [with skipmetricvalidation]' + + string_val = ' '.join(values) + + lexer = MetricAlertConditionLexer(antlr4.InputStream(string_val)) + stream = antlr4.CommonTokenStream(lexer) + parser = MetricAlertConditionParser(stream) + tree = parser.expression() + + try: + validator = MetricAlertConditionValidator() + walker = antlr4.ParseTreeWalker() + walker.walk(validator, tree) + metric_condition = validator.result() + if "static" in metric_condition: + # static metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'threshold']: + if item not in metric_condition["static"]: + raise InvalidArgumentValueError(usage) + elif "dynamic" in metric_condition: + # dynamic metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'alert_sensitivity', 'failing_periods']: + if item not in metric_condition["dynamic"]: + raise InvalidArgumentValueError(usage) + else: + raise NotImplementedError() + except (AttributeError, TypeError, KeyError): + raise InvalidArgumentValueError(usage) + super().__call__(parser, namespace, metric_condition, option_string) + + +# pylint: disable=protected-access, too-few-public-methods +class MetricAlertAddAction(argparse._AppendAction): + + def __call__(self, parser, namespace, values, option_string=None): + action_group_id = values[0] + try: + webhook_property_candidates = dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None + except ValueError: + err_msg = "value of {} is invalid. Please refer to --help to get insight of correct format".format( + option_string + ) + raise InvalidArgumentValueError(err_msg) + + action = { + "action_group_id": action_group_id, + "web_hook_properties": webhook_property_candidates + } + action["odatatype"] = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights." \ + "Nexus.DataContracts.Resources.ScheduledQueryRules.Action" + super().__call__(parser, namespace, action, option_string) + + +class AlertRemoveAction(argparse._AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + action = self.get_action(values, option_string) + super().__call__(parser, namespace, action, option_string) + + def get_action(self, values, option_string): # pylint: disable=no-self-use + # TYPE is artificially enforced to create consistency with the --add-action argument + # but it could be enhanced to do additional validation in the future. + _type = values[0].lower() + if _type not in ['email', 'webhook']: + raise InvalidArgumentValueError('{} TYPE KEY [KEY ...]'.format(option_string)) + return values[1:] + + +# pylint: disable=protected-access +class AutoscaleCreateAction(argparse._AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + action = self.get_action(values, option_string) + super().__call__(parser, namespace, action, option_string) + + def get_action(self, values, option_string): # pylint: disable=no-self-use + _type = values[0].lower() + if _type == 'email': + return { + "key": "email", + "value": { + "custom_emails": values[1:] + } + } + if _type == 'webhook': + uri = values[1] + try: + properties = dict(x.split('=', 1) for x in values[2:]) + except ValueError: + raise InvalidArgumentValueError('{} webhook URI [KEY=VALUE ...]'.format(option_string)) + return { + "key": "webhook", + "value": { + "service_uri": uri, + "properties": properties + } + } + raise InvalidArgumentValueError('{} TYPE KEY [ARGS]'.format(option_string)) + + +# pylint: disable=protected-access +class AutoscaleAddAction(argparse._AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + action = self.get_action(values, option_string) + super().__call__(parser, namespace, action, option_string) + + def get_action(self, values, option_string): # pylint: disable=no-self-use + _type = values[0].lower() + if _type == 'email': + from azure.mgmt.monitor.models import EmailNotification + return EmailNotification(custom_emails=values[1:]) + if _type == 'webhook': + from azure.mgmt.monitor.models import WebhookNotification + uri = values[1] + try: + properties = dict(x.split('=', 1) for x in values[2:]) + except ValueError: + raise InvalidArgumentValueError('{} webhook URI [KEY=VALUE ...]'.format(option_string)) + return WebhookNotification(service_uri=uri, properties=properties) + raise InvalidArgumentValueError('{} TYPE KEY [ARGS]'.format(option_string)) + + +class AutoscaleRemoveAction(argparse._AppendAction): + def __call__(self, parser, namespace, values, option_string=None): + action = self.get_action(values, option_string) + super().__call__(parser, namespace, action, option_string) + + def get_action(self, values, option_string): # pylint: disable=no-self-use + # TYPE is artificially enforced to create consistency with the --add-action argument + # but it could be enhanced to do additional validation in the future. + _type = values[0].lower() + if _type not in ['email', 'webhook']: + raise InvalidArgumentValueError('{} TYPE KEY [KEY ...]'.format(option_string)) + return values[1:] + + +class AutoscaleConditionAction(argparse.Action): # pylint: disable=protected-access + def __call__(self, parser, namespace, values, option_string=None): + # antlr4 is not available everywhere, restrict the import scope so that commands + # that do not need it don't fail when it is absent + import antlr4 + + from azure.cli.command_modules.monitor._legacy.grammar.autoscale import ( + AutoscaleConditionLexer, AutoscaleConditionParser, AutoscaleConditionValidator) + + # pylint: disable=line-too-long + usage = '--condition ["NAMESPACE"] METRIC {==,!=,>,>=,<,<=} THRESHOLD {avg,min,max,total,count} PERIOD\n' \ + ' [where DIMENSION {==,!=} VALUE [or VALUE ...]\n' \ + ' [and DIMENSION {==,!=} VALUE [or VALUE ...] ...]]' + + string_val = ' '.join(values) + + lexer = AutoscaleConditionLexer(antlr4.InputStream(string_val)) + stream = antlr4.CommonTokenStream(lexer) + parser = AutoscaleConditionParser(stream) + tree = parser.expression() + + try: + validator = AutoscaleConditionValidator() + walker = antlr4.ParseTreeWalker() + walker.walk(validator, tree) + autoscale_condition = validator.result() + for item in ['time_aggregation', 'metric_name', 'threshold', 'operator', 'time_window']: + if not getattr(autoscale_condition, item, None): + raise InvalidArgumentValueError(usage) + except (AttributeError, TypeError, KeyError): + raise InvalidArgumentValueError(usage) + + namespace.condition = autoscale_condition + + +class AutoscaleScaleAction(argparse.Action): # pylint: disable=protected-access + def __call__(self, parser, namespace, values, option_string=None): + from azure.mgmt.monitor.models import ScaleAction, ScaleType + if len(values) == 1: + # workaround because CMD.exe eats > character... Allows condition to be + # specified as a quoted expression + values = values[0].split(' ') + if len(values) != 2: + raise InvalidArgumentValueError('--scale {in,out,to} VALUE[%]') + dir_val = values[0] + amt_val = values[1] + scale_type = None + if dir_val == 'to': + scale_type = ScaleType.exact_count.value + elif str(amt_val).endswith('%'): + scale_type = ScaleType.percent_change_count.value + amt_val = amt_val[:-1] # strip off the percent + else: + scale_type = ScaleType.change_count.value + + scale = ScaleAction( + direction=get_autoscale_scale_direction_map()[dir_val], + type=scale_type, + cooldown=None, # this will be filled in later + value=amt_val + ) + namespace.scale = scale + + +class MultiObjectsDeserializeAction(argparse._AppendAction): # pylint: disable=protected-access + def __call__(self, parser, namespace, values, option_string=None): + type_name = values[0] + type_properties = values[1:] + + try: + super().__call__(parser, + namespace, + self.deserialize_object(type_name, type_properties), + option_string) + except KeyError: + raise InvalidArgumentValueError('the type "{}" is not recognizable.'.format(type_name)) + except TypeError: + raise InvalidArgumentValueError( + 'Failed to parse "{}" as object of type "{}".'.format(' '.join(values), type_name)) + except ValueError as ex: + raise InvalidArgumentValueError( + 'Failed to parse "{}" as object of type "{}". {}'.format( + ' '.join(values), type_name, str(ex))) + + def deserialize_object(self, type_name, type_properties): + raise NotImplementedError() + + +class ActionGroupReceiverParameterAction(MultiObjectsDeserializeAction): + def deserialize_object(self, type_name, type_properties): + from azure.mgmt.monitor.models import EmailReceiver, SmsReceiver, WebhookReceiver, \ + ArmRoleReceiver, AzureAppPushReceiver, ItsmReceiver, AutomationRunbookReceiver, \ + VoiceReceiver, LogicAppReceiver, AzureFunctionReceiver, EventHubReceiver + syntax = { + 'email': 'NAME EMAIL_ADDRESS [usecommonalertschema]', + 'sms': 'NAME COUNTRY_CODE PHONE_NUMBER', + 'webhook': 'NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]', + 'armrole': 'NAME ROLE_ID [usecommonalertschema]', + 'azureapppush': 'NAME EMAIL_ADDRESS', + 'itsm': 'NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIG REGION', + 'automationrunbook': 'NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID ' + 'SERVICE_URI [isglobalrunbook] [usecommonalertschema]', + 'voice': 'NAME COUNTRY_CODE PHONE_NUMBER', + 'logicapp': 'NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]', + 'azurefunction': 'NAME FUNCTION_APP_RESOURCE_ID ' + 'FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]', + 'eventhub': 'NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema] ' + } + + receiver = None + useCommonAlertSchema = 'usecommonalertschema' in (property.lower() for property in type_properties) + try: + if type_name == 'email': + receiver = EmailReceiver(name=type_properties[0], email_address=type_properties[1], + use_common_alert_schema=useCommonAlertSchema) + elif type_name == 'sms': + receiver = SmsReceiver( + name=type_properties[0], + country_code=type_properties[1], + phone_number=type_properties[2] + ) + elif type_name == 'webhook': + useAadAuth = len(type_properties) >= 3 and type_properties[2] == 'useaadauth' + object_id = type_properties[3] if useAadAuth else None + identifier_uri = type_properties[4] if useAadAuth else None + receiver = WebhookReceiver(name=type_properties[0], service_uri=type_properties[1], + use_common_alert_schema=useCommonAlertSchema, + use_aad_auth=useAadAuth, object_id=object_id, + identifier_uri=identifier_uri) + elif type_name == 'armrole': + receiver = ArmRoleReceiver(name=type_properties[0], role_id=type_properties[1], + use_common_alert_schema=useCommonAlertSchema) + elif type_name == 'azureapppush': + receiver = AzureAppPushReceiver(name=type_properties[0], email_address=type_properties[1]) + elif type_name == 'itsm': + receiver = ItsmReceiver(name=type_properties[0], workspace_id=type_properties[1], + connection_id=type_properties[2], ticket_configuration=type_properties[3], + region=type_properties[4]) + elif type_name == 'automationrunbook': + isGlobalRunbook = 'isglobalrunbook' in (property.lower() for property in type_properties) + receiver = AutomationRunbookReceiver(name=type_properties[0], automation_account_id=type_properties[1], + runbook_name=type_properties[2], + webhook_resource_id=type_properties[3], + service_uri=type_properties[4], + is_global_runbook=isGlobalRunbook, + use_common_alert_schema=useCommonAlertSchema) + elif type_name == 'voice': + receiver = VoiceReceiver( + name=type_properties[0], + country_code=type_properties[1], + phone_number=type_properties[2] + ) + elif type_name == 'logicapp': + receiver = LogicAppReceiver(name=type_properties[0], resource_id=type_properties[1], + callback_url=type_properties[2], + use_common_alert_schema=useCommonAlertSchema) + elif type_name == 'azurefunction': + receiver = AzureFunctionReceiver(name=type_properties[0], function_app_resource_id=type_properties[1], + function_name=type_properties[2], + http_trigger_url=type_properties[3], + use_common_alert_schema=useCommonAlertSchema) + elif type_name == 'eventhub': + receiver = EventHubReceiver(name=type_properties[0], subscription_id=type_properties[1], + event_hub_name_space=type_properties[2], event_hub_name=type_properties[3], + use_common_alert_schema=useCommonAlertSchema) + else: + raise InvalidArgumentValueError('The type "{}" is not recognizable.'.format(type_name)) + + except IndexError: + raise InvalidArgumentValueError('--action {}'.format(syntax[type_name])) + return receiver + + +class AAZCustomListArgAction(AAZCompoundTypeArgAction): + + def __call__(self, parser, namespace, values, option_string=None): + if not isinstance(getattr(namespace, self.dest), AAZArgActionOperations): + # overwrite existing namespace value which is not an instance of AAZArgActionOperations. + # especially the default value of argument. + setattr(namespace, self.dest, AAZArgActionOperations()) + dest_ops = getattr(namespace, self.dest) + try: + if self._schema.singular_options and option_string in self._schema.singular_options: + # if singular option is used then parsed values by element action + action = self._schema.Element._build_cmd_action() + action.setup_operations(dest_ops, values, prefix_keys=[_ELEMENT_APPEND_KEY]) + else: + self.setup_operations(dest_ops, values) + except (ValueError, KeyError) as ex: + raise InvalidArgumentValueError(f"Failed to parse '{option_string}' argument: {ex}") from ex + except AAZShowHelp as aaz_help: + aaz_help.keys = (option_string, *aaz_help.keys) + self.show_aaz_help(parser, aaz_help) + + @classmethod + def setup_operations(cls, dest_ops, values, prefix_keys=None): + if prefix_keys is None: + prefix_keys = [] + if values is None or values == []: + if cls._schema._blank == AAZUndefined: + raise AAZInvalidValueError("argument cannot be blank") + assert not isinstance(cls._schema._blank, AAZPromptInput), "Prompt input is not supported in List args." + dest_ops.add(copy.deepcopy(cls._schema._blank), *prefix_keys) + else: + assert isinstance(values, list) + ops = [] + + # This part of logic is to support Separate Elements Expression which is widely used in current command, + # such as: + # --args val1 val2 val3. + # The standard expression of it should be: + # --args [val1,val2,val3] + + element_action = cls._schema.Element._build_cmd_action() + if not issubclass(element_action, AAZSimpleTypeArgAction): + # Separate Elements Expression only supported for simple type element array + raise AAZInvalidValueError("Element action is not nullable") + + # dest_ops + try: + element_ops = AAZArgActionOperations() + for value in values: + element_action.setup_operations(element_ops, value, prefix_keys=[_ELEMENT_APPEND_KEY]) + except AAZShowHelp as aaz_help: + aaz_help.schema = cls._schema + aaz_help.keys = (0, *aaz_help.keys) + raise aaz_help + + elements = [] + for _, data in element_ops._ops: + elements.append(data) + ops = [([], elements)] + + for key_parts, data in ops: + dest_ops.add(data, *prefix_keys, *key_parts) + + @classmethod + def format_data(cls, data): + if data == AAZBlankArgValue: + if cls._schema._blank == AAZUndefined: + raise AAZInvalidValueError("argument value cannot be blank") + assert not isinstance(cls._schema._blank, AAZPromptInput), "Prompt input is not supported in List args." + data = copy.deepcopy(cls._schema._blank) + + if data is None: + if cls._schema._nullable: + return data + raise AAZInvalidValueError("field is not nullable") + + if isinstance(data, list): + result = [] + action = cls._schema.Element._build_cmd_action() + for idx, value in enumerate(data): + try: + result.append(action.format_data(value)) + except AAZInvalidValueError as ex: + raise AAZInvalidValueError(f"Invalid at [{idx}] : {ex}") from ex + return result + + raise AAZInvalidValueError(f"list type value expected, got '{data}'({type(data)})") + + +class AAZCustomListArg(AAZCompoundTypeArg, AAZListType): + + def __init__(self, fmt=None, singular_options=None, **kwargs): + fmt = fmt or AAZListArgFormat() + super().__init__(fmt=fmt, **kwargs) + self.singular_options = singular_options + + def to_cmd_arg(self, name, **kwargs): + arg = super().to_cmd_arg(name, **kwargs) + if self.singular_options: + assert arg.options_list + arg.options_list.extend(self.singular_options) # support to parse singular options + + if self._blank != AAZUndefined: + arg.nargs = '*' + else: + arg.nargs = '+' + return arg + + def _build_cmd_action(self): + class Action(AAZCustomListArgAction): + _schema = self # bind action class with current schema + + return Action + + @property + def _type_in_help(self): + return f"List<{self.Element._type_in_help}>" diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/commands.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/commands.py new file mode 100644 index 00000000000..c44f53c7567 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/commands.py @@ -0,0 +1,213 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +from azure.cli.core.commands import CliCommandType + + +# pylint: disable=line-too-long, too-many-locals, too-many-statements +def load_command_table(self, _): + from ._client_factory import ( + cf_autoscale, + cf_action_groups, cf_event_categories, + cf_metric_alerts, cf_log_analytics_workspace, cf_log_analytics_linked_storage) + from .transformers import (action_group_list_table) + from .validators import (process_autoscale_create_namespace) + + from ._exception_handler import exception_handler + + monitor_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.custom#{}', + exception_handler=exception_handler) + + action_group_sdk = CliCommandType( + operations_tmpl='azure.mgmt.monitor.operations#ActionGroupsOperations.{}', + client_factory=cf_action_groups, + operation_group='action_groups', + exception_handler=exception_handler) + + action_group_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.action_groups#{}', + client_factory=cf_action_groups, + operation_group='action_groups', + exception_handler=exception_handler) + + activity_log_sdk = CliCommandType( + operations_tmpl='azure.mgmt.monitor.operations#EventCategoriesOperations.{}', + client_factory=cf_event_categories, + operation_group='event_categories', + exception_handler=exception_handler) + + autoscale_sdk = CliCommandType( + operations_tmpl='azure.mgmt.monitor.operations#AutoscaleSettingsOperations.{}', + client_factory=cf_autoscale, + operation_group='autoscale_settings', + exception_handler=exception_handler) + + autoscale_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.autoscale_settings#{}', + client_factory=cf_autoscale, + operation_group='autoscale_settings', + exception_handler=exception_handler) + + alert_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.metric_alert#{}', + exception_handler=exception_handler) + + metric_alert_sdk = CliCommandType( + operations_tmpl='azure.mgmt.monitor.operations#MetricAlertsOperations.{}', + client_factory=cf_metric_alerts, + operation_group='metric_alerts', + exception_handler=exception_handler) + + log_analytics_workspace_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.log_analytics_workspace#{}', + client_factory=cf_log_analytics_workspace, + exception_handler=exception_handler) + + log_analytics_linked_storage_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.log_analytics_linked_storage_account#{}', + client_factory=cf_log_analytics_linked_storage, + exception_handler=exception_handler) + + monitor_general_custom = CliCommandType( + operations_tmpl='azure.cli.command_modules.monitor._legacy.operations.general_operations#{}', + client_factory=cf_metric_alerts, + exception_handler=exception_handler) + + with self.command_group('monitor action-group', action_group_sdk, custom_command_type=action_group_custom) as g: + g.wait_command('wait') + + from .operations.action_groups import ActionGroupCreate, ActionGroupUpdate, ActionGroupTestNotificationCreate + from .aaz.latest.monitor.action_group import Show, List, EnableReceiver + self.command_table['monitor action-group create'] = ActionGroupCreate(loader=self, + table_transformer=action_group_list_table) + self.command_table['monitor action-group show'] = Show(loader=self, + table_transformer=action_group_list_table) + self.command_table['monitor action-group list'] = List(loader=self, + table_transformer=action_group_list_table) + self.command_table['monitor action-group update'] = ActionGroupUpdate(loader=self, + table_transformer=action_group_list_table) + self.command_table['monitor action-group enable-receiver'] = \ + EnableReceiver(loader=self, table_transformer=action_group_list_table) + + self.command_table['monitor action-group test-notifications create'] = \ + ActionGroupTestNotificationCreate(loader=self, table_transformer=action_group_list_table) + + from .operations.action_groups_identity import AGIdentityAssign, AGIdentityRemove, AGIdentityShow + self.command_table['monitor action-group identity assign'] = AGIdentityAssign(loader=self) + self.command_table['monitor action-group identity remove'] = AGIdentityRemove(loader=self) + self.command_table['monitor action-group identity show'] = AGIdentityShow(loader=self) + + with self.command_group('monitor activity-log', activity_log_sdk) as g: + g.custom_command('list', 'list_activity_log') + + from .operations.activity_log_alerts import ActivityLogAlertCreate, ActivityLogAlertUpdate, \ + ActivityLogAlertActionGroupAdd, ActivityLogAlertActionGroupRemove, \ + ActivityLogAlertScopeAdd, ActivityLogAlertScopeRemove + self.command_table['monitor activity-log alert create'] = ActivityLogAlertCreate(loader=self) + self.command_table['monitor activity-log alert update'] = ActivityLogAlertUpdate(loader=self) + self.command_table['monitor activity-log alert action-group add'] = ActivityLogAlertActionGroupAdd(loader=self) + self.command_table['monitor activity-log alert action-group remove'] = \ + ActivityLogAlertActionGroupRemove(loader=self) + self.command_table['monitor activity-log alert scope add'] = ActivityLogAlertScopeAdd(loader=self) + self.command_table['monitor activity-log alert scope remove'] = ActivityLogAlertScopeRemove(loader=self) + + with self.command_group('monitor autoscale', autoscale_sdk, custom_command_type=autoscale_custom) as g: + g.custom_command('create', 'autoscale_create', validator=process_autoscale_create_namespace) + # g.generic_update_command('update', custom_func_name='autoscale_update', custom_func_type=autoscale_custom) + from .operations.autoscale_settings import AutoScaleShow, AutoScaleList, AutoScaleUpdate + self.command_table['monitor autoscale show'] = AutoScaleShow(loader=self) + self.command_table['monitor autoscale list'] = AutoScaleList(loader=self) + self.command_table['monitor autoscale update'] = AutoScaleUpdate(loader=self) + + with self.command_group('monitor autoscale profile', autoscale_sdk, custom_command_type=autoscale_custom) as g: + g.custom_command('create', 'autoscale_profile_create') + g.custom_command('list', 'autoscale_profile_list') + g.custom_show_command('show', 'autoscale_profile_show') + g.custom_command('delete', 'autoscale_profile_delete') + g.custom_command('list-timezones', 'autoscale_profile_list_timezones') + + with self.command_group('monitor autoscale rule', autoscale_sdk, custom_command_type=autoscale_custom) as g: + g.custom_command('create', 'autoscale_rule_create') + g.custom_command('list', 'autoscale_rule_list') + g.custom_command('delete', 'autoscale_rule_delete') + g.custom_command('copy', 'autoscale_rule_copy') + + from .operations.diagnostics_settings import DiagnosticSettingsCreate, DiagnosticSettingsShow, \ + DiagnosticSettingsList, DiagnosticSettingsDelete, DiagnosticSettingsUpdate + self.command_table['monitor diagnostic-settings create'] = DiagnosticSettingsCreate(loader=self) + self.command_table['monitor diagnostic-settings show'] = DiagnosticSettingsShow(loader=self) + self.command_table['monitor diagnostic-settings list'] = DiagnosticSettingsList(loader=self) + self.command_table['monitor diagnostic-settings delete'] = DiagnosticSettingsDelete(loader=self) + self.command_table['monitor diagnostic-settings update'] = DiagnosticSettingsUpdate(loader=self) + + from .operations.diagnostics_settings import DiagnosticSettingsCategoryShow, DiagnosticSettingsCategoryList + self.command_table['monitor diagnostic-settings categories show'] = DiagnosticSettingsCategoryShow(loader=self) + self.command_table['monitor diagnostic-settings categories list'] = DiagnosticSettingsCategoryList(loader=self) + + with self.command_group('monitor metrics') as g: + from .transformers import metrics_table, metrics_definitions_table, metrics_namespaces_table + g.command('list', 'list_metrics', command_type=monitor_custom, table_transformer=metrics_table) + g.custom_command('list-definitions', 'list_definations', command_type=monitor_custom, table_transformer=metrics_definitions_table) + g.command('list-namespaces', 'list_namespaces', is_preview=True, command_type=monitor_custom, table_transformer=metrics_namespaces_table) + + with self.command_group("monitor metrics alert") as g: + from .operations.metric_alert import MetricsAlertUpdate + self.command_table["monitor metrics alert update"] = MetricsAlertUpdate(loader=self) + g.custom_command("create", "create_metric_alert", custom_command_type=alert_custom) + + with self.command_group('monitor metrics alert dimension') as g: + from .validators import validate_metrics_alert_dimension + g.custom_command('create', 'create_metric_alert_dimension', custom_command_type=alert_custom, + validator=validate_metrics_alert_dimension, is_preview=True) + + with self.command_group('monitor metrics alert condition') as g: + from .validators import validate_metrics_alert_condition + g.custom_command('create', 'create_metric_alert_condition', custom_command_type=alert_custom, + validator=validate_metrics_alert_condition, is_preview=True) + + with self.command_group('monitor log-analytics workspace', custom_command_type=log_analytics_workspace_custom) as g: + g.custom_command('recover', 'recover_log_analytics_workspace', supports_no_wait=True) + + with self.command_group('monitor log-analytics workspace table', custom_command_type=log_analytics_workspace_custom) as g: + g.custom_command('create', 'create_log_analytics_workspace_table', supports_no_wait=True) + g.custom_command('update', 'update_log_analytics_workspace_table', supports_no_wait=True) + + with self.command_group('monitor log-analytics workspace table search-job', + custom_command_type=log_analytics_workspace_custom) as g: + g.custom_command('create', 'create_log_analytics_workspace_table_search_job', supports_no_wait=True) + from .operations.log_analytics_workspace import WorkspaceTableSearchJobCancel + self.command_table['monitor log-analytics workspace table search-job cancel'] = \ + WorkspaceTableSearchJobCancel(loader=self) + + with self.command_group('monitor log-analytics workspace table restore', + custom_command_type=log_analytics_workspace_custom) as g: + g.custom_command('create', 'create_log_analytics_workspace_table_restore', supports_no_wait=True) + + from .operations.log_analytics_workspace import WorkspaceDataExportCreate, WorkspaceDataExportUpdate + self.command_table['monitor log-analytics workspace data-export create'] = WorkspaceDataExportCreate(loader=self) + self.command_table['monitor log-analytics workspace data-export update'] = WorkspaceDataExportUpdate(loader=self) + + with self.command_group('monitor log-analytics workspace saved-search', + custom_command_type=log_analytics_workspace_custom) as g: + g.custom_command('create', 'create_log_analytics_workspace_saved_search') + g.custom_command('update', 'update_log_analytics_workspace_saved_search') + + from .operations.log_analytics_linked_storage_account import WorkspaceLinkedStorageAccountCreate + self.command_table['monitor log-analytics workspace linked-storage create'] = WorkspaceLinkedStorageAccountCreate( + loader=self) + with self.command_group('monitor log-analytics workspace linked-storage', + custom_command_type=log_analytics_linked_storage_custom) as g: + g.custom_command('add', 'add_log_analytics_workspace_linked_storage_accounts') + g.custom_command('remove', 'remove_log_analytics_workspace_linked_storage_accounts') + + with self.command_group('monitor', metric_alert_sdk, custom_command_type=monitor_general_custom) as g: + g.custom_command('clone', 'clone_existed_settings', is_preview=True) + + from .operations.private_link_scope import PrivateLinkScopeCreate, ConnectionDelete, ConnectionShow, ConnectionApprove, ConnectionReject + self.command_table["monitor private-link-scope create"] = PrivateLinkScopeCreate(loader=self) + self.command_table["monitor private-link-scope private-endpoint-connection delete"] = ConnectionDelete(loader=self) + self.command_table["monitor private-link-scope private-endpoint-connection show"] = ConnectionShow(loader=self) + self.command_table["monitor private-link-scope private-endpoint-connection approve"] = ConnectionApprove(loader=self) + self.command_table["monitor private-link-scope private-endpoint-connection reject"] = ConnectionReject(loader=self) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/custom.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/custom.py new file mode 100644 index 00000000000..7c37796989c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/custom.py @@ -0,0 +1,156 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from knack.log import get_logger + +logger = get_logger(__name__) + + +# region ActivityLog +def list_activity_log(cmd, correlation_id=None, resource_group=None, resource_id=None, + resource_provider=None, start_time=None, end_time=None, caller=None, status=None, max_events=50, + select=None, offset='6h'): + odata_filters = _build_activity_log_odata_filter(correlation_id, resource_group, resource_id, resource_provider, + start_time, end_time, caller, status, offset) + + select_filters = _activity_log_select_filter_builder(select) + logger.info('OData Filter: %s', odata_filters) + logger.info('Select Filter: %s', select_filters) + + from .aaz.latest.monitor.activity_log import List + # activity_log = client.list(filter=odata_filters, select=select_filters) + activity_log = List(cli_ctx=cmd.cli_ctx)(command_args={ + "filter": odata_filters, + "select": select_filters, + }) + + return _limit_results(activity_log, max_events) + + +def _build_activity_log_odata_filter(correlation_id=None, resource_group=None, resource_id=None, resource_provider=None, + start_time=None, end_time=None, caller=None, status=None, offset=None): + from datetime import datetime + import dateutil.parser + + if not start_time and not end_time: + # if neither value provided, end_time is now + end_time = datetime.utcnow().isoformat() + if not start_time: + # if no start_time, apply offset backwards from end_time + start_time = (dateutil.parser.parse(end_time) - offset).isoformat() + elif not end_time: + # if no end_time, apply offset fowards from start_time + end_time = (dateutil.parser.parse(start_time) + offset).isoformat() + + odata_filters = 'eventTimestamp ge {} and eventTimestamp le {}'.format(start_time, end_time) + + if correlation_id: + odata_filters = _build_odata_filter(odata_filters, 'correlation_id', correlation_id, 'correlationId') + elif resource_group: + odata_filters = _build_odata_filter(odata_filters, 'resource_group', resource_group, 'resourceGroupName') + elif resource_id: + odata_filters = _build_odata_filter(odata_filters, 'resource_id', resource_id, 'resourceId') + elif resource_provider: + odata_filters = _build_odata_filter(odata_filters, 'resource_provider', resource_provider, 'resourceProvider') + if caller: + odata_filters = _build_odata_filter(odata_filters, 'caller', caller, 'caller') + if status: + odata_filters = _build_odata_filter(odata_filters, 'status', status, 'status') + + return odata_filters + + +def _activity_log_select_filter_builder(events=None): + """Build up select filter string from events""" + if events: + return ' , '.join(events) + return None + + +def _build_odata_filter(default_filter, field_name, field_value, field_label): + if not field_value: + from knack.util import CLIError + raise CLIError('Value for {} can not be empty.'.format(field_name)) + + return _add_condition(default_filter, field_label, field_value) + + +def _add_condition(default_filter, field_label, field_value): + if not field_value: + return default_filter + + return "{} and {} eq '{}'".format(default_filter, field_label, field_value) + + +def _single(collection): + return len([x for x in collection if x]) == 1 + + +def _limit_results(paged, limit): + results = [] + for index, item in enumerate(paged): + if index < limit: + results.append(item) + else: + break + return list(results) +# endregion + + +# region Metrics +# pylint:disable=unused-argument +def list_metrics(cmd, resource, + start_time=None, end_time=None, offset='1h', interval='1m', + metadata=None, dimension=None, aggregation=None, metrics=None, + filters=None, metric_namespace=None, orderby=None, top=10): + + from datetime import datetime + import dateutil.parser + from urllib.parse import quote_plus + + if not start_time and not end_time: + # if neither value provided, end_time is now + end_time = datetime.utcnow().isoformat() + if not start_time: + # if no start_time, apply offset backwards from end_time + start_time = (dateutil.parser.parse(end_time) - offset).isoformat() + elif not end_time: + # if no end_time, apply offset fowards from start_time + end_time = (dateutil.parser.parse(start_time) + offset).isoformat() + + timespan = '{}/{}'.format(start_time, end_time) + + from .aaz.latest.monitor.metrics import List + return List(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_uri": resource, + "timespan": quote_plus(timespan), + "interval": interval, + "metricnames": ','.join(metrics) if metrics else None, + "aggregation": ','.join(aggregation) if aggregation else None, + "top": top, + "orderby": orderby, + "filter": filters, + "result_typ": "Metadata" if metadata else None, + "metricnamespac": metric_namespace + }) + + +def list_definations(cmd, resource_uri, metricnamespace=None): + from .aaz.latest.monitor.metrics import ListDefinitions + return ListDefinitions(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_uri": resource_uri, + "metricnamespace": metricnamespace + }) + + +def list_namespaces(cmd, resource_uri, start_time=None): + from .aaz.latest.monitor.metrics import ListNamespaces + return ListNamespaces(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_uri": resource_uri, + "start_time": start_time + }) +# endregion diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleCondition.g4 b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleCondition.g4 new file mode 100644 index 00000000000..549fc815f2e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleCondition.g4 @@ -0,0 +1,74 @@ +/* PARSER RULES */ + +grammar AutoscaleCondition ; + +/* Main Rules */ + +expression : (QUOTE namespace QUOTE WHITESPACE)* (metric WHITESPACE) operator threshold aggregation period (WHITESPACE dimensions)* NEWLINE* ; + +aggregation : WORD WHITESPACE ; + +namespace : (WORD | WHITESPACE | '/' | '.' | '*' | '-' | '_' | ':' | '%' | '#' | '@')+; + +metric : (WORD | WHITESPACE | '.' | '/' | '_' | '\\' | ':' | '%' | '-' | ',' | '|')+; + +operator : OPERATOR WHITESPACE ; + +threshold : NUMBER WHITESPACE ; + +period : WORD ; + +/* Dimensions */ + +where : WHERE WHITESPACE ; + +dimensions : where dimension (dim_separator dimension)* ; + +dimension : dim_name dim_operator dim_values ; + +dim_separator : (AND | ',') WHITESPACE ; + +dim_operator : ('==' | '!=') WHITESPACE ; + +dim_val_separator : (OR | ',') WHITESPACE ; + +dim_name : WORD WHITESPACE ; + +dim_values : dim_value (dim_val_separator dim_value)* ; + +dim_value : (NUMBER | WORD | '-' | '.' | '*' | WHITESPACE | ':'| '~')+ ; + +/* LEXER RULES */ + +fragment A : ('a'|'A') ; +fragment C : ('c'|'C') ; +fragment D : ('d'|'D') ; +fragment E : ('e'|'E') ; +fragment H : ('h'|'H') ; +fragment I : ('i'|'I') ; +fragment L : ('l'|'L') ; +fragment N : ('n'|'N') ; +fragment O : ('o'|'O') ; +fragment R : ('r'|'R') ; +fragment S : ('s'|'S') ; +fragment U : ('u'|'U') ; +fragment W : ('w'|'W') ; +fragment X : ('x'|'X') ; + +fragment DIGIT : [0-9] ; +fragment LOWERCASE : [a-z] ; +fragment UPPERCASE : [A-Z] ; + +WHERE : W H E R E ; +AND : A N D ; +INCLUDES : I N C L U D E S ; +EXCLUDES : E X C L U D E S ; +OR : O R ; + +OPERATOR : ('<' | '<=' | '==' | '>=' | '>' | '!=') ; +NUMBER : DIGIT+ ([.,] DIGIT+)? ; +QUOTE : ('\'' | '"') ; +WHITESPACE : (' ' | '\t')+ ; +NEWLINE : ('\r'? '\n' | '\r')+ ; +WORD : (LOWERCASE | UPPERCASE | DIGIT | '_')+ ; + diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionLexer.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionLexer.py new file mode 100644 index 00000000000..10448602a5c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionLexer.py @@ -0,0 +1,163 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from AutoscaleCondition.g4 by ANTLR 4.13.1 +# encoding: utf-8 +# pylint: disable=all +from antlr4 import * +from io import StringIO +import sys +from typing import TextIO + + +def serializedATN(): + return [ + 4,0,26,233,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5, + 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2, + 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7, + 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2, + 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7, + 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2, + 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,1,0,1,0,1,1,1,1,1,2,1,2,1, + 3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,1,10,1,10, + 1,11,1,11,1,12,1,12,1,12,1,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16, + 1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22, + 1,23,1,23,1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,28,1,28,1,29, + 1,29,1,30,1,30,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,33,1,33, + 1,33,1,33,1,34,1,34,1,34,1,34,1,34,1,34,1,34,1,34,1,34,1,35,1,35, + 1,35,1,35,1,35,1,35,1,35,1,35,1,35,1,36,1,36,1,36,1,37,1,37,1,37, + 1,37,1,37,1,37,1,37,1,37,1,37,1,37,3,37,195,8,37,1,38,4,38,198,8, + 38,11,38,12,38,199,1,38,1,38,4,38,204,8,38,11,38,12,38,205,3,38, + 208,8,38,1,39,1,39,1,40,4,40,213,8,40,11,40,12,40,214,1,41,3,41, + 218,8,41,1,41,1,41,4,41,222,8,41,11,41,12,41,223,1,42,1,42,1,42, + 1,42,4,42,230,8,42,11,42,12,42,231,0,0,43,1,1,3,2,5,3,7,4,9,5,11, + 6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,0,33,0,35, + 0,37,0,39,0,41,0,43,0,45,0,47,0,49,0,51,0,53,0,55,0,57,0,59,0,61, + 0,63,0,65,16,67,17,69,18,71,19,73,20,75,21,77,22,79,23,81,24,83, + 25,85,26,1,0,20,2,0,65,65,97,97,2,0,67,67,99,99,2,0,68,68,100,100, + 2,0,69,69,101,101,2,0,72,72,104,104,2,0,73,73,105,105,2,0,76,76, + 108,108,2,0,78,78,110,110,2,0,79,79,111,111,2,0,82,82,114,114,2, + 0,83,83,115,115,2,0,85,85,117,117,2,0,87,87,119,119,2,0,88,88,120, + 120,1,0,48,57,1,0,97,122,1,0,65,90,2,0,44,44,46,46,2,0,34,34,39, + 39,2,0,9,9,32,32,231,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0, + 0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0, + 0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,1,0, + 0,0,0,29,1,0,0,0,0,65,1,0,0,0,0,67,1,0,0,0,0,69,1,0,0,0,0,71,1,0, + 0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,1,0,0,0,0,79,1,0,0,0,0,81,1,0, + 0,0,0,83,1,0,0,0,0,85,1,0,0,0,1,87,1,0,0,0,3,89,1,0,0,0,5,91,1,0, + 0,0,7,93,1,0,0,0,9,95,1,0,0,0,11,97,1,0,0,0,13,99,1,0,0,0,15,101, + 1,0,0,0,17,103,1,0,0,0,19,105,1,0,0,0,21,107,1,0,0,0,23,109,1,0, + 0,0,25,111,1,0,0,0,27,114,1,0,0,0,29,117,1,0,0,0,31,119,1,0,0,0, + 33,121,1,0,0,0,35,123,1,0,0,0,37,125,1,0,0,0,39,127,1,0,0,0,41,129, + 1,0,0,0,43,131,1,0,0,0,45,133,1,0,0,0,47,135,1,0,0,0,49,137,1,0, + 0,0,51,139,1,0,0,0,53,141,1,0,0,0,55,143,1,0,0,0,57,145,1,0,0,0, + 59,147,1,0,0,0,61,149,1,0,0,0,63,151,1,0,0,0,65,153,1,0,0,0,67,159, + 1,0,0,0,69,163,1,0,0,0,71,172,1,0,0,0,73,181,1,0,0,0,75,194,1,0, + 0,0,77,197,1,0,0,0,79,209,1,0,0,0,81,212,1,0,0,0,83,221,1,0,0,0, + 85,229,1,0,0,0,87,88,5,47,0,0,88,2,1,0,0,0,89,90,5,46,0,0,90,4,1, + 0,0,0,91,92,5,42,0,0,92,6,1,0,0,0,93,94,5,45,0,0,94,8,1,0,0,0,95, + 96,5,95,0,0,96,10,1,0,0,0,97,98,5,58,0,0,98,12,1,0,0,0,99,100,5, + 37,0,0,100,14,1,0,0,0,101,102,5,35,0,0,102,16,1,0,0,0,103,104,5, + 64,0,0,104,18,1,0,0,0,105,106,5,92,0,0,106,20,1,0,0,0,107,108,5, + 44,0,0,108,22,1,0,0,0,109,110,5,124,0,0,110,24,1,0,0,0,111,112,5, + 61,0,0,112,113,5,61,0,0,113,26,1,0,0,0,114,115,5,33,0,0,115,116, + 5,61,0,0,116,28,1,0,0,0,117,118,5,126,0,0,118,30,1,0,0,0,119,120, + 7,0,0,0,120,32,1,0,0,0,121,122,7,1,0,0,122,34,1,0,0,0,123,124,7, + 2,0,0,124,36,1,0,0,0,125,126,7,3,0,0,126,38,1,0,0,0,127,128,7,4, + 0,0,128,40,1,0,0,0,129,130,7,5,0,0,130,42,1,0,0,0,131,132,7,6,0, + 0,132,44,1,0,0,0,133,134,7,7,0,0,134,46,1,0,0,0,135,136,7,8,0,0, + 136,48,1,0,0,0,137,138,7,9,0,0,138,50,1,0,0,0,139,140,7,10,0,0,140, + 52,1,0,0,0,141,142,7,11,0,0,142,54,1,0,0,0,143,144,7,12,0,0,144, + 56,1,0,0,0,145,146,7,13,0,0,146,58,1,0,0,0,147,148,7,14,0,0,148, + 60,1,0,0,0,149,150,7,15,0,0,150,62,1,0,0,0,151,152,7,16,0,0,152, + 64,1,0,0,0,153,154,3,55,27,0,154,155,3,39,19,0,155,156,3,37,18,0, + 156,157,3,49,24,0,157,158,3,37,18,0,158,66,1,0,0,0,159,160,3,31, + 15,0,160,161,3,45,22,0,161,162,3,35,17,0,162,68,1,0,0,0,163,164, + 3,41,20,0,164,165,3,45,22,0,165,166,3,33,16,0,166,167,3,43,21,0, + 167,168,3,53,26,0,168,169,3,35,17,0,169,170,3,37,18,0,170,171,3, + 51,25,0,171,70,1,0,0,0,172,173,3,37,18,0,173,174,3,57,28,0,174,175, + 3,33,16,0,175,176,3,43,21,0,176,177,3,53,26,0,177,178,3,35,17,0, + 178,179,3,37,18,0,179,180,3,51,25,0,180,72,1,0,0,0,181,182,3,47, + 23,0,182,183,3,49,24,0,183,74,1,0,0,0,184,195,5,60,0,0,185,186,5, + 60,0,0,186,195,5,61,0,0,187,188,5,61,0,0,188,195,5,61,0,0,189,190, + 5,62,0,0,190,195,5,61,0,0,191,195,5,62,0,0,192,193,5,33,0,0,193, + 195,5,61,0,0,194,184,1,0,0,0,194,185,1,0,0,0,194,187,1,0,0,0,194, + 189,1,0,0,0,194,191,1,0,0,0,194,192,1,0,0,0,195,76,1,0,0,0,196,198, + 3,59,29,0,197,196,1,0,0,0,198,199,1,0,0,0,199,197,1,0,0,0,199,200, + 1,0,0,0,200,207,1,0,0,0,201,203,7,17,0,0,202,204,3,59,29,0,203,202, + 1,0,0,0,204,205,1,0,0,0,205,203,1,0,0,0,205,206,1,0,0,0,206,208, + 1,0,0,0,207,201,1,0,0,0,207,208,1,0,0,0,208,78,1,0,0,0,209,210,7, + 18,0,0,210,80,1,0,0,0,211,213,7,19,0,0,212,211,1,0,0,0,213,214,1, + 0,0,0,214,212,1,0,0,0,214,215,1,0,0,0,215,82,1,0,0,0,216,218,5,13, + 0,0,217,216,1,0,0,0,217,218,1,0,0,0,218,219,1,0,0,0,219,222,5,10, + 0,0,220,222,5,13,0,0,221,217,1,0,0,0,221,220,1,0,0,0,222,223,1,0, + 0,0,223,221,1,0,0,0,223,224,1,0,0,0,224,84,1,0,0,0,225,230,3,61, + 30,0,226,230,3,63,31,0,227,230,3,59,29,0,228,230,5,95,0,0,229,225, + 1,0,0,0,229,226,1,0,0,0,229,227,1,0,0,0,229,228,1,0,0,0,230,231, + 1,0,0,0,231,229,1,0,0,0,231,232,1,0,0,0,232,86,1,0,0,0,11,0,194, + 199,205,207,214,217,221,223,229,231,0 + ] + +class AutoscaleConditionLexer(Lexer): + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + T__0 = 1 + T__1 = 2 + T__2 = 3 + T__3 = 4 + T__4 = 5 + T__5 = 6 + T__6 = 7 + T__7 = 8 + T__8 = 9 + T__9 = 10 + T__10 = 11 + T__11 = 12 + T__12 = 13 + T__13 = 14 + T__14 = 15 + WHERE = 16 + AND = 17 + INCLUDES = 18 + EXCLUDES = 19 + OR = 20 + OPERATOR = 21 + NUMBER = 22 + QUOTE = 23 + WHITESPACE = 24 + NEWLINE = 25 + WORD = 26 + + channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ] + + modeNames = [ "DEFAULT_MODE" ] + + literalNames = [ "", + "'/'", "'.'", "'*'", "'-'", "'_'", "':'", "'%'", "'#'", "'@'", + "'\\'", "','", "'|'", "'=='", "'!='", "'~'" ] + + symbolicNames = [ "", + "WHERE", "AND", "INCLUDES", "EXCLUDES", "OR", "OPERATOR", "NUMBER", + "QUOTE", "WHITESPACE", "NEWLINE", "WORD" ] + + ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", + "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13", + "T__14", "A", "C", "D", "E", "H", "I", "L", "N", "O", + "R", "S", "U", "W", "X", "DIGIT", "LOWERCASE", "UPPERCASE", + "WHERE", "AND", "INCLUDES", "EXCLUDES", "OR", "OPERATOR", + "NUMBER", "QUOTE", "WHITESPACE", "NEWLINE", "WORD" ] + + grammarFileName = "AutoscaleCondition.g4" + + def __init__(self, input=None, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.13.1") + self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) + self._actions = None + self._predicates = None + + diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionListener.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionListener.py new file mode 100644 index 00000000000..c06f6fb6c34 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionListener.py @@ -0,0 +1,161 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from AutoscaleCondition.g4 by ANTLR 4.13.1 +# pylint: disable=all +from antlr4 import * +if "." in __name__: + from .AutoscaleConditionParser import AutoscaleConditionParser +else: + from AutoscaleConditionParser import AutoscaleConditionParser + +# This class defines a complete listener for a parse tree produced by AutoscaleConditionParser. +class AutoscaleConditionListener(ParseTreeListener): + + # Enter a parse tree produced by AutoscaleConditionParser#expression. + def enterExpression(self, ctx:AutoscaleConditionParser.ExpressionContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#expression. + def exitExpression(self, ctx:AutoscaleConditionParser.ExpressionContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#aggregation. + def enterAggregation(self, ctx:AutoscaleConditionParser.AggregationContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#aggregation. + def exitAggregation(self, ctx:AutoscaleConditionParser.AggregationContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#namespace. + def enterNamespace(self, ctx:AutoscaleConditionParser.NamespaceContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#namespace. + def exitNamespace(self, ctx:AutoscaleConditionParser.NamespaceContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#metric. + def enterMetric(self, ctx:AutoscaleConditionParser.MetricContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#metric. + def exitMetric(self, ctx:AutoscaleConditionParser.MetricContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#operator. + def enterOperator(self, ctx:AutoscaleConditionParser.OperatorContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#operator. + def exitOperator(self, ctx:AutoscaleConditionParser.OperatorContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#threshold. + def enterThreshold(self, ctx:AutoscaleConditionParser.ThresholdContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#threshold. + def exitThreshold(self, ctx:AutoscaleConditionParser.ThresholdContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#period. + def enterPeriod(self, ctx:AutoscaleConditionParser.PeriodContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#period. + def exitPeriod(self, ctx:AutoscaleConditionParser.PeriodContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#where. + def enterWhere(self, ctx:AutoscaleConditionParser.WhereContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#where. + def exitWhere(self, ctx:AutoscaleConditionParser.WhereContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dimensions. + def enterDimensions(self, ctx:AutoscaleConditionParser.DimensionsContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dimensions. + def exitDimensions(self, ctx:AutoscaleConditionParser.DimensionsContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dimension. + def enterDimension(self, ctx:AutoscaleConditionParser.DimensionContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dimension. + def exitDimension(self, ctx:AutoscaleConditionParser.DimensionContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_separator. + def enterDim_separator(self, ctx:AutoscaleConditionParser.Dim_separatorContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_separator. + def exitDim_separator(self, ctx:AutoscaleConditionParser.Dim_separatorContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_operator. + def enterDim_operator(self, ctx:AutoscaleConditionParser.Dim_operatorContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_operator. + def exitDim_operator(self, ctx:AutoscaleConditionParser.Dim_operatorContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_val_separator. + def enterDim_val_separator(self, ctx:AutoscaleConditionParser.Dim_val_separatorContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_val_separator. + def exitDim_val_separator(self, ctx:AutoscaleConditionParser.Dim_val_separatorContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_name. + def enterDim_name(self, ctx:AutoscaleConditionParser.Dim_nameContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_name. + def exitDim_name(self, ctx:AutoscaleConditionParser.Dim_nameContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_values. + def enterDim_values(self, ctx:AutoscaleConditionParser.Dim_valuesContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_values. + def exitDim_values(self, ctx:AutoscaleConditionParser.Dim_valuesContext): + pass + + + # Enter a parse tree produced by AutoscaleConditionParser#dim_value. + def enterDim_value(self, ctx:AutoscaleConditionParser.Dim_valueContext): + pass + + # Exit a parse tree produced by AutoscaleConditionParser#dim_value. + def exitDim_value(self, ctx:AutoscaleConditionParser.Dim_valueContext): + pass + + + +del AutoscaleConditionParser diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionParser.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionParser.py new file mode 100644 index 00000000000..fd629dbed08 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionParser.py @@ -0,0 +1,1095 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from AutoscaleCondition.g4 by ANTLR 4.13.1 +# encoding: utf-8 +# pylint: disable=all +from antlr4 import * +from io import StringIO +import sys +from typing import TextIO + +def serializedATN(): + return [ + 4,1,26,127,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, + 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13, + 2,14,7,14,2,15,7,15,1,0,1,0,1,0,1,0,1,0,5,0,38,8,0,10,0,12,0,41, + 9,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,5,0,52,8,0,10,0,12,0,55, + 9,0,1,0,5,0,58,8,0,10,0,12,0,61,9,0,1,1,1,1,1,1,1,2,4,2,67,8,2,11, + 2,12,2,68,1,3,4,3,72,8,3,11,3,12,3,73,1,4,1,4,1,4,1,5,1,5,1,5,1, + 6,1,6,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,5,8,92,8,8,10,8,12,8,95,9, + 8,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,11,1,11,1,11,1,12,1,12,1,12,1, + 13,1,13,1,13,1,14,1,14,1,14,1,14,5,14,117,8,14,10,14,12,14,120,9, + 14,1,15,4,15,123,8,15,11,15,12,15,124,1,15,0,0,16,0,2,4,6,8,10,12, + 14,16,18,20,22,24,26,28,30,0,6,3,0,1,9,24,24,26,26,5,0,1,2,4,7,10, + 12,24,24,26,26,2,0,11,11,17,17,1,0,13,14,2,0,11,11,20,20,6,0,2,4, + 6,6,15,15,22,22,24,24,26,26,118,0,39,1,0,0,0,2,62,1,0,0,0,4,66,1, + 0,0,0,6,71,1,0,0,0,8,75,1,0,0,0,10,78,1,0,0,0,12,81,1,0,0,0,14,83, + 1,0,0,0,16,86,1,0,0,0,18,96,1,0,0,0,20,100,1,0,0,0,22,103,1,0,0, + 0,24,106,1,0,0,0,26,109,1,0,0,0,28,112,1,0,0,0,30,122,1,0,0,0,32, + 33,5,23,0,0,33,34,3,4,2,0,34,35,5,23,0,0,35,36,5,24,0,0,36,38,1, + 0,0,0,37,32,1,0,0,0,38,41,1,0,0,0,39,37,1,0,0,0,39,40,1,0,0,0,40, + 42,1,0,0,0,41,39,1,0,0,0,42,43,3,6,3,0,43,44,5,24,0,0,44,45,1,0, + 0,0,45,46,3,8,4,0,46,47,3,10,5,0,47,48,3,2,1,0,48,53,3,12,6,0,49, + 50,5,24,0,0,50,52,3,16,8,0,51,49,1,0,0,0,52,55,1,0,0,0,53,51,1,0, + 0,0,53,54,1,0,0,0,54,59,1,0,0,0,55,53,1,0,0,0,56,58,5,25,0,0,57, + 56,1,0,0,0,58,61,1,0,0,0,59,57,1,0,0,0,59,60,1,0,0,0,60,1,1,0,0, + 0,61,59,1,0,0,0,62,63,5,26,0,0,63,64,5,24,0,0,64,3,1,0,0,0,65,67, + 7,0,0,0,66,65,1,0,0,0,67,68,1,0,0,0,68,66,1,0,0,0,68,69,1,0,0,0, + 69,5,1,0,0,0,70,72,7,1,0,0,71,70,1,0,0,0,72,73,1,0,0,0,73,71,1,0, + 0,0,73,74,1,0,0,0,74,7,1,0,0,0,75,76,5,21,0,0,76,77,5,24,0,0,77, + 9,1,0,0,0,78,79,5,22,0,0,79,80,5,24,0,0,80,11,1,0,0,0,81,82,5,26, + 0,0,82,13,1,0,0,0,83,84,5,16,0,0,84,85,5,24,0,0,85,15,1,0,0,0,86, + 87,3,14,7,0,87,93,3,18,9,0,88,89,3,20,10,0,89,90,3,18,9,0,90,92, + 1,0,0,0,91,88,1,0,0,0,92,95,1,0,0,0,93,91,1,0,0,0,93,94,1,0,0,0, + 94,17,1,0,0,0,95,93,1,0,0,0,96,97,3,26,13,0,97,98,3,22,11,0,98,99, + 3,28,14,0,99,19,1,0,0,0,100,101,7,2,0,0,101,102,5,24,0,0,102,21, + 1,0,0,0,103,104,7,3,0,0,104,105,5,24,0,0,105,23,1,0,0,0,106,107, + 7,4,0,0,107,108,5,24,0,0,108,25,1,0,0,0,109,110,5,26,0,0,110,111, + 5,24,0,0,111,27,1,0,0,0,112,118,3,30,15,0,113,114,3,24,12,0,114, + 115,3,30,15,0,115,117,1,0,0,0,116,113,1,0,0,0,117,120,1,0,0,0,118, + 116,1,0,0,0,118,119,1,0,0,0,119,29,1,0,0,0,120,118,1,0,0,0,121,123, + 7,5,0,0,122,121,1,0,0,0,123,124,1,0,0,0,124,122,1,0,0,0,124,125, + 1,0,0,0,125,31,1,0,0,0,8,39,53,59,68,73,93,118,124 + ] + +class AutoscaleConditionParser ( Parser ): + + grammarFileName = "AutoscaleCondition.g4" + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + sharedContextCache = PredictionContextCache() + + literalNames = [ "", "'/'", "'.'", "'*'", "'-'", "'_'", "':'", + "'%'", "'#'", "'@'", "'\\'", "','", "'|'", "'=='", + "'!='", "'~'" ] + + symbolicNames = [ "", "", "", "", + "", "", "", "", + "", "", "", "", + "", "", "", "", + "WHERE", "AND", "INCLUDES", "EXCLUDES", "OR", "OPERATOR", + "NUMBER", "QUOTE", "WHITESPACE", "NEWLINE", "WORD" ] + + RULE_expression = 0 + RULE_aggregation = 1 + RULE_namespace = 2 + RULE_metric = 3 + RULE_operator = 4 + RULE_threshold = 5 + RULE_period = 6 + RULE_where = 7 + RULE_dimensions = 8 + RULE_dimension = 9 + RULE_dim_separator = 10 + RULE_dim_operator = 11 + RULE_dim_val_separator = 12 + RULE_dim_name = 13 + RULE_dim_values = 14 + RULE_dim_value = 15 + + ruleNames = [ "expression", "aggregation", "namespace", "metric", "operator", + "threshold", "period", "where", "dimensions", "dimension", + "dim_separator", "dim_operator", "dim_val_separator", + "dim_name", "dim_values", "dim_value" ] + + EOF = Token.EOF + T__0=1 + T__1=2 + T__2=3 + T__3=4 + T__4=5 + T__5=6 + T__6=7 + T__7=8 + T__8=9 + T__9=10 + T__10=11 + T__11=12 + T__12=13 + T__13=14 + T__14=15 + WHERE=16 + AND=17 + INCLUDES=18 + EXCLUDES=19 + OR=20 + OPERATOR=21 + NUMBER=22 + QUOTE=23 + WHITESPACE=24 + NEWLINE=25 + WORD=26 + + def __init__(self, input:TokenStream, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.13.1") + self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) + self._predicates = None + + + + + class ExpressionContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def operator(self): + return self.getTypedRuleContext(AutoscaleConditionParser.OperatorContext,0) + + + def threshold(self): + return self.getTypedRuleContext(AutoscaleConditionParser.ThresholdContext,0) + + + def aggregation(self): + return self.getTypedRuleContext(AutoscaleConditionParser.AggregationContext,0) + + + def period(self): + return self.getTypedRuleContext(AutoscaleConditionParser.PeriodContext,0) + + + def metric(self): + return self.getTypedRuleContext(AutoscaleConditionParser.MetricContext,0) + + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WHITESPACE) + else: + return self.getToken(AutoscaleConditionParser.WHITESPACE, i) + + def QUOTE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.QUOTE) + else: + return self.getToken(AutoscaleConditionParser.QUOTE, i) + + def namespace(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.NamespaceContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.NamespaceContext,i) + + + def dimensions(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.DimensionsContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.DimensionsContext,i) + + + def NEWLINE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.NEWLINE) + else: + return self.getToken(AutoscaleConditionParser.NEWLINE, i) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_expression + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterExpression" ): + listener.enterExpression(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitExpression" ): + listener.exitExpression(self) + + + + + def expression(self): + + localctx = AutoscaleConditionParser.ExpressionContext(self, self._ctx, self.state) + self.enterRule(localctx, 0, self.RULE_expression) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 39 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==23: + self.state = 32 + self.match(AutoscaleConditionParser.QUOTE) + self.state = 33 + self.namespace() + self.state = 34 + self.match(AutoscaleConditionParser.QUOTE) + self.state = 35 + self.match(AutoscaleConditionParser.WHITESPACE) + self.state = 41 + self._errHandler.sync(self) + _la = self._input.LA(1) + + self.state = 42 + self.metric() + self.state = 43 + self.match(AutoscaleConditionParser.WHITESPACE) + self.state = 45 + self.operator() + self.state = 46 + self.threshold() + self.state = 47 + self.aggregation() + self.state = 48 + self.period() + self.state = 53 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==24: + self.state = 49 + self.match(AutoscaleConditionParser.WHITESPACE) + self.state = 50 + self.dimensions() + self.state = 55 + self._errHandler.sync(self) + _la = self._input.LA(1) + + self.state = 59 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==25: + self.state = 56 + self.match(AutoscaleConditionParser.NEWLINE) + self.state = 61 + self._errHandler.sync(self) + _la = self._input.LA(1) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class AggregationContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(AutoscaleConditionParser.WORD, 0) + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_aggregation + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterAggregation" ): + listener.enterAggregation(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitAggregation" ): + listener.exitAggregation(self) + + + + + def aggregation(self): + + localctx = AutoscaleConditionParser.AggregationContext(self, self._ctx, self.state) + self.enterRule(localctx, 2, self.RULE_aggregation) + try: + self.enterOuterAlt(localctx, 1) + self.state = 62 + self.match(AutoscaleConditionParser.WORD) + self.state = 63 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class NamespaceContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WORD) + else: + return self.getToken(AutoscaleConditionParser.WORD, i) + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WHITESPACE) + else: + return self.getToken(AutoscaleConditionParser.WHITESPACE, i) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_namespace + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterNamespace" ): + listener.enterNamespace(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitNamespace" ): + listener.exitNamespace(self) + + + + + def namespace(self): + + localctx = AutoscaleConditionParser.NamespaceContext(self, self._ctx, self.state) + self.enterRule(localctx, 4, self.RULE_namespace) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 66 + self._errHandler.sync(self) + _la = self._input.LA(1) + while True: + self.state = 65 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 83887102) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 68 + self._errHandler.sync(self) + _la = self._input.LA(1) + if not (((_la) & ~0x3f) == 0 and ((1 << _la) & 83887102) != 0): + break + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class MetricContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WORD) + else: + return self.getToken(AutoscaleConditionParser.WORD, i) + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WHITESPACE) + else: + return self.getToken(AutoscaleConditionParser.WHITESPACE, i) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_metric + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterMetric" ): + listener.enterMetric(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitMetric" ): + listener.exitMetric(self) + + + + + def metric(self): + + localctx = AutoscaleConditionParser.MetricContext(self, self._ctx, self.state) + self.enterRule(localctx, 6, self.RULE_metric) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 71 + self._errHandler.sync(self) + _alt = 1 + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt == 1: + self.state = 70 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 83893494) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + + else: + raise NoViableAltException(self) + self.state = 73 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,4,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class OperatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def OPERATOR(self): + return self.getToken(AutoscaleConditionParser.OPERATOR, 0) + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_operator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterOperator" ): + listener.enterOperator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitOperator" ): + listener.exitOperator(self) + + + + + def operator(self): + + localctx = AutoscaleConditionParser.OperatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 8, self.RULE_operator) + try: + self.enterOuterAlt(localctx, 1) + self.state = 75 + self.match(AutoscaleConditionParser.OPERATOR) + self.state = 76 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class ThresholdContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self): + return self.getToken(AutoscaleConditionParser.NUMBER, 0) + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_threshold + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterThreshold" ): + listener.enterThreshold(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitThreshold" ): + listener.exitThreshold(self) + + + + + def threshold(self): + + localctx = AutoscaleConditionParser.ThresholdContext(self, self._ctx, self.state) + self.enterRule(localctx, 10, self.RULE_threshold) + try: + self.enterOuterAlt(localctx, 1) + self.state = 78 + self.match(AutoscaleConditionParser.NUMBER) + self.state = 79 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class PeriodContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(AutoscaleConditionParser.WORD, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_period + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterPeriod" ): + listener.enterPeriod(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitPeriod" ): + listener.exitPeriod(self) + + + + + def period(self): + + localctx = AutoscaleConditionParser.PeriodContext(self, self._ctx, self.state) + self.enterRule(localctx, 12, self.RULE_period) + try: + self.enterOuterAlt(localctx, 1) + self.state = 81 + self.match(AutoscaleConditionParser.WORD) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class WhereContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHERE(self): + return self.getToken(AutoscaleConditionParser.WHERE, 0) + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_where + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterWhere" ): + listener.enterWhere(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitWhere" ): + listener.exitWhere(self) + + + + + def where(self): + + localctx = AutoscaleConditionParser.WhereContext(self, self._ctx, self.state) + self.enterRule(localctx, 14, self.RULE_where) + try: + self.enterOuterAlt(localctx, 1) + self.state = 83 + self.match(AutoscaleConditionParser.WHERE) + self.state = 84 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DimensionsContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def where(self): + return self.getTypedRuleContext(AutoscaleConditionParser.WhereContext,0) + + + def dimension(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.DimensionContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.DimensionContext,i) + + + def dim_separator(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.Dim_separatorContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_separatorContext,i) + + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dimensions + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDimensions" ): + listener.enterDimensions(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDimensions" ): + listener.exitDimensions(self) + + + + + def dimensions(self): + + localctx = AutoscaleConditionParser.DimensionsContext(self, self._ctx, self.state) + self.enterRule(localctx, 16, self.RULE_dimensions) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 86 + self.where() + self.state = 87 + self.dimension() + self.state = 93 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==11 or _la==17: + self.state = 88 + self.dim_separator() + self.state = 89 + self.dimension() + self.state = 95 + self._errHandler.sync(self) + _la = self._input.LA(1) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DimensionContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def dim_name(self): + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_nameContext,0) + + + def dim_operator(self): + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_operatorContext,0) + + + def dim_values(self): + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_valuesContext,0) + + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dimension + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDimension" ): + listener.enterDimension(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDimension" ): + listener.exitDimension(self) + + + + + def dimension(self): + + localctx = AutoscaleConditionParser.DimensionContext(self, self._ctx, self.state) + self.enterRule(localctx, 18, self.RULE_dimension) + try: + self.enterOuterAlt(localctx, 1) + self.state = 96 + self.dim_name() + self.state = 97 + self.dim_operator() + self.state = 98 + self.dim_values() + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_separatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def AND(self): + return self.getToken(AutoscaleConditionParser.AND, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_separator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_separator" ): + listener.enterDim_separator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_separator" ): + listener.exitDim_separator(self) + + + + + def dim_separator(self): + + localctx = AutoscaleConditionParser.Dim_separatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 20, self.RULE_dim_separator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 100 + _la = self._input.LA(1) + if not(_la==11 or _la==17): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 101 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_operatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_operator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_operator" ): + listener.enterDim_operator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_operator" ): + listener.exitDim_operator(self) + + + + + def dim_operator(self): + + localctx = AutoscaleConditionParser.Dim_operatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 22, self.RULE_dim_operator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 103 + _la = self._input.LA(1) + if not(_la==13 or _la==14): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 104 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_val_separatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def OR(self): + return self.getToken(AutoscaleConditionParser.OR, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_val_separator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_val_separator" ): + listener.enterDim_val_separator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_val_separator" ): + listener.exitDim_val_separator(self) + + + + + def dim_val_separator(self): + + localctx = AutoscaleConditionParser.Dim_val_separatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 24, self.RULE_dim_val_separator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 106 + _la = self._input.LA(1) + if not(_la==11 or _la==20): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 107 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_nameContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(AutoscaleConditionParser.WORD, 0) + + def WHITESPACE(self): + return self.getToken(AutoscaleConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_name + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_name" ): + listener.enterDim_name(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_name" ): + listener.exitDim_name(self) + + + + + def dim_name(self): + + localctx = AutoscaleConditionParser.Dim_nameContext(self, self._ctx, self.state) + self.enterRule(localctx, 26, self.RULE_dim_name) + try: + self.enterOuterAlt(localctx, 1) + self.state = 109 + self.match(AutoscaleConditionParser.WORD) + self.state = 110 + self.match(AutoscaleConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_valuesContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def dim_value(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.Dim_valueContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_valueContext,i) + + + def dim_val_separator(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(AutoscaleConditionParser.Dim_val_separatorContext) + else: + return self.getTypedRuleContext(AutoscaleConditionParser.Dim_val_separatorContext,i) + + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_values + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_values" ): + listener.enterDim_values(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_values" ): + listener.exitDim_values(self) + + + + + def dim_values(self): + + localctx = AutoscaleConditionParser.Dim_valuesContext(self, self._ctx, self.state) + self.enterRule(localctx, 28, self.RULE_dim_values) + try: + self.enterOuterAlt(localctx, 1) + self.state = 112 + self.dim_value() + self.state = 118 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,6,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + self.state = 113 + self.dim_val_separator() + self.state = 114 + self.dim_value() + self.state = 120 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,6,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_valueContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.NUMBER) + else: + return self.getToken(AutoscaleConditionParser.NUMBER, i) + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WORD) + else: + return self.getToken(AutoscaleConditionParser.WORD, i) + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(AutoscaleConditionParser.WHITESPACE) + else: + return self.getToken(AutoscaleConditionParser.WHITESPACE, i) + + def getRuleIndex(self): + return AutoscaleConditionParser.RULE_dim_value + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_value" ): + listener.enterDim_value(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_value" ): + listener.exitDim_value(self) + + + + + def dim_value(self): + + localctx = AutoscaleConditionParser.Dim_valueContext(self, self._ctx, self.state) + self.enterRule(localctx, 30, self.RULE_dim_value) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 122 + self._errHandler.sync(self) + _alt = 1 + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt == 1: + self.state = 121 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 88113244) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + + else: + raise NoViableAltException(self) + self.state = 124 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,7,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionValidator.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionValidator.py new file mode 100644 index 00000000000..3da186acf8d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/AutoscaleConditionValidator.py @@ -0,0 +1,89 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +from azure.cli.command_modules.monitor._legacy.util import ( + get_autoscale_operator_map, get_autoscale_aggregation_map) +from azure.cli.command_modules.monitor._legacy.actions import get_period_type +from .AutoscaleConditionListener import AutoscaleConditionListener + + + +dim_op_conversion = { + '==': 'Equals', + '!=': 'NotEquals' +} + +# This class defines a complete listener for a parse tree produced by MetricAlertConditionParser. +class AutoscaleConditionValidator(AutoscaleConditionListener): + + def __init__(self): + super().__init__() + self.parameters = {} + self._dimension_index = 0 + + # Exit a parse tree produced by MetricAlertConditionParser#aggregation. + def exitAggregation(self, ctx): + aggregation = get_autoscale_aggregation_map()[ctx.getText().strip()] + self.parameters['time_aggregation'] = aggregation + + # Exit a parse tree produced by MetricAlertConditionParser#namespace. + def exitNamespace(self, ctx): + self.parameters['metric_namespace'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#metric. + def exitMetric(self, ctx): + self.parameters['metric_name'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#metric. + def exitPeriod(self, ctx): + self.parameters['time_window'] = get_period_type()(ctx.getText().strip()) + + # Exit a parse tree produced by MetricAlertConditionParser#operator. + def exitOperator(self, ctx): + operator = get_autoscale_operator_map()[ctx.getText().strip()] + self.parameters['operator'] = operator + + # Exit a parse tree produced by MetricAlertConditionParser#threshold. + def exitThreshold(self, ctx): + self.parameters['threshold'] = ctx.getText().strip() + + # Enter a parse tree produced by MetricAlertConditionParser#dimensions. + def enterDimensions(self, ctx): + self.parameters['dimensions'] = [] + + # Enter a parse tree produced by MetricAlertConditionParser#dimension. + def enterDimension(self, ctx): + self.parameters['dimensions'].append({}) + + # Exit a parse tree produced by MetricAlertConditionParser#dimension. + def exitDimension(self, ctx): + self._dimension_index = self._dimension_index + 1 + + # Exit a parse tree produced by MetricAlertConditionParser#dname. + def exitDim_name(self, ctx): + self.parameters['dimensions'][self._dimension_index]['dimension_name'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#dop. + def exitDim_operator(self, ctx): + op_text = ctx.getText().strip() + self.parameters['dimensions'][self._dimension_index]['operator'] = dim_op_conversion[op_text.lower()] + + # Exit a parse tree produced by MetricAlertConditionParser#dvalues. + def exitDim_values(self, ctx): + dvalues = ctx.getText().strip().split(' ') + self.parameters['dimensions'][self._dimension_index]['values'] = [x for x in dvalues if x not in ['', 'or']] + + def result(self): + from azure.mgmt.monitor.models import MetricTrigger, ScaleRuleMetricDimension + dim_params = self.parameters.get('dimensions', []) + dimensions = [] + for dim in dim_params: + dimensions.append(ScaleRuleMetricDimension(**dim)) + self.parameters['dimensions'] = dimensions + self.parameters['metric_resource_uri'] = None # will be filled in later + self.parameters['time_grain'] = None # will be filled in later + self.parameters['statistic'] = None # will be filled in later + return MetricTrigger(**self.parameters) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/README.md b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/README.md new file mode 100644 index 00000000000..d0ae6ea3c16 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/README.md @@ -0,0 +1,28 @@ +# Working with the ANTLR grammar in Azure CLI + +The ANTLR grammar is used to generate expression parsing for the `az monitor autoscale rule create` commands. Due to the complexity, and introduction of other authoring features, it is *not* recommended that new commands follow this pattern. + +## SETUP + +To set up your system to be able to alter and regenerate the grammar code, see the QuickStart section on [the ANTLR website](https://www.antlr.org/). You will need to have the Java JDK (JRE is *not* sufficient) installed. + +The steps for Windows are replicated here: +``` +Download https://www.antlr.org/download/antlr-4.9.3-complete.jar. +Add antlr4-complete.jar to CLASSPATH, either: +Permanently: Using System Properties dialog > Environment variables > Create or append to CLASSPATH variable +Temporarily, at command line: +SET CLASSPATH=.;C:\Javalib\antlr-4.9.3-complete.jar;%CLASSPATH% +``` + +You will likely also need to add the path to your JDK bin directory to your PATH. + +## MAKING CHANGES + +1. Make updates to the `AutoscaleCondition.g4` grammar file. +2. Test your changes by entering a condition expression in a file called `test.txt` and running `run_test.bat`. This will open a GUI where you can visually see how your expression will be parsed--useful in identifying problems with your grammar. +3. Once you are happy with the grammar changes, run `build_python.bat` to update the generated Python classes. Add the license header to the three generated files. +4. Add a test to cover your new scenario. +5. Update the `AutoscaleConditionValidator.py` file until your test passes. +6. Clean up the unneeded Java files `del *.class *.java *.tokens *.interp test.txt` +7. Open a PR. License headers and pylint annotations will be removed during autogeneration, so you will need to reverse those lines. diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/__init__.py new file mode 100644 index 00000000000..91f0ce7dd30 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/__init__.py @@ -0,0 +1,10 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-import +from .AutoscaleConditionLexer import AutoscaleConditionLexer +from .AutoscaleConditionParser import AutoscaleConditionParser +from .AutoscaleConditionListener import AutoscaleConditionListener +from .AutoscaleConditionValidator import AutoscaleConditionValidator diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/antlr.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/antlr.bat new file mode 100644 index 00000000000..f372d21e618 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/antlr.bat @@ -0,0 +1 @@ +java org.antlr.v4.Tool %* diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/build_python.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/build_python.bat new file mode 100644 index 00000000000..e70e4c9ce67 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/build_python.bat @@ -0,0 +1,3 @@ +echo off +echo Building AutoscaleCondition +call antlr -Dlanguage=Python3 AutoscaleCondition.g4 diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/grun.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/grun.bat new file mode 100644 index 00000000000..de42a9366db --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/grun.bat @@ -0,0 +1,5 @@ +@ECHO OFF +SET TEST_CURRENT_DIR=%CLASSPATH:.;=% +if "%TEST_CURRENT_DIR%" == "%CLASSPATH%" ( SET CLASSPATH=.;%CLASSPATH% ) +@ECHO ON +java org.antlr.v4.gui.TestRig %* diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/run_test.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/run_test.bat new file mode 100644 index 00000000000..4ebe47d021d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/autoscale/run_test.bat @@ -0,0 +1,5 @@ +echo off +echo Testing AutoscaleCondition +call antlr AutoscaleCondition.g4 +call javac Autoscale*.java +call grun AutoscaleCondition expression test.txt -gui diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertCondition.g4 b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertCondition.g4 new file mode 100644 index 00000000000..712c67315a7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertCondition.g4 @@ -0,0 +1,111 @@ +/* PARSER RULES */ + +grammar MetricAlertCondition ; + +/* Main Rules */ + +expression : aggregation (namespace '.')* (QUOTE metric QUOTE WHITESPACE | metric) operator (threshold | dynamics) (WHITESPACE dimensions)* (WHITESPACE options_)? NEWLINE* ; + +aggregation : WORD WHITESPACE ; + +namespace : (NUMBER | WORD | '/' | '.' | '-')+; + +metric : (NUMBER | WORD | WHITESPACE | '.' | '/' | '_' | '\\' | ':' | '%' | '-' | ',' | '|' | '(' | ')')+; + +operator : OPERATOR WHITESPACE ; + +/* Statics */ + +threshold : NUMBER ; + +/* Dynamics */ + +dynamic : DYNAMIC WHITESPACE ; + +dynamics : dynamic dyn_sensitivity dyn_violations dyn_of_separator dyn_windows (WHITESPACE dyn_since_seperator dyn_datetime)* ; + +dyn_sensitivity : WORD WHITESPACE ; + +dyn_violations : NUMBER WHITESPACE ; + +dyn_of_separator : OF WHITESPACE ; + +dyn_windows : NUMBER ; + +dyn_since_seperator : SINCE WHITESPACE ; + +dyn_datetime : (NUMBER | WORD | '.' | '-' | ':' | '+')+; + +/* Dimensions */ + +where : WHERE WHITESPACE ; + +dimensions : where dimension (dim_separator dimension)* ; + +dimension : dim_name dim_operator dim_values ; + +dim_separator : (AND | ',') WHITESPACE ; + +dim_operator : (INCLUDES | EXCLUDES) WHITESPACE ; + +dim_val_separator : (OR | ',') WHITESPACE ; + +dim_name : WORD WHITESPACE ; + +dim_values : dim_value (dim_val_separator dim_value)* ; + +dim_value : (NUMBER | WORD | '-' | '.' | '*' | WHITESPACE | ':'| '~' | ',' | '|' | '%' | '_')+ ; + +/* Options */ + +options_ : with_ option ; + +with_ : WITH WHITESPACE ; + +option : SKIPMETRICVALIDATION ; + +/* LEXER RULES */ + +fragment A : ('a'|'A') ; +fragment C : ('c'|'C') ; +fragment D : ('d'|'D') ; +fragment E : ('e'|'E') ; +fragment F : ('f'|'F') ; +fragment H : ('h'|'H') ; +fragment I : ('i'|'I') ; +fragment K : ('k'|'K') ; +fragment L : ('l'|'L') ; +fragment M : ('m'|'M') ; +fragment N : ('n'|'N') ; +fragment O : ('o'|'O') ; +fragment P : ('p'|'P') ; +fragment R : ('r'|'R') ; +fragment S : ('s'|'S') ; +fragment T : ('t'|'T') ; +fragment U : ('u'|'U') ; +fragment V : ('v'|'V') ; +fragment W : ('w'|'W') ; +fragment X : ('x'|'X') ; +fragment Y : ('y'|'Y') ; + +fragment DIGIT : [0-9] ; +fragment LOWERCASE : [a-z] ; +fragment UPPERCASE : [A-Z] ; + +WHERE : W H E R E ; +AND : A N D ; +INCLUDES : I N C L U D E S ; +EXCLUDES : E X C L U D E S ; +OR : O R ; +DYNAMIC : D Y N A M I C ; +OF : O F ; +SINCE : S I N C E ; +WITH : W I T H ; +SKIPMETRICVALIDATION : S K I P M E T R I C V A L I D A T I O N ; + +OPERATOR : ('<' | '<=' | '=' | '>=' | '>' | '!=' | '><') ; +NUMBER : DIGIT+ ([.,] DIGIT+)? ; +QUOTE : ('\'' | '"') ; +WHITESPACE : (' ' | '\t')+ ; +NEWLINE : ('\r'? '\n' | '\r')+ ; +WORD : (LOWERCASE | UPPERCASE | DIGIT | '_' )+ ; diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionLexer.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionLexer.py new file mode 100644 index 00000000000..45ee78794e7 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionLexer.py @@ -0,0 +1,198 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from MetricAlertCondition.g4 by ANTLR 4.13.1 +# encoding: utf-8 +# pylint: disable=all +from antlr4 import * +from io import StringIO +import sys +from typing import TextIO + + +def serializedATN(): + return [ + 4,0,30,309,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5, + 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2, + 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7, + 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2, + 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7, + 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2, + 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7, + 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2, + 52,7,52,2,53,7,53,1,0,1,0,1,1,1,1,1,2,1,2,1,3,1,3,1,4,1,4,1,5,1, + 5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12, + 1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19, + 1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,23,1,23,1,24,1,24,1,25,1,25, + 1,26,1,26,1,27,1,27,1,28,1,28,1,29,1,29,1,30,1,30,1,31,1,31,1,32, + 1,32,1,33,1,33,1,34,1,34,1,35,1,35,1,36,1,36,1,37,1,37,1,38,1,38, + 1,38,1,38,1,38,1,38,1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40, + 1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41,1,41,1,41,1,41, + 1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,43,1,43,1,43,1,44,1,44, + 1,44,1,45,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46,1,47, + 1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47, + 1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48,1,48,1,48,1,48,1,48, + 1,48,1,48,1,48,1,48,1,48,3,48,271,8,48,1,49,4,49,274,8,49,11,49, + 12,49,275,1,49,1,49,4,49,280,8,49,11,49,12,49,281,3,49,284,8,49, + 1,50,1,50,1,51,4,51,289,8,51,11,51,12,51,290,1,52,3,52,294,8,52, + 1,52,1,52,4,52,298,8,52,11,52,12,52,299,1,53,1,53,1,53,1,53,4,53, + 306,8,53,11,53,12,53,307,0,0,54,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15, + 8,17,9,19,10,21,11,23,12,25,13,27,14,29,0,31,0,33,0,35,0,37,0,39, + 0,41,0,43,0,45,0,47,0,49,0,51,0,53,0,55,0,57,0,59,0,61,0,63,0,65, + 0,67,0,69,0,71,0,73,0,75,0,77,15,79,16,81,17,83,18,85,19,87,20,89, + 21,91,22,93,23,95,24,97,25,99,26,101,27,103,28,105,29,107,30,1,0, + 27,2,0,65,65,97,97,2,0,67,67,99,99,2,0,68,68,100,100,2,0,69,69,101, + 101,2,0,70,70,102,102,2,0,72,72,104,104,2,0,73,73,105,105,2,0,75, + 75,107,107,2,0,76,76,108,108,2,0,77,77,109,109,2,0,78,78,110,110, + 2,0,79,79,111,111,2,0,80,80,112,112,2,0,82,82,114,114,2,0,83,83, + 115,115,2,0,84,84,116,116,2,0,85,85,117,117,2,0,86,86,118,118,2, + 0,87,87,119,119,2,0,88,88,120,120,2,0,89,89,121,121,1,0,48,57,1, + 0,97,122,1,0,65,90,2,0,44,44,46,46,2,0,34,34,39,39,2,0,9,9,32,32, + 301,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0, + 0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,1,0,0,0, + 0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,1,0,0,0,0,77,1,0,0,0, + 0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,87,1,0,0,0, + 0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0, + 0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0,0,0,107,1,0, + 0,0,1,109,1,0,0,0,3,111,1,0,0,0,5,113,1,0,0,0,7,115,1,0,0,0,9,117, + 1,0,0,0,11,119,1,0,0,0,13,121,1,0,0,0,15,123,1,0,0,0,17,125,1,0, + 0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0,0,0, + 27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0,35,143, + 1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151,1,0, + 0,0,45,153,1,0,0,0,47,155,1,0,0,0,49,157,1,0,0,0,51,159,1,0,0,0, + 53,161,1,0,0,0,55,163,1,0,0,0,57,165,1,0,0,0,59,167,1,0,0,0,61,169, + 1,0,0,0,63,171,1,0,0,0,65,173,1,0,0,0,67,175,1,0,0,0,69,177,1,0, + 0,0,71,179,1,0,0,0,73,181,1,0,0,0,75,183,1,0,0,0,77,185,1,0,0,0, + 79,191,1,0,0,0,81,195,1,0,0,0,83,204,1,0,0,0,85,213,1,0,0,0,87,216, + 1,0,0,0,89,224,1,0,0,0,91,227,1,0,0,0,93,233,1,0,0,0,95,238,1,0, + 0,0,97,270,1,0,0,0,99,273,1,0,0,0,101,285,1,0,0,0,103,288,1,0,0, + 0,105,297,1,0,0,0,107,305,1,0,0,0,109,110,5,46,0,0,110,2,1,0,0,0, + 111,112,5,47,0,0,112,4,1,0,0,0,113,114,5,45,0,0,114,6,1,0,0,0,115, + 116,5,95,0,0,116,8,1,0,0,0,117,118,5,92,0,0,118,10,1,0,0,0,119,120, + 5,58,0,0,120,12,1,0,0,0,121,122,5,37,0,0,122,14,1,0,0,0,123,124, + 5,44,0,0,124,16,1,0,0,0,125,126,5,124,0,0,126,18,1,0,0,0,127,128, + 5,40,0,0,128,20,1,0,0,0,129,130,5,41,0,0,130,22,1,0,0,0,131,132, + 5,43,0,0,132,24,1,0,0,0,133,134,5,42,0,0,134,26,1,0,0,0,135,136, + 5,126,0,0,136,28,1,0,0,0,137,138,7,0,0,0,138,30,1,0,0,0,139,140, + 7,1,0,0,140,32,1,0,0,0,141,142,7,2,0,0,142,34,1,0,0,0,143,144,7, + 3,0,0,144,36,1,0,0,0,145,146,7,4,0,0,146,38,1,0,0,0,147,148,7,5, + 0,0,148,40,1,0,0,0,149,150,7,6,0,0,150,42,1,0,0,0,151,152,7,7,0, + 0,152,44,1,0,0,0,153,154,7,8,0,0,154,46,1,0,0,0,155,156,7,9,0,0, + 156,48,1,0,0,0,157,158,7,10,0,0,158,50,1,0,0,0,159,160,7,11,0,0, + 160,52,1,0,0,0,161,162,7,12,0,0,162,54,1,0,0,0,163,164,7,13,0,0, + 164,56,1,0,0,0,165,166,7,14,0,0,166,58,1,0,0,0,167,168,7,15,0,0, + 168,60,1,0,0,0,169,170,7,16,0,0,170,62,1,0,0,0,171,172,7,17,0,0, + 172,64,1,0,0,0,173,174,7,18,0,0,174,66,1,0,0,0,175,176,7,19,0,0, + 176,68,1,0,0,0,177,178,7,20,0,0,178,70,1,0,0,0,179,180,7,21,0,0, + 180,72,1,0,0,0,181,182,7,22,0,0,182,74,1,0,0,0,183,184,7,23,0,0, + 184,76,1,0,0,0,185,186,3,65,32,0,186,187,3,39,19,0,187,188,3,35, + 17,0,188,189,3,55,27,0,189,190,3,35,17,0,190,78,1,0,0,0,191,192, + 3,29,14,0,192,193,3,49,24,0,193,194,3,33,16,0,194,80,1,0,0,0,195, + 196,3,41,20,0,196,197,3,49,24,0,197,198,3,31,15,0,198,199,3,45,22, + 0,199,200,3,61,30,0,200,201,3,33,16,0,201,202,3,35,17,0,202,203, + 3,57,28,0,203,82,1,0,0,0,204,205,3,35,17,0,205,206,3,67,33,0,206, + 207,3,31,15,0,207,208,3,45,22,0,208,209,3,61,30,0,209,210,3,33,16, + 0,210,211,3,35,17,0,211,212,3,57,28,0,212,84,1,0,0,0,213,214,3,51, + 25,0,214,215,3,55,27,0,215,86,1,0,0,0,216,217,3,33,16,0,217,218, + 3,69,34,0,218,219,3,49,24,0,219,220,3,29,14,0,220,221,3,47,23,0, + 221,222,3,41,20,0,222,223,3,31,15,0,223,88,1,0,0,0,224,225,3,51, + 25,0,225,226,3,37,18,0,226,90,1,0,0,0,227,228,3,57,28,0,228,229, + 3,41,20,0,229,230,3,49,24,0,230,231,3,31,15,0,231,232,3,35,17,0, + 232,92,1,0,0,0,233,234,3,65,32,0,234,235,3,41,20,0,235,236,3,59, + 29,0,236,237,3,39,19,0,237,94,1,0,0,0,238,239,3,57,28,0,239,240, + 3,43,21,0,240,241,3,41,20,0,241,242,3,53,26,0,242,243,3,47,23,0, + 243,244,3,35,17,0,244,245,3,59,29,0,245,246,3,55,27,0,246,247,3, + 41,20,0,247,248,3,31,15,0,248,249,3,63,31,0,249,250,3,29,14,0,250, + 251,3,45,22,0,251,252,3,41,20,0,252,253,3,33,16,0,253,254,3,29,14, + 0,254,255,3,59,29,0,255,256,3,41,20,0,256,257,3,51,25,0,257,258, + 3,49,24,0,258,96,1,0,0,0,259,271,5,60,0,0,260,261,5,60,0,0,261,271, + 5,61,0,0,262,271,5,61,0,0,263,264,5,62,0,0,264,271,5,61,0,0,265, + 271,5,62,0,0,266,267,5,33,0,0,267,271,5,61,0,0,268,269,5,62,0,0, + 269,271,5,60,0,0,270,259,1,0,0,0,270,260,1,0,0,0,270,262,1,0,0,0, + 270,263,1,0,0,0,270,265,1,0,0,0,270,266,1,0,0,0,270,268,1,0,0,0, + 271,98,1,0,0,0,272,274,3,71,35,0,273,272,1,0,0,0,274,275,1,0,0,0, + 275,273,1,0,0,0,275,276,1,0,0,0,276,283,1,0,0,0,277,279,7,24,0,0, + 278,280,3,71,35,0,279,278,1,0,0,0,280,281,1,0,0,0,281,279,1,0,0, + 0,281,282,1,0,0,0,282,284,1,0,0,0,283,277,1,0,0,0,283,284,1,0,0, + 0,284,100,1,0,0,0,285,286,7,25,0,0,286,102,1,0,0,0,287,289,7,26, + 0,0,288,287,1,0,0,0,289,290,1,0,0,0,290,288,1,0,0,0,290,291,1,0, + 0,0,291,104,1,0,0,0,292,294,5,13,0,0,293,292,1,0,0,0,293,294,1,0, + 0,0,294,295,1,0,0,0,295,298,5,10,0,0,296,298,5,13,0,0,297,293,1, + 0,0,0,297,296,1,0,0,0,298,299,1,0,0,0,299,297,1,0,0,0,299,300,1, + 0,0,0,300,106,1,0,0,0,301,306,3,73,36,0,302,306,3,75,37,0,303,306, + 3,71,35,0,304,306,5,95,0,0,305,301,1,0,0,0,305,302,1,0,0,0,305,303, + 1,0,0,0,305,304,1,0,0,0,306,307,1,0,0,0,307,305,1,0,0,0,307,308, + 1,0,0,0,308,108,1,0,0,0,11,0,270,275,281,283,290,293,297,299,305, + 307,0 + ] + +class MetricAlertConditionLexer(Lexer): + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + T__0 = 1 + T__1 = 2 + T__2 = 3 + T__3 = 4 + T__4 = 5 + T__5 = 6 + T__6 = 7 + T__7 = 8 + T__8 = 9 + T__9 = 10 + T__10 = 11 + T__11 = 12 + T__12 = 13 + T__13 = 14 + WHERE = 15 + AND = 16 + INCLUDES = 17 + EXCLUDES = 18 + OR = 19 + DYNAMIC = 20 + OF = 21 + SINCE = 22 + WITH = 23 + SKIPMETRICVALIDATION = 24 + OPERATOR = 25 + NUMBER = 26 + QUOTE = 27 + WHITESPACE = 28 + NEWLINE = 29 + WORD = 30 + + channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ] + + modeNames = [ "DEFAULT_MODE" ] + + literalNames = [ "", + "'.'", "'/'", "'-'", "'_'", "'\\'", "':'", "'%'", "','", "'|'", + "'('", "')'", "'+'", "'*'", "'~'" ] + + symbolicNames = [ "", + "WHERE", "AND", "INCLUDES", "EXCLUDES", "OR", "DYNAMIC", "OF", + "SINCE", "WITH", "SKIPMETRICVALIDATION", "OPERATOR", "NUMBER", + "QUOTE", "WHITESPACE", "NEWLINE", "WORD" ] + + ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", + "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13", + "A", "C", "D", "E", "F", "H", "I", "K", "L", "M", "N", + "O", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "DIGIT", + "LOWERCASE", "UPPERCASE", "WHERE", "AND", "INCLUDES", + "EXCLUDES", "OR", "DYNAMIC", "OF", "SINCE", "WITH", "SKIPMETRICVALIDATION", + "OPERATOR", "NUMBER", "QUOTE", "WHITESPACE", "NEWLINE", + "WORD" ] + + grammarFileName = "MetricAlertCondition.g4" + + def __init__(self, input=None, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.13.1") + self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) + self._actions = None + self._predicates = None + + diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionListener.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionListener.py new file mode 100644 index 00000000000..fd784e63092 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionListener.py @@ -0,0 +1,252 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from MetricAlertCondition.g4 by ANTLR 4.13.1 +# encoding: utf-8 +# pylint: disable=all +from antlr4 import * +if "." in __name__: + from .MetricAlertConditionParser import MetricAlertConditionParser +else: + from MetricAlertConditionParser import MetricAlertConditionParser + +# This class defines a complete listener for a parse tree produced by MetricAlertConditionParser. +class MetricAlertConditionListener(ParseTreeListener): + + # Enter a parse tree produced by MetricAlertConditionParser#expression. + def enterExpression(self, ctx:MetricAlertConditionParser.ExpressionContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#expression. + def exitExpression(self, ctx:MetricAlertConditionParser.ExpressionContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#aggregation. + def enterAggregation(self, ctx:MetricAlertConditionParser.AggregationContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#aggregation. + def exitAggregation(self, ctx:MetricAlertConditionParser.AggregationContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#namespace. + def enterNamespace(self, ctx:MetricAlertConditionParser.NamespaceContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#namespace. + def exitNamespace(self, ctx:MetricAlertConditionParser.NamespaceContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#metric. + def enterMetric(self, ctx:MetricAlertConditionParser.MetricContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#metric. + def exitMetric(self, ctx:MetricAlertConditionParser.MetricContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#operator. + def enterOperator(self, ctx:MetricAlertConditionParser.OperatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#operator. + def exitOperator(self, ctx:MetricAlertConditionParser.OperatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#threshold. + def enterThreshold(self, ctx:MetricAlertConditionParser.ThresholdContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#threshold. + def exitThreshold(self, ctx:MetricAlertConditionParser.ThresholdContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dynamic. + def enterDynamic(self, ctx:MetricAlertConditionParser.DynamicContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dynamic. + def exitDynamic(self, ctx:MetricAlertConditionParser.DynamicContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dynamics. + def enterDynamics(self, ctx:MetricAlertConditionParser.DynamicsContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dynamics. + def exitDynamics(self, ctx:MetricAlertConditionParser.DynamicsContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_sensitivity. + def enterDyn_sensitivity(self, ctx:MetricAlertConditionParser.Dyn_sensitivityContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_sensitivity. + def exitDyn_sensitivity(self, ctx:MetricAlertConditionParser.Dyn_sensitivityContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_violations. + def enterDyn_violations(self, ctx:MetricAlertConditionParser.Dyn_violationsContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_violations. + def exitDyn_violations(self, ctx:MetricAlertConditionParser.Dyn_violationsContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_of_separator. + def enterDyn_of_separator(self, ctx:MetricAlertConditionParser.Dyn_of_separatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_of_separator. + def exitDyn_of_separator(self, ctx:MetricAlertConditionParser.Dyn_of_separatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_windows. + def enterDyn_windows(self, ctx:MetricAlertConditionParser.Dyn_windowsContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_windows. + def exitDyn_windows(self, ctx:MetricAlertConditionParser.Dyn_windowsContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_since_seperator. + def enterDyn_since_seperator(self, ctx:MetricAlertConditionParser.Dyn_since_seperatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_since_seperator. + def exitDyn_since_seperator(self, ctx:MetricAlertConditionParser.Dyn_since_seperatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dyn_datetime. + def enterDyn_datetime(self, ctx:MetricAlertConditionParser.Dyn_datetimeContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dyn_datetime. + def exitDyn_datetime(self, ctx:MetricAlertConditionParser.Dyn_datetimeContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#where. + def enterWhere(self, ctx:MetricAlertConditionParser.WhereContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#where. + def exitWhere(self, ctx:MetricAlertConditionParser.WhereContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dimensions. + def enterDimensions(self, ctx:MetricAlertConditionParser.DimensionsContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dimensions. + def exitDimensions(self, ctx:MetricAlertConditionParser.DimensionsContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dimension. + def enterDimension(self, ctx:MetricAlertConditionParser.DimensionContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dimension. + def exitDimension(self, ctx:MetricAlertConditionParser.DimensionContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_separator. + def enterDim_separator(self, ctx:MetricAlertConditionParser.Dim_separatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_separator. + def exitDim_separator(self, ctx:MetricAlertConditionParser.Dim_separatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_operator. + def enterDim_operator(self, ctx:MetricAlertConditionParser.Dim_operatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_operator. + def exitDim_operator(self, ctx:MetricAlertConditionParser.Dim_operatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_val_separator. + def enterDim_val_separator(self, ctx:MetricAlertConditionParser.Dim_val_separatorContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_val_separator. + def exitDim_val_separator(self, ctx:MetricAlertConditionParser.Dim_val_separatorContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_name. + def enterDim_name(self, ctx:MetricAlertConditionParser.Dim_nameContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_name. + def exitDim_name(self, ctx:MetricAlertConditionParser.Dim_nameContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_values. + def enterDim_values(self, ctx:MetricAlertConditionParser.Dim_valuesContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_values. + def exitDim_values(self, ctx:MetricAlertConditionParser.Dim_valuesContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#dim_value. + def enterDim_value(self, ctx:MetricAlertConditionParser.Dim_valueContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#dim_value. + def exitDim_value(self, ctx:MetricAlertConditionParser.Dim_valueContext): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#options_. + def enterOptions_(self, ctx:MetricAlertConditionParser.Options_Context): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#options_. + def exitOptions_(self, ctx:MetricAlertConditionParser.Options_Context): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#with_. + def enterWith_(self, ctx:MetricAlertConditionParser.With_Context): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#with_. + def exitWith_(self, ctx:MetricAlertConditionParser.With_Context): + pass + + + # Enter a parse tree produced by MetricAlertConditionParser#option. + def enterOption(self, ctx:MetricAlertConditionParser.OptionContext): + pass + + # Exit a parse tree produced by MetricAlertConditionParser#option. + def exitOption(self, ctx:MetricAlertConditionParser.OptionContext): + pass + + + +del MetricAlertConditionParser diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionParser.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionParser.py new file mode 100644 index 00000000000..3734692f060 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionParser.py @@ -0,0 +1,1717 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# Generated from MetricAlertCondition.g4 by ANTLR 4.13.1 +# encoding: utf-8 +# pylint: disable=all +from antlr4 import * +import sys +from typing import TextIO + +def serializedATN(): + return [ + 4,1,30,197,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7, + 6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13, + 2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20, + 7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,1,0,1,0,1, + 0,1,0,5,0,57,8,0,10,0,12,0,60,9,0,1,0,1,0,1,0,1,0,1,0,1,0,3,0,68, + 8,0,1,0,1,0,1,0,3,0,73,8,0,1,0,1,0,5,0,77,8,0,10,0,12,0,80,9,0,1, + 0,1,0,3,0,84,8,0,1,0,5,0,87,8,0,10,0,12,0,90,9,0,1,1,1,1,1,1,1,2, + 4,2,96,8,2,11,2,12,2,97,1,3,4,3,101,8,3,11,3,12,3,102,1,4,1,4,1, + 4,1,5,1,5,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,1,7,5,7,122, + 8,7,10,7,12,7,125,9,7,1,8,1,8,1,8,1,9,1,9,1,9,1,10,1,10,1,10,1,11, + 1,11,1,12,1,12,1,12,1,13,4,13,142,8,13,11,13,12,13,143,1,14,1,14, + 1,14,1,15,1,15,1,15,1,15,1,15,5,15,154,8,15,10,15,12,15,157,9,15, + 1,16,1,16,1,16,1,16,1,17,1,17,1,17,1,18,1,18,1,18,1,19,1,19,1,19, + 1,20,1,20,1,20,1,21,1,21,1,21,1,21,5,21,179,8,21,10,21,12,21,182, + 9,21,1,22,4,22,185,8,22,11,22,12,22,186,1,23,1,23,1,23,1,24,1,24, + 1,24,1,25,1,25,1,25,0,0,26,0,2,4,6,8,10,12,14,16,18,20,22,24,26, + 28,30,32,34,36,38,40,42,44,46,48,50,0,7,3,0,1,3,26,26,30,30,4,0, + 1,11,26,26,28,28,30,30,6,0,1,1,3,3,6,6,12,12,26,26,30,30,2,0,8,8, + 16,16,1,0,17,18,2,0,8,8,19,19,7,0,1,1,3,4,6,9,13,14,26,26,28,28, + 30,30,183,0,52,1,0,0,0,2,91,1,0,0,0,4,95,1,0,0,0,6,100,1,0,0,0,8, + 104,1,0,0,0,10,107,1,0,0,0,12,109,1,0,0,0,14,112,1,0,0,0,16,126, + 1,0,0,0,18,129,1,0,0,0,20,132,1,0,0,0,22,135,1,0,0,0,24,137,1,0, + 0,0,26,141,1,0,0,0,28,145,1,0,0,0,30,148,1,0,0,0,32,158,1,0,0,0, + 34,162,1,0,0,0,36,165,1,0,0,0,38,168,1,0,0,0,40,171,1,0,0,0,42,174, + 1,0,0,0,44,184,1,0,0,0,46,188,1,0,0,0,48,191,1,0,0,0,50,194,1,0, + 0,0,52,58,3,2,1,0,53,54,3,4,2,0,54,55,5,1,0,0,55,57,1,0,0,0,56,53, + 1,0,0,0,57,60,1,0,0,0,58,56,1,0,0,0,58,59,1,0,0,0,59,67,1,0,0,0, + 60,58,1,0,0,0,61,62,5,27,0,0,62,63,3,6,3,0,63,64,5,27,0,0,64,65, + 5,28,0,0,65,68,1,0,0,0,66,68,3,6,3,0,67,61,1,0,0,0,67,66,1,0,0,0, + 68,69,1,0,0,0,69,72,3,8,4,0,70,73,3,10,5,0,71,73,3,14,7,0,72,70, + 1,0,0,0,72,71,1,0,0,0,73,78,1,0,0,0,74,75,5,28,0,0,75,77,3,30,15, + 0,76,74,1,0,0,0,77,80,1,0,0,0,78,76,1,0,0,0,78,79,1,0,0,0,79,83, + 1,0,0,0,80,78,1,0,0,0,81,82,5,28,0,0,82,84,3,46,23,0,83,81,1,0,0, + 0,83,84,1,0,0,0,84,88,1,0,0,0,85,87,5,29,0,0,86,85,1,0,0,0,87,90, + 1,0,0,0,88,86,1,0,0,0,88,89,1,0,0,0,89,1,1,0,0,0,90,88,1,0,0,0,91, + 92,5,30,0,0,92,93,5,28,0,0,93,3,1,0,0,0,94,96,7,0,0,0,95,94,1,0, + 0,0,96,97,1,0,0,0,97,95,1,0,0,0,97,98,1,0,0,0,98,5,1,0,0,0,99,101, + 7,1,0,0,100,99,1,0,0,0,101,102,1,0,0,0,102,100,1,0,0,0,102,103,1, + 0,0,0,103,7,1,0,0,0,104,105,5,25,0,0,105,106,5,28,0,0,106,9,1,0, + 0,0,107,108,5,26,0,0,108,11,1,0,0,0,109,110,5,20,0,0,110,111,5,28, + 0,0,111,13,1,0,0,0,112,113,3,12,6,0,113,114,3,16,8,0,114,115,3,18, + 9,0,115,116,3,20,10,0,116,123,3,22,11,0,117,118,5,28,0,0,118,119, + 3,24,12,0,119,120,3,26,13,0,120,122,1,0,0,0,121,117,1,0,0,0,122, + 125,1,0,0,0,123,121,1,0,0,0,123,124,1,0,0,0,124,15,1,0,0,0,125,123, + 1,0,0,0,126,127,5,30,0,0,127,128,5,28,0,0,128,17,1,0,0,0,129,130, + 5,26,0,0,130,131,5,28,0,0,131,19,1,0,0,0,132,133,5,21,0,0,133,134, + 5,28,0,0,134,21,1,0,0,0,135,136,5,26,0,0,136,23,1,0,0,0,137,138, + 5,22,0,0,138,139,5,28,0,0,139,25,1,0,0,0,140,142,7,2,0,0,141,140, + 1,0,0,0,142,143,1,0,0,0,143,141,1,0,0,0,143,144,1,0,0,0,144,27,1, + 0,0,0,145,146,5,15,0,0,146,147,5,28,0,0,147,29,1,0,0,0,148,149,3, + 28,14,0,149,155,3,32,16,0,150,151,3,34,17,0,151,152,3,32,16,0,152, + 154,1,0,0,0,153,150,1,0,0,0,154,157,1,0,0,0,155,153,1,0,0,0,155, + 156,1,0,0,0,156,31,1,0,0,0,157,155,1,0,0,0,158,159,3,40,20,0,159, + 160,3,36,18,0,160,161,3,42,21,0,161,33,1,0,0,0,162,163,7,3,0,0,163, + 164,5,28,0,0,164,35,1,0,0,0,165,166,7,4,0,0,166,167,5,28,0,0,167, + 37,1,0,0,0,168,169,7,5,0,0,169,170,5,28,0,0,170,39,1,0,0,0,171,172, + 5,30,0,0,172,173,5,28,0,0,173,41,1,0,0,0,174,180,3,44,22,0,175,176, + 3,38,19,0,176,177,3,44,22,0,177,179,1,0,0,0,178,175,1,0,0,0,179, + 182,1,0,0,0,180,178,1,0,0,0,180,181,1,0,0,0,181,43,1,0,0,0,182,180, + 1,0,0,0,183,185,7,6,0,0,184,183,1,0,0,0,185,186,1,0,0,0,186,184, + 1,0,0,0,186,187,1,0,0,0,187,45,1,0,0,0,188,189,3,48,24,0,189,190, + 3,50,25,0,190,47,1,0,0,0,191,192,5,23,0,0,192,193,5,28,0,0,193,49, + 1,0,0,0,194,195,5,24,0,0,195,51,1,0,0,0,13,58,67,72,78,83,88,97, + 102,123,143,155,180,186 + ] + +class MetricAlertConditionParser ( Parser ): + + grammarFileName = "MetricAlertCondition.g4" + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + sharedContextCache = PredictionContextCache() + + literalNames = [ "", "'.'", "'/'", "'-'", "'_'", "'\\'", "':'", + "'%'", "','", "'|'", "'('", "')'", "'+'", "'*'", "'~'" ] + + symbolicNames = [ "", "", "", "", + "", "", "", "", + "", "", "", "", + "", "", "", "WHERE", "AND", + "INCLUDES", "EXCLUDES", "OR", "DYNAMIC", "OF", "SINCE", + "WITH", "SKIPMETRICVALIDATION", "OPERATOR", "NUMBER", + "QUOTE", "WHITESPACE", "NEWLINE", "WORD" ] + + RULE_expression = 0 + RULE_aggregation = 1 + RULE_namespace = 2 + RULE_metric = 3 + RULE_operator = 4 + RULE_threshold = 5 + RULE_dynamic = 6 + RULE_dynamics = 7 + RULE_dyn_sensitivity = 8 + RULE_dyn_violations = 9 + RULE_dyn_of_separator = 10 + RULE_dyn_windows = 11 + RULE_dyn_since_seperator = 12 + RULE_dyn_datetime = 13 + RULE_where = 14 + RULE_dimensions = 15 + RULE_dimension = 16 + RULE_dim_separator = 17 + RULE_dim_operator = 18 + RULE_dim_val_separator = 19 + RULE_dim_name = 20 + RULE_dim_values = 21 + RULE_dim_value = 22 + RULE_options_ = 23 + RULE_with_ = 24 + RULE_option = 25 + + ruleNames = [ "expression", "aggregation", "namespace", "metric", "operator", + "threshold", "dynamic", "dynamics", "dyn_sensitivity", + "dyn_violations", "dyn_of_separator", "dyn_windows", + "dyn_since_seperator", "dyn_datetime", "where", "dimensions", + "dimension", "dim_separator", "dim_operator", "dim_val_separator", + "dim_name", "dim_values", "dim_value", "options_", "with_", + "option" ] + + EOF = Token.EOF + T__0=1 + T__1=2 + T__2=3 + T__3=4 + T__4=5 + T__5=6 + T__6=7 + T__7=8 + T__8=9 + T__9=10 + T__10=11 + T__11=12 + T__12=13 + T__13=14 + WHERE=15 + AND=16 + INCLUDES=17 + EXCLUDES=18 + OR=19 + DYNAMIC=20 + OF=21 + SINCE=22 + WITH=23 + SKIPMETRICVALIDATION=24 + OPERATOR=25 + NUMBER=26 + QUOTE=27 + WHITESPACE=28 + NEWLINE=29 + WORD=30 + + def __init__(self, input:TokenStream, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.13.1") + self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) + self._predicates = None + + + + + class ExpressionContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def aggregation(self): + return self.getTypedRuleContext(MetricAlertConditionParser.AggregationContext,0) + + + def operator(self): + return self.getTypedRuleContext(MetricAlertConditionParser.OperatorContext,0) + + + def QUOTE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.QUOTE) + else: + return self.getToken(MetricAlertConditionParser.QUOTE, i) + + def metric(self): + return self.getTypedRuleContext(MetricAlertConditionParser.MetricContext,0) + + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WHITESPACE) + else: + return self.getToken(MetricAlertConditionParser.WHITESPACE, i) + + def threshold(self): + return self.getTypedRuleContext(MetricAlertConditionParser.ThresholdContext,0) + + + def dynamics(self): + return self.getTypedRuleContext(MetricAlertConditionParser.DynamicsContext,0) + + + def namespace(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.NamespaceContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.NamespaceContext,i) + + + def dimensions(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionsContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.DimensionsContext,i) + + + def options_(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Options_Context,0) + + + def NEWLINE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.NEWLINE) + else: + return self.getToken(MetricAlertConditionParser.NEWLINE, i) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_expression + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterExpression" ): + listener.enterExpression(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitExpression" ): + listener.exitExpression(self) + + + + + def expression(self): + + localctx = MetricAlertConditionParser.ExpressionContext(self, self._ctx, self.state) + self.enterRule(localctx, 0, self.RULE_expression) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 52 + self.aggregation() + self.state = 58 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,0,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + self.state = 53 + self.namespace() + self.state = 54 + self.match(MetricAlertConditionParser.T__0) + self.state = 60 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,0,self._ctx) + + self.state = 67 + self._errHandler.sync(self) + token = self._input.LA(1) + if token in [27]: + self.state = 61 + self.match(MetricAlertConditionParser.QUOTE) + self.state = 62 + self.metric() + self.state = 63 + self.match(MetricAlertConditionParser.QUOTE) + self.state = 64 + self.match(MetricAlertConditionParser.WHITESPACE) + pass + elif token in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 26, 28, 30]: + self.state = 66 + self.metric() + pass + else: + raise NoViableAltException(self) + + self.state = 69 + self.operator() + self.state = 72 + self._errHandler.sync(self) + token = self._input.LA(1) + if token in [26]: + self.state = 70 + self.threshold() + pass + elif token in [20]: + self.state = 71 + self.dynamics() + pass + else: + raise NoViableAltException(self) + + self.state = 78 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,3,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + self.state = 74 + self.match(MetricAlertConditionParser.WHITESPACE) + self.state = 75 + self.dimensions() + self.state = 80 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,3,self._ctx) + + self.state = 83 + self._errHandler.sync(self) + _la = self._input.LA(1) + if _la==28: + self.state = 81 + self.match(MetricAlertConditionParser.WHITESPACE) + self.state = 82 + self.options_() + + + self.state = 88 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==29: + self.state = 85 + self.match(MetricAlertConditionParser.NEWLINE) + self.state = 90 + self._errHandler.sync(self) + _la = self._input.LA(1) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class AggregationContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(MetricAlertConditionParser.WORD, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_aggregation + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterAggregation" ): + listener.enterAggregation(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitAggregation" ): + listener.exitAggregation(self) + + + + + def aggregation(self): + + localctx = MetricAlertConditionParser.AggregationContext(self, self._ctx, self.state) + self.enterRule(localctx, 2, self.RULE_aggregation) + try: + self.enterOuterAlt(localctx, 1) + self.state = 91 + self.match(MetricAlertConditionParser.WORD) + self.state = 92 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class NamespaceContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.NUMBER) + else: + return self.getToken(MetricAlertConditionParser.NUMBER, i) + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WORD) + else: + return self.getToken(MetricAlertConditionParser.WORD, i) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_namespace + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterNamespace" ): + listener.enterNamespace(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitNamespace" ): + listener.exitNamespace(self) + + + + + def namespace(self): + + localctx = MetricAlertConditionParser.NamespaceContext(self, self._ctx, self.state) + self.enterRule(localctx, 4, self.RULE_namespace) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 95 + self._errHandler.sync(self) + _alt = 1 + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt == 1: + self.state = 94 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1140850702) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + + else: + raise NoViableAltException(self) + self.state = 97 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,6,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class MetricContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.NUMBER) + else: + return self.getToken(MetricAlertConditionParser.NUMBER, i) + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WORD) + else: + return self.getToken(MetricAlertConditionParser.WORD, i) + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WHITESPACE) + else: + return self.getToken(MetricAlertConditionParser.WHITESPACE, i) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_metric + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterMetric" ): + listener.enterMetric(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitMetric" ): + listener.exitMetric(self) + + + + + def metric(self): + + localctx = MetricAlertConditionParser.MetricContext(self, self._ctx, self.state) + self.enterRule(localctx, 6, self.RULE_metric) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 100 + self._errHandler.sync(self) + _la = self._input.LA(1) + while True: + self.state = 99 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1409290238) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 102 + self._errHandler.sync(self) + _la = self._input.LA(1) + if not (((_la) & ~0x3f) == 0 and ((1 << _la) & 1409290238) != 0): + break + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class OperatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def OPERATOR(self): + return self.getToken(MetricAlertConditionParser.OPERATOR, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_operator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterOperator" ): + listener.enterOperator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitOperator" ): + listener.exitOperator(self) + + + + + def operator(self): + + localctx = MetricAlertConditionParser.OperatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 8, self.RULE_operator) + try: + self.enterOuterAlt(localctx, 1) + self.state = 104 + self.match(MetricAlertConditionParser.OPERATOR) + self.state = 105 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class ThresholdContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self): + return self.getToken(MetricAlertConditionParser.NUMBER, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_threshold + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterThreshold" ): + listener.enterThreshold(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitThreshold" ): + listener.exitThreshold(self) + + + + + def threshold(self): + + localctx = MetricAlertConditionParser.ThresholdContext(self, self._ctx, self.state) + self.enterRule(localctx, 10, self.RULE_threshold) + try: + self.enterOuterAlt(localctx, 1) + self.state = 107 + self.match(MetricAlertConditionParser.NUMBER) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DynamicContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def DYNAMIC(self): + return self.getToken(MetricAlertConditionParser.DYNAMIC, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dynamic + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDynamic" ): + listener.enterDynamic(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDynamic" ): + listener.exitDynamic(self) + + + + + def dynamic(self): + + localctx = MetricAlertConditionParser.DynamicContext(self, self._ctx, self.state) + self.enterRule(localctx, 12, self.RULE_dynamic) + try: + self.enterOuterAlt(localctx, 1) + self.state = 109 + self.match(MetricAlertConditionParser.DYNAMIC) + self.state = 110 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DynamicsContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def dynamic(self): + return self.getTypedRuleContext(MetricAlertConditionParser.DynamicContext,0) + + + def dyn_sensitivity(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_sensitivityContext,0) + + + def dyn_violations(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_violationsContext,0) + + + def dyn_of_separator(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_of_separatorContext,0) + + + def dyn_windows(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_windowsContext,0) + + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WHITESPACE) + else: + return self.getToken(MetricAlertConditionParser.WHITESPACE, i) + + def dyn_since_seperator(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.Dyn_since_seperatorContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_since_seperatorContext,i) + + + def dyn_datetime(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.Dyn_datetimeContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.Dyn_datetimeContext,i) + + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dynamics + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDynamics" ): + listener.enterDynamics(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDynamics" ): + listener.exitDynamics(self) + + + + + def dynamics(self): + + localctx = MetricAlertConditionParser.DynamicsContext(self, self._ctx, self.state) + self.enterRule(localctx, 14, self.RULE_dynamics) + try: + self.enterOuterAlt(localctx, 1) + self.state = 112 + self.dynamic() + self.state = 113 + self.dyn_sensitivity() + self.state = 114 + self.dyn_violations() + self.state = 115 + self.dyn_of_separator() + self.state = 116 + self.dyn_windows() + self.state = 123 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,8,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + self.state = 117 + self.match(MetricAlertConditionParser.WHITESPACE) + self.state = 118 + self.dyn_since_seperator() + self.state = 119 + self.dyn_datetime() + self.state = 125 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,8,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_sensitivityContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(MetricAlertConditionParser.WORD, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_sensitivity + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_sensitivity" ): + listener.enterDyn_sensitivity(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_sensitivity" ): + listener.exitDyn_sensitivity(self) + + + + + def dyn_sensitivity(self): + + localctx = MetricAlertConditionParser.Dyn_sensitivityContext(self, self._ctx, self.state) + self.enterRule(localctx, 16, self.RULE_dyn_sensitivity) + try: + self.enterOuterAlt(localctx, 1) + self.state = 126 + self.match(MetricAlertConditionParser.WORD) + self.state = 127 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_violationsContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self): + return self.getToken(MetricAlertConditionParser.NUMBER, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_violations + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_violations" ): + listener.enterDyn_violations(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_violations" ): + listener.exitDyn_violations(self) + + + + + def dyn_violations(self): + + localctx = MetricAlertConditionParser.Dyn_violationsContext(self, self._ctx, self.state) + self.enterRule(localctx, 18, self.RULE_dyn_violations) + try: + self.enterOuterAlt(localctx, 1) + self.state = 129 + self.match(MetricAlertConditionParser.NUMBER) + self.state = 130 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_of_separatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def OF(self): + return self.getToken(MetricAlertConditionParser.OF, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_of_separator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_of_separator" ): + listener.enterDyn_of_separator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_of_separator" ): + listener.exitDyn_of_separator(self) + + + + + def dyn_of_separator(self): + + localctx = MetricAlertConditionParser.Dyn_of_separatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 20, self.RULE_dyn_of_separator) + try: + self.enterOuterAlt(localctx, 1) + self.state = 132 + self.match(MetricAlertConditionParser.OF) + self.state = 133 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_windowsContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self): + return self.getToken(MetricAlertConditionParser.NUMBER, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_windows + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_windows" ): + listener.enterDyn_windows(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_windows" ): + listener.exitDyn_windows(self) + + + + + def dyn_windows(self): + + localctx = MetricAlertConditionParser.Dyn_windowsContext(self, self._ctx, self.state) + self.enterRule(localctx, 22, self.RULE_dyn_windows) + try: + self.enterOuterAlt(localctx, 1) + self.state = 135 + self.match(MetricAlertConditionParser.NUMBER) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_since_seperatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def SINCE(self): + return self.getToken(MetricAlertConditionParser.SINCE, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_since_seperator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_since_seperator" ): + listener.enterDyn_since_seperator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_since_seperator" ): + listener.exitDyn_since_seperator(self) + + + + + def dyn_since_seperator(self): + + localctx = MetricAlertConditionParser.Dyn_since_seperatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 24, self.RULE_dyn_since_seperator) + try: + self.enterOuterAlt(localctx, 1) + self.state = 137 + self.match(MetricAlertConditionParser.SINCE) + self.state = 138 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dyn_datetimeContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.NUMBER) + else: + return self.getToken(MetricAlertConditionParser.NUMBER, i) + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WORD) + else: + return self.getToken(MetricAlertConditionParser.WORD, i) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dyn_datetime + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDyn_datetime" ): + listener.enterDyn_datetime(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDyn_datetime" ): + listener.exitDyn_datetime(self) + + + + + def dyn_datetime(self): + + localctx = MetricAlertConditionParser.Dyn_datetimeContext(self, self._ctx, self.state) + self.enterRule(localctx, 26, self.RULE_dyn_datetime) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 141 + self._errHandler.sync(self) + _la = self._input.LA(1) + while True: + self.state = 140 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1140854858) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 143 + self._errHandler.sync(self) + _la = self._input.LA(1) + if not (((_la) & ~0x3f) == 0 and ((1 << _la) & 1140854858) != 0): + break + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class WhereContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHERE(self): + return self.getToken(MetricAlertConditionParser.WHERE, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_where + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterWhere" ): + listener.enterWhere(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitWhere" ): + listener.exitWhere(self) + + + + + def where(self): + + localctx = MetricAlertConditionParser.WhereContext(self, self._ctx, self.state) + self.enterRule(localctx, 28, self.RULE_where) + try: + self.enterOuterAlt(localctx, 1) + self.state = 145 + self.match(MetricAlertConditionParser.WHERE) + self.state = 146 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DimensionsContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def where(self): + return self.getTypedRuleContext(MetricAlertConditionParser.WhereContext,0) + + + def dimension(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.DimensionContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.DimensionContext,i) + + + def dim_separator(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_separatorContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_separatorContext,i) + + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dimensions + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDimensions" ): + listener.enterDimensions(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDimensions" ): + listener.exitDimensions(self) + + + + + def dimensions(self): + + localctx = MetricAlertConditionParser.DimensionsContext(self, self._ctx, self.state) + self.enterRule(localctx, 30, self.RULE_dimensions) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 148 + self.where() + self.state = 149 + self.dimension() + self.state = 155 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==8 or _la==16: + self.state = 150 + self.dim_separator() + self.state = 151 + self.dimension() + self.state = 157 + self._errHandler.sync(self) + _la = self._input.LA(1) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class DimensionContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def dim_name(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_nameContext,0) + + + def dim_operator(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_operatorContext,0) + + + def dim_values(self): + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valuesContext,0) + + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dimension + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDimension" ): + listener.enterDimension(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDimension" ): + listener.exitDimension(self) + + + + + def dimension(self): + + localctx = MetricAlertConditionParser.DimensionContext(self, self._ctx, self.state) + self.enterRule(localctx, 32, self.RULE_dimension) + try: + self.enterOuterAlt(localctx, 1) + self.state = 158 + self.dim_name() + self.state = 159 + self.dim_operator() + self.state = 160 + self.dim_values() + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_separatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def AND(self): + return self.getToken(MetricAlertConditionParser.AND, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_separator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_separator" ): + listener.enterDim_separator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_separator" ): + listener.exitDim_separator(self) + + + + + def dim_separator(self): + + localctx = MetricAlertConditionParser.Dim_separatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 34, self.RULE_dim_separator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 162 + _la = self._input.LA(1) + if not(_la==8 or _la==16): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 163 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_operatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def INCLUDES(self): + return self.getToken(MetricAlertConditionParser.INCLUDES, 0) + + def EXCLUDES(self): + return self.getToken(MetricAlertConditionParser.EXCLUDES, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_operator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_operator" ): + listener.enterDim_operator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_operator" ): + listener.exitDim_operator(self) + + + + + def dim_operator(self): + + localctx = MetricAlertConditionParser.Dim_operatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 36, self.RULE_dim_operator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 165 + _la = self._input.LA(1) + if not(_la==17 or _la==18): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 166 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_val_separatorContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def OR(self): + return self.getToken(MetricAlertConditionParser.OR, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_val_separator + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_val_separator" ): + listener.enterDim_val_separator(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_val_separator" ): + listener.exitDim_val_separator(self) + + + + + def dim_val_separator(self): + + localctx = MetricAlertConditionParser.Dim_val_separatorContext(self, self._ctx, self.state) + self.enterRule(localctx, 38, self.RULE_dim_val_separator) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 168 + _la = self._input.LA(1) + if not(_la==8 or _la==19): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 169 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_nameContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WORD(self): + return self.getToken(MetricAlertConditionParser.WORD, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_name + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_name" ): + listener.enterDim_name(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_name" ): + listener.exitDim_name(self) + + + + + def dim_name(self): + + localctx = MetricAlertConditionParser.Dim_nameContext(self, self._ctx, self.state) + self.enterRule(localctx, 40, self.RULE_dim_name) + try: + self.enterOuterAlt(localctx, 1) + self.state = 171 + self.match(MetricAlertConditionParser.WORD) + self.state = 172 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_valuesContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def dim_value(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_valueContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_valueContext,i) + + + def dim_val_separator(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(MetricAlertConditionParser.Dim_val_separatorContext) + else: + return self.getTypedRuleContext(MetricAlertConditionParser.Dim_val_separatorContext,i) + + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_values + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_values" ): + listener.enterDim_values(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_values" ): + listener.exitDim_values(self) + + + + + def dim_values(self): + + localctx = MetricAlertConditionParser.Dim_valuesContext(self, self._ctx, self.state) + self.enterRule(localctx, 42, self.RULE_dim_values) + try: + self.enterOuterAlt(localctx, 1) + self.state = 174 + self.dim_value() + self.state = 180 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,11,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + self.state = 175 + self.dim_val_separator() + self.state = 176 + self.dim_value() + self.state = 182 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,11,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Dim_valueContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def NUMBER(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.NUMBER) + else: + return self.getToken(MetricAlertConditionParser.NUMBER, i) + + def WORD(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WORD) + else: + return self.getToken(MetricAlertConditionParser.WORD, i) + + def WHITESPACE(self, i:int=None): + if i is None: + return self.getTokens(MetricAlertConditionParser.WHITESPACE) + else: + return self.getToken(MetricAlertConditionParser.WHITESPACE, i) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_dim_value + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterDim_value" ): + listener.enterDim_value(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitDim_value" ): + listener.exitDim_value(self) + + + + + def dim_value(self): + + localctx = MetricAlertConditionParser.Dim_valueContext(self, self._ctx, self.state) + self.enterRule(localctx, 44, self.RULE_dim_value) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 184 + self._errHandler.sync(self) + _alt = 1 + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt == 1: + self.state = 183 + _la = self._input.LA(1) + if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1409311706) != 0): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + + else: + raise NoViableAltException(self) + self.state = 186 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,12,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class Options_Context(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def with_(self): + return self.getTypedRuleContext(MetricAlertConditionParser.With_Context,0) + + + def option(self): + return self.getTypedRuleContext(MetricAlertConditionParser.OptionContext,0) + + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_options_ + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterOptions_" ): + listener.enterOptions_(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitOptions_" ): + listener.exitOptions_(self) + + + + + def options_(self): + + localctx = MetricAlertConditionParser.Options_Context(self, self._ctx, self.state) + self.enterRule(localctx, 46, self.RULE_options_) + try: + self.enterOuterAlt(localctx, 1) + self.state = 188 + self.with_() + self.state = 189 + self.option() + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class With_Context(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def WITH(self): + return self.getToken(MetricAlertConditionParser.WITH, 0) + + def WHITESPACE(self): + return self.getToken(MetricAlertConditionParser.WHITESPACE, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_with_ + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterWith_" ): + listener.enterWith_(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitWith_" ): + listener.exitWith_(self) + + + + + def with_(self): + + localctx = MetricAlertConditionParser.With_Context(self, self._ctx, self.state) + self.enterRule(localctx, 48, self.RULE_with_) + try: + self.enterOuterAlt(localctx, 1) + self.state = 191 + self.match(MetricAlertConditionParser.WITH) + self.state = 192 + self.match(MetricAlertConditionParser.WHITESPACE) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + class OptionContext(ParserRuleContext): + __slots__ = 'parser' + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def SKIPMETRICVALIDATION(self): + return self.getToken(MetricAlertConditionParser.SKIPMETRICVALIDATION, 0) + + def getRuleIndex(self): + return MetricAlertConditionParser.RULE_option + + def enterRule(self, listener:ParseTreeListener): + if hasattr( listener, "enterOption" ): + listener.enterOption(self) + + def exitRule(self, listener:ParseTreeListener): + if hasattr( listener, "exitOption" ): + listener.exitOption(self) + + + + + def option(self): + + localctx = MetricAlertConditionParser.OptionContext(self, self._ctx, self.state) + self.enterRule(localctx, 50, self.RULE_option) + try: + self.enterOuterAlt(localctx, 1) + self.state = 194 + self.match(MetricAlertConditionParser.SKIPMETRICVALIDATION) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + + + diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionValidator.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionValidator.py new file mode 100644 index 00000000000..e324a6a509a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/MetricAlertConditionValidator.py @@ -0,0 +1,149 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from .MetricAlertConditionListener import MetricAlertConditionListener + + +op_conversion = { + '=': 'Equals', + '!=': 'NotEquals', + '>': 'GreaterThan', + '>=': 'GreaterThanOrEqual', + '<': 'LessThan', + '<=': 'LessThanOrEqual', + '><': 'GreaterOrLessThan' +} + +agg_conversion = { + 'avg': 'Average', + 'min': 'Minimum', + 'max': 'Maximum', + 'total': 'Total', + 'count': 'Count' +} + +sens_conversion = { + 'low': 'Low', + 'medium': 'Medium', + 'high': 'High', +} + +dim_op_conversion = { + 'includes': 'Include', + 'excludes': 'Exclude' +} + + +# This class defines a complete listener for a parse tree produced by MetricAlertConditionParser. +class MetricAlertConditionValidator(MetricAlertConditionListener): + + def __init__(self): + super().__init__() + self.parameters = {} + self._dimension_index = 0 + + # Exit a parse tree produced by MetricAlertConditionParser#aggregation. + def exitAggregation(self, ctx): + aggregation = agg_conversion[ctx.getText().strip()] + self.parameters['time_aggregation'] = aggregation + + # Exit a parse tree produced by MetricAlertConditionParser#namespace. + def exitNamespace(self, ctx): + self.parameters['metric_namespace'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#metric. + def exitMetric(self, ctx): + self.parameters['metric_name'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#operator. + def exitOperator(self, ctx): + self.parameters['operator'] = op_conversion[ctx.getText().strip()] + + # Exit a parse tree produced by MetricAlertConditionParser#threshold. + def exitThreshold(self, ctx): + self.parameters['threshold'] = float(ctx.getText().strip()) + + def exitDynamic(self, ctx): + self.parameters['failing_periods'] = {} + + def exitDyn_sensitivity(self, ctx): + sensitivity = sens_conversion[ctx.getText().strip().lower()] + self.parameters['alert_sensitivity'] = sensitivity + + def exitDyn_violations(self, ctx): + min_failing_periods_to_alert = float(ctx.getText().strip()) + if min_failing_periods_to_alert < 1 or min_failing_periods_to_alert > 6: + message = "Violations {} should be 1-6." + raise ValueError(message.format(min_failing_periods_to_alert)) + self.parameters['failing_periods']['min_failing_periods_to_alert'] = min_failing_periods_to_alert + + def exitDyn_windows(self, ctx): + number_of_evaluation_periods = float(ctx.getText().strip()) + min_failing_periods_to_alert = self.parameters['failing_periods']['min_failing_periods_to_alert'] + if number_of_evaluation_periods < 1 or number_of_evaluation_periods > 6: + message = "Windows {} should be 1-6." + raise ValueError(message.format(number_of_evaluation_periods)) + if min_failing_periods_to_alert > number_of_evaluation_periods: + message = "Violations {} should be smaller or equal to windows {}." + raise ValueError(message.format(min_failing_periods_to_alert, number_of_evaluation_periods)) + self.parameters['failing_periods']['number_of_evaluation_periods'] = number_of_evaluation_periods + + def exitDyn_datetime(self, ctx): + from msrest.serialization import Deserializer + from msrest.exceptions import DeserializationError + datetime_str = ctx.getText().strip() + try: + self.parameters['ignore_data_before'] = Deserializer.deserialize_iso(datetime_str) + except DeserializationError: + message = "Datetime {} is not a valid ISO-8601 format" + raise ValueError(message.format(datetime_str)) + + # Enter a parse tree produced by MetricAlertConditionParser#dimensions. + def enterDimensions(self, ctx): + self.parameters['dimensions'] = [] + + # Enter a parse tree produced by MetricAlertConditionParser#dimension. + def enterDimension(self, ctx): + self.parameters['dimensions'].append({}) + + # Exit a parse tree produced by MetricAlertConditionParser#dimension. + def exitDimension(self, ctx): + self._dimension_index = self._dimension_index + 1 + + # Exit a parse tree produced by MetricAlertConditionParser#dname. + def exitDim_name(self, ctx): + self.parameters['dimensions'][self._dimension_index]['name'] = ctx.getText().strip() + + # Exit a parse tree produced by MetricAlertConditionParser#dop. + def exitDim_operator(self, ctx): + op_text = ctx.getText().strip() + self.parameters['dimensions'][self._dimension_index]['operator'] = dim_op_conversion[op_text.lower()] + + # Exit a parse tree produced by MetricAlertConditionParser#dvalues. + def exitDim_values(self, ctx): + dvalues = ctx.getText().strip().split(' ') + self.parameters['dimensions'][self._dimension_index]['values'] = [x for x in dvalues if x not in ['', 'or']] + + # Exit a parse tree produced by MetricAlertConditionParser#option. + def exitOption(self, ctx): + if ctx.getText().strip().lower() == 'skipmetricvalidation': + self.parameters['skip_metric_validation'] = True + + def result(self): + dim_params = self.parameters.get('dimensions', []) + dimensions = [] + for dim in dim_params: + dimensions.append(dim) + self.parameters['dimensions'] = dimensions + self.parameters['name'] = '' # will be auto-populated later + + if 'failing_periods' in self.parameters: + # dynamic metric criteria + failing_periods = self.parameters['failing_periods'] + self.parameters['failing_periods'] = failing_periods + return {"dynamic": self.parameters} + + # static metric criteria + return {"static": self.parameters} diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/README.md b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/README.md new file mode 100644 index 00000000000..68fc4668d41 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/README.md @@ -0,0 +1,28 @@ +# Working with the ANTLR grammar in Azure CLI + +The ANTLR grammar is used to generate expression parsing for the `az monitor metrics alert create/update` commands. Due to the complexity, and introduction of other authoring features, it is *not* recommended that new commands follow this pattern. + +## SETUP + +To set up your system to be able to alter and regenerate the grammar code, see the QuickStart section on [the ANTLR website](https://www.antlr.org/). You will need to have the Java JDK (JRE is *not* sufficient) installed. + +The steps for Windows are replicated here: +``` +Download https://www.antlr.org/download/antlr-4.9.3-complete.jar. +Add antlr4-complete.jar to CLASSPATH, either: +Permanently: Using System Properties dialog > Environment variables > Create or append to CLASSPATH variable +Temporarily, at command line: +SET CLASSPATH=.;C:\Javalib\antlr-4.9.3-complete.jar;%CLASSPATH% +``` + +You will likely also need to add the path to your JDK bin directory to your PATH. + +## MAKING CHANGES + +1. Make updates to the `MetricAlertCondition.g4` grammar file. +2. Test your changes by entering a condition expression in a file called `test.txt` and running `run_test.bat`. This will open a GUI where you can visually see how your expression will be parsed--useful in identifying problems with your grammar. +3. Once you are happy with the grammar changes, run `build_python.bat` to update the generated Python classes. Add the license header to the three generated files. +4. Add a test to cover your new scenario. +5. Update the `MetricAlertConditionValidator.py` file until your test passes. +6. Clean up the unneeded Java files `del *.class *.java *.tokens *.interp test.txt` +7. Open a PR. License headers and pylint annotations will be removed during autogeneration, so you will need to reverse those lines. diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/__init__.py new file mode 100644 index 00000000000..47b76d0b0cf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/__init__.py @@ -0,0 +1,10 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=unused-import +from .MetricAlertConditionLexer import MetricAlertConditionLexer +from .MetricAlertConditionParser import MetricAlertConditionParser +from .MetricAlertConditionListener import MetricAlertConditionListener +from .MetricAlertConditionValidator import MetricAlertConditionValidator diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/antlr.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/antlr.bat new file mode 100644 index 00000000000..f372d21e618 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/antlr.bat @@ -0,0 +1 @@ +java org.antlr.v4.Tool %* diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/build_python.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/build_python.bat new file mode 100644 index 00000000000..f5ee69cdc77 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/build_python.bat @@ -0,0 +1,3 @@ +echo off +echo Building MetricAlertCondition +call antlr -Dlanguage=Python3 MetricAlertCondition.g4 diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/grun.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/grun.bat new file mode 100644 index 00000000000..de42a9366db --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/grun.bat @@ -0,0 +1,5 @@ +@ECHO OFF +SET TEST_CURRENT_DIR=%CLASSPATH:.;=% +if "%TEST_CURRENT_DIR%" == "%CLASSPATH%" ( SET CLASSPATH=.;%CLASSPATH% ) +@ECHO ON +java org.antlr.v4.gui.TestRig %* diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/run_test.bat b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/run_test.bat new file mode 100644 index 00000000000..3b0dfe244ae --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/grammar/metric_alert/run_test.bat @@ -0,0 +1,5 @@ +echo off +echo Testing MetricAlertCondition +call antlr MetricAlertCondition.g4 +call javac Metric*.java +call grun MetricAlertCondition expression test.txt -gui diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/linter_exclusions.yml b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/linter_exclusions.yml new file mode 100644 index 00000000000..b166ade8e85 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/linter_exclusions.yml @@ -0,0 +1,34 @@ +--- +monitor activity-log alert update: + parameters: + enabled: + rule_exclusions: + - missing_parameter_help +monitor alert update: + parameters: + enabled: + rule_exclusions: + - missing_parameter_help +monitor action-group create: + parameters: + automation_runbook_receivers: + rule_exclusions: + - option_length_too_long + azure_app_push_receivers: + rule_exclusions: + - option_length_too_long + azure_function_receivers: + rule_exclusions: + - option_length_too_long +monitor action-group update: + parameters: + automation_runbook_receivers: + rule_exclusions: + - option_length_too_long + azure_app_push_receivers: + rule_exclusions: + - option_length_too_long + azure_function_receivers: + rule_exclusions: + - option_length_too_long +... diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/action_groups.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/action_groups.py new file mode 100644 index 00000000000..7a28709a6fc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/action_groups.py @@ -0,0 +1,387 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=protected-access +from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg +from azure.cli.core.commands.validators import validate_tags +from azure.cli.core.azclierror import ValidationError +from azure.cli.command_modules.monitor._legacy.actions import AAZCustomListArg +from ..aaz.latest.monitor.action_group import Create as _ActionGroupCreate, Update as _ActionGroupUpdate +from ..aaz.latest.monitor.action_group.test_notifications import Create as _ActionGroupTestNotificationCreate + + +def update_action_group_receivers(args): + syntax = { + 'email': 'NAME EMAIL_ADDRESS [usecommonalertschema]', + 'sms': 'NAME COUNTRY_CODE PHONE_NUMBER', + 'webhook': 'NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]', + 'armrole': 'NAME ROLE_ID [usecommonalertschema]', + 'azureapppush': 'NAME EMAIL_ADDRESS', + 'itsm': 'NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIG REGION', + 'automationrunbook': 'NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID ' + 'SERVICE_URI [isglobalrunbook] [usecommonalertschema]', + 'voice': 'NAME COUNTRY_CODE PHONE_NUMBER', + 'logicapp': 'NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]', + 'azurefunction': 'NAME FUNCTION_APP_RESOURCE_ID ' + 'FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]', + 'eventhub': 'NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema] ' + } + + for receiver_item in args.receiver_actions: + receiver_item_arr = receiver_item.to_serialized_data() + type_name = receiver_item_arr[0] + type_properties = receiver_item_arr[1:] + useCommonAlertSchema = 'usecommonalertschema' in (t_property.lower() for t_property in type_properties) + try: + if type_name == 'email': + args.email_receivers.append({ + 'name': type_properties[0], + "email_address": type_properties[1], + "use_common_alert_schema": useCommonAlertSchema + }) + elif type_name == 'sms': + args.sms_receivers.append({ + "name": type_properties[0], + "country_code": type_properties[1], + "phone_number": type_properties[2] + }) + elif type_name == 'webhook': + useAadAuth = len(type_properties) >= 3 and type_properties[2] == 'useaadauth' + object_id = type_properties[3] if useAadAuth else None + identifier_uri = type_properties[4] if useAadAuth else None + args.webhook_receivers.append({ + "name": type_properties[0], + "service_uri": type_properties[1], + "use_common_alert_schema": useCommonAlertSchema, + "use_aad_auth": useAadAuth, + "object_id": object_id, + "identifier_uri": identifier_uri + }) + elif type_name == 'armrole': + args.arm_role_receivers.append({ + "name": type_properties[0], + "role_id": type_properties[1], + "use_common_alert_schema": useCommonAlertSchema + }) + elif type_name == 'azureapppush': + args.azure_app_push_receivers.append({ + "name": type_properties[0], + "email_address": type_properties[1] + }) + elif type_name == 'itsm': + args.itsm_receivers.append({ + "name": type_properties[0], + "workspace_id": type_properties[1], + "connection_id": type_properties[2], + "ticket_configuration": type_properties[3], + "region": type_properties[4] + }) + elif type_name == 'automationrunbook': + isGlobalRunbook = 'isglobalrunbook' in (t_property.lower() for t_property in type_properties) + args.automation_runbook_receivers.append({ + "name": type_properties[0], + "automation_account_id": type_properties[1], + "runbook_name": type_properties[2], + "webhook_resource_id": type_properties[3], + "service_uri": type_properties[4], + "is_global_runbook": isGlobalRunbook, + "use_common_alert_schema": useCommonAlertSchema + }) + elif type_name == 'voice': + args.voice_receivers.append({ + "name": type_properties[0], + "country_code": type_properties[1], + "phone_number": type_properties[2] + }) + elif type_name == 'logicapp': + args.logic_app_receivers.append({ + "name": type_properties[0], + "resource_id": type_properties[1], + "callback_url": type_properties[2], + "use_common_alert_schema": useCommonAlertSchema + }) + elif type_name == 'azurefunction': + args.azure_function_receivers.append({ + "name": type_properties[0], + "function_app_resource_id": type_properties[1], + "function_name": type_properties[2], + "http_trigger_url": type_properties[3], + "use_common_alert_schema": useCommonAlertSchema + }) + elif type_name == 'eventhub': + args.event_hub_receivers.append({ + "name": type_properties[0], + "subscription_id": type_properties[1], + "event_hub_name_space": type_properties[2], + "event_hub_name": type_properties[3], + "use_common_alert_schema": useCommonAlertSchema + }) + else: + raise ValidationError('The type "{}" is not recognizable.'.format(type_name)) + + except IndexError: + raise ValidationError('--action {}'.format(syntax[type_name])) + + +class ActionGroupCreate(_ActionGroupCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.receiver_actions = AAZCustomListArg( + options=["--actions"], + singular_options=["--action", "-a"], + help=''' + Add receivers to the action group during the creation.\n\n + Usage: --action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --action webhook alert_hook https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well. + ''', + arg_group="Actions", + ) + args_schema.receiver_actions.Element = AAZCustomListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.enabled = True + validate_tags(args) + action_group_name = args.action_group_name.to_serialized_data() + if not has_value(args.location): + # both inputed or 'global' location are available for action group + args.location = "Global" + if not has_value(args.group_short_name): + # '12' is the short name length limitation + args.group_short_name = action_group_name[:12] + if not has_value(args.receiver_actions): + return + update_action_group_receivers(args) + + +class ActionGroupUpdate(_ActionGroupUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.receiver_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action", "-a"], + help=''' + Add receivers to the action group.\n\n + Usage: --add-action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --add-action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --add-action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', + arg_group="Actions", + ) + args_schema.receiver_actions.Element = AAZListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + + args_schema.receiver_remove_list = AAZListArg( + options=["--remove-action", "-r"], + help="Remove receivers from the action group. Accept space-separated list of receiver names.", + arg_group="Actions", + ) + args_schema.receiver_remove_list.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.enabled = True + update_action_group_receivers(args) + + def pre_instance_update(self, instance): + args = self.ctx.args + receiver_remove_list = set() + if has_value(args.receiver_remove_list): + receiver_remove_list = set(args.receiver_remove_list.to_serialized_data()) + + def filter_receivers(collection): + return [item for item in collection if item.name.to_serialized_data() not in receiver_remove_list] + + instance.properties.incident_receivers = filter_receivers(instance.properties.incident_receivers) + instance.properties.incident_receivers.extend(args.incident_receivers) + args.incident_receivers = instance.properties.incident_receivers + + instance.properties.email_receivers = filter_receivers(instance.properties.email_receivers) + instance.properties.email_receivers.extend(args.email_receivers) + args.email_receivers = instance.properties.email_receivers + + instance.properties.sms_receivers = filter_receivers(instance.properties.sms_receivers) + instance.properties.sms_receivers.extend(args.sms_receivers) + args.sms_receivers = instance.properties.sms_receivers + + instance.properties.webhook_receivers = filter_receivers(instance.properties.webhook_receivers) + instance.properties.webhook_receivers.extend(args.webhook_receivers) + args.webhook_receivers = instance.properties.webhook_receivers + + instance.properties.arm_role_receivers = filter_receivers(instance.properties.arm_role_receivers) + instance.properties.arm_role_receivers.extend(args.arm_role_receivers) + args.arm_role_receivers = instance.properties.arm_role_receivers + + instance.properties.azure_app_push_receivers = filter_receivers(instance.properties.azure_app_push_receivers) + instance.properties.azure_app_push_receivers.extend(args.azure_app_push_receivers) + args.azure_app_push_receivers = instance.properties.azure_app_push_receivers + + instance.properties.itsm_receivers = filter_receivers(instance.properties.itsm_receivers) + instance.properties.itsm_receivers.extend(args.itsm_receivers) + args.itsm_receivers = instance.properties.itsm_receivers + + instance.properties.automation_runbook_receivers = \ + filter_receivers(instance.properties.automation_runbook_receivers) + instance.properties.automation_runbook_receivers.extend(args.automation_runbook_receivers) + args.automation_runbook_receivers = instance.properties.automation_runbook_receivers + + instance.properties.voice_receivers = filter_receivers(instance.properties.voice_receivers) + instance.properties.voice_receivers.extend(args.voice_receivers) + args.voice_receivers = instance.properties.voice_receivers + + instance.properties.logic_app_receivers = filter_receivers(instance.properties.logic_app_receivers) + instance.properties.logic_app_receivers.extend(args.logic_app_receivers) + args.logic_app_receivers = instance.properties.logic_app_receivers + + instance.properties.azure_function_receivers = filter_receivers(instance.properties.azure_function_receivers) + instance.properties.azure_function_receivers.extend(args.azure_function_receivers) + args.azure_function_receivers = instance.properties.azure_function_receivers + + instance.properties.event_hub_receivers = filter_receivers(instance.properties.event_hub_receivers) + instance.properties.event_hub_receivers.extend(args.event_hub_receivers) + args.event_hub_receivers = instance.properties.event_hub_receivers + + +class ActionGroupTestNotificationCreate(_ActionGroupTestNotificationCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.arm_role_receivers._registered = False + args_schema.automation_runbook_receivers._registered = False + args_schema.azure_app_push_receivers._registered = False + args_schema.azure_function_receivers._registered = False + args_schema.email_receivers._registered = False + + args_schema.event_hub_receivers._registered = False + args_schema.itsm_receivers._registered = False + args_schema.logic_app_receivers._registered = False + args_schema.sms_receivers._registered = False + args_schema.voice_receivers._registered = False + args_schema.webhook_receivers._registered = False + args_schema.receiver_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action", "-a"], + help=''' + Add receivers to the action group.\n\n + Usage: --add-action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --add-action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --add-action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', + ) + args_schema.receiver_actions.Element = AAZListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + update_action_group_receivers(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups_identity.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/action_groups_identity.py similarity index 100% rename from src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups_identity.py rename to src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/action_groups_identity.py diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/activity_log_alerts.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/activity_log_alerts.py new file mode 100644 index 00000000000..3e2b5a71509 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/activity_log_alerts.py @@ -0,0 +1,492 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=protected-access, line-too-long +from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg, AAZBoolArg, register_command, \ + AAZResourceIdArg, AAZResourceIdArgFormat +from azure.cli.command_modules.monitor._legacy.actions import AAZCustomListArg +from azure.cli.core.azclierror import ValidationError +from ..aaz.latest.monitor.activity_log.alert import Create as _ActivityLogAlertCreate, \ + Update as _ActivityLogAlertUpdate + + +def _get_alert_settings_for_alert(cmd, resource_group_name, activity_log_alert_name, throw_if_missing=True): + from azure.core.exceptions import HttpResponseError + from ..aaz.latest.monitor.activity_log.alert import Show as ActivityLogAlertGet + try: + return ActivityLogAlertGet(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "activity_log_alert_name": activity_log_alert_name + }) + except HttpResponseError as ex: + if ex.status_code == 404: + if throw_if_missing: + raise ValidationError('Can\'t find activity log alert {} in resource group {}.'.format( + activity_log_alert_name, resource_group_name)) + return None + raise ValidationError(ex.message) + + +# pylint: disable=inconsistent-return-statements +def _normalize_condition_for_alert(condition_instance): + if isinstance(condition_instance, str): + try: + field, value = condition_instance.split('=') + condition = { + "field": field, + "equals": value, + } + return '{}={}'.format(field.lower(), value), condition + except ValueError: + # too many values to unpack or not enough values to unpack + raise ValueError('Condition "{}" does not follow format FIELD=VALUE'.format(condition_instance)) + + +def process_condition_parameter_for_alert(args): + if not has_value(args.condition): + return + expression = args.condition.to_serialized_data() + error = 'incorrect usage: --condition requires an expression in the form of FIELD=VALUE[ and FIELD=VALUE...]' + + if len(expression) == 1: + expression = [each.strip() for each in expression[0].split(' ')] + elif isinstance(expression, list): + expression = [each.strip() for each in expression] + else: + raise ValidationError(error) + + if len(expression) == 0 or not len(expression) % 2: + raise ValidationError(error) + + # This is a temporary approach built on the assumption that there is only AND operators. Eventually, a proper + # YACC will be created to parse complex condition expression. + + # Ensure all the string at even options are AND operator + operators = [expression[i] for i in range(1, len(expression), 2)] + if any(op != 'and' for op in operators): + raise ValidationError(error) + + # Pick the strings at odd position and convert them into condition leaf. + conditions = dict(_normalize_condition_for_alert(expression[i]) for i in range(0, len(expression), 2)) + for cond in list(conditions.values()): + args.all_of.append(cond) + + +def process_webhook_properties(args): + result = {} + if not has_value(args.webhook_properties_list): + return result + for each in args.webhook_properties_list: + + if has_value(each): + if '=' in each.to_serialized_data(): + key, value = each.to_serialized_data().split('=', 1) + else: + key, value = each, '' + result[key] = value + return result + + +class ActivityLogAlertCreate(_ActivityLogAlertCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.location._registered = False + args_schema.action_groups._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + help="A list of strings that will be used as prefixes." + ''' + The alert rule will only apply to activity logs with resourceIDs that fall under one of + these prefixes. If not provided, the subscriptionId will be used. + ''', + ) + args_schema.scope_ui.Element = AAZStrArg() + + args_schema.disable = AAZBoolArg( + options=["--disable"], + help="Disable the activity log alert rule after it is created.", + default=False, + ) + args_schema.condition = AAZCustomListArg( + options=["--condition", "-c"], + help="The condition that will cause the alert rule to activate. " + "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' + The possible values for the field are 'resourceId', 'category', 'caller', + 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', + 'subStatus', 'resourceType', or anything beginning with 'properties'. + ''' + ) + args_schema.condition.Element = AAZStrArg() + + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + help="Add an action group. Accepts space-separated action group identifiers. " + "The identifier can be the action group's name or its resource ID.", + ) + args_schema.action_group_ids.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", + ) + ) + + args_schema.webhook_properties_list = AAZCustomListArg( + options=['--webhook-properties', '-w'], + help="Space-separated webhook properties in 'key[=value]' format. " + "These properties are associated with the action groups added in this command." + ''' + For any webhook receiver in these action group, this data is appended to the webhook + payload. To attach different webhook properties to different action groups, add the + action groups in separate update-action commands. + ''' + ) + args_schema.webhook_properties_list.Element = AAZStrArg() + + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.location = "Global" + process_condition_parameter_for_alert(args) + webhook_properties = process_webhook_properties(args) + if not has_value(args.scope_ui): + from azure.mgmt.core.tools import resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + # args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx), + # resource_group=args.resource_group)] + # service check + args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx))] + else: + args.scopes = args.scope_ui.to_serialized_data() + if _get_alert_settings_for_alert(self, args.resource_group, args.activity_log_alert_name, + throw_if_missing=False): + raise ValidationError( + 'The activity log alert {} already exists in resource group {}.'.format(args.activity_log_alert_name, + args.resource_group)) + if not has_value(args.all_of): + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + else: + current_all_of = args.all_of.to_serialized_data() + category_found = False + for item in current_all_of: + if item.get("field", None) == "category": + category_found = True + break + if not category_found: + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + # Add action groups + action_group_rids = set() + if has_value(args.action_group_ids): + action_group_rids = set(args.action_group_ids.to_serialized_data()) + args.action_groups = [] + for i in action_group_rids: + args.action_groups.append({ + "action_group_id": i, + "webhook_properties": webhook_properties + }) + if has_value(args.disable): + args.enabled = not args.disable + + +class ActivityLogAlertUpdate(_ActivityLogAlertUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.scopes._registered = False + args_schema.condition = AAZCustomListArg( + options=["--condition", "-c"], + help="The condition that will cause the alert rule to activate. " + "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' + The possible values for the field are 'resourceId', 'category', 'caller', + 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', + 'subStatus', 'resourceType', or anything beginning with 'properties'. + ''' + ) + args_schema.condition.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + process_condition_parameter_for_alert(args) + if not has_value(args.all_of): + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + else: + current_all_of = args.all_of.to_serialized_data() + category_found = False + for item in current_all_of: + if item.get("field", None) == "category": + category_found = True + break + if not category_found: + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + + +@register_command("monitor activity-log alert action-group add") +class ActivityLogAlertActionGroupAdd(_ActivityLogAlertUpdate): + """Add action groups to this activity log alert rule. It can also be used to overwrite existing webhook properties of particular action groups. + + :example: Add an action group and specify webhook properties. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + --action /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insight + s/actionGroups/{ActionGroup} \\ + --webhook-properties usage=test owner=jane + + :example: Overwite an existing action group's webhook properties. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti + onGroups/{ActionGroup} \\ + --webhook-properties usage=test owner=john + + :example: Remove webhook properties from an existing action group. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti + onGroups/{ActionGroup} + + :example: Add new action groups but prevent the command from accidently overwrite existing webhook properties + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup --strict \\ + --action-group ResourceIDList + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.all_of._registered = False + args_schema.description._registered = False + args_schema.enabled._registered = False + args_schema.scopes._registered = False + args_schema.tags._registered = False + + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + help="The names or the resource ids of the action groups to be added.", + required=True + ) + args_schema.action_group_ids.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", + ) + ) + + args_schema.webhook_properties_list = AAZCustomListArg( + options=['--webhook-properties', '-w'], + help="Space-separated webhook properties in 'key[=value]' format. " + "These properties are associated with the action groups added in this command." + ''' + For any webhook receiver in these action group, these data are appended to the webhook + payload. To attach different webhook properties to different action groups, add the + action groups in separate update-action commands. + ''' + ) + args_schema.webhook_properties_list.Element = AAZStrArg() + + args_schema.reset = AAZBoolArg( + options=["--reset"], + help="Remove all the existing action groups before add new conditions.", + default=False + ) + args_schema.strict = AAZBoolArg( + options=["--strict"], + help="Fails the command if an action group to be added will change existing webhook properties.", + default=False, + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + webhook_properties = process_webhook_properties(args) + + rids = args.action_group_ids.to_serialized_data() + + if has_value(args.reset) and args.reset: + action_groups = [] + for rid in rids: + action_groups.append({ + "action_group_id": rid, + "webhook_properties": webhook_properties + }) + instance.properties.actions.action_groups = action_groups + else: + action_groups_map = {} + for item in instance.properties.actions.action_groups: + ac_id = item.actionGroupId.to_serialized_data() + # service returned action group id can be uppercase + action_groups_map[ac_id.lower()] = { + "action_group_id": ac_id, + "webhook_properties": dict(item.webhookProperties) + } + + for rid in rids: + if args.strict: + for key, item in action_groups_map.items(): + if key.lower() == rid.lower() and webhook_properties != item["webhook_properties"]: + raise ValueError( + 'Fails to override webhook properties of action group {} in strict mode.'.format(rid)) + + action_groups_map[rid.lower()] = { + "action_group_id": rid, + "webhook_properties": webhook_properties + } + + action_groups = list(action_groups_map.values()) + instance.properties.actions.action_groups = action_groups + + +@register_command("monitor activity-log alert action-group remove") +class ActivityLogAlertActionGroupRemove(_ActivityLogAlertUpdate): + """Remove action groups from this activity log alert rule. + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.all_of._registered = False + args_schema.description._registered = False + args_schema.enabled._registered = False + args_schema.scopes._registered = False + args_schema.tags._registered = False + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + required=True, + help="The names or the resource ids of the action groups to be added.", + ) + args_schema.action_group_ids.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + action_group_ids = args.action_group_ids.to_serialized_data() + if len(action_group_ids) == 1 and action_group_ids[0] == '*': + instance.properties.actions.actionGroups = [] + else: + # normalize the action group ids + rids = _normalize_names(self.cli_ctx, args.action_group_ids.to_serialized_data(), args.resource_group, + 'microsoft.insights', 'actionGroups') + action_groups = [] + for item in instance.properties.actions.actionGroups: + ac_id = item.actionGroupId.to_serialized_data() + found = False + for rid in rids: + if ac_id.lower() == rid.lower(): # service returned action group id can be uppercase + found = True + break + if not found: + action_groups.append(item) + instance.properties.actions.actionGroups = action_groups + + +@register_command("monitor activity-log alert scope add") +class ActivityLogAlertScopeAdd(_ActivityLogAlertUpdate): + """Add scopes to this activity log alert rule. + + :example: Add scopes to this activity log alert rule. + az monitor activity-log alert scope add --name MyActivityLogAlerts --resource-group + MyResourceGroup --scope /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myRG + /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx- + xxxxxxxxxxxx/resourceGroups/myRG/Microsoft.KeyVault/vaults/mykey + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.all_of._registered = False + args_schema.action_groups._registered = False + args_schema.tags._registered = False + args_schema.description._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + required=True, + help="List of scopes to add. Each scope could be a resource ID or a subscription ID.", + ) + args_schema.scope_ui.Element = AAZStrArg() + + args_schema.reset = AAZBoolArg( + options=["--reset"], + help="Remove all the existing action groups before add new conditions.", + default=False + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + new_scopes = set() if args.reset else set(instance.properties.scopes.to_serialized_data()) + for scope in args.scope_ui.to_serialized_data(): + new_scopes.add(scope) + + args.scopes = list(new_scopes) + + +@register_command("monitor activity-log alert scope remove") +class ActivityLogAlertScopeRemove(_ActivityLogAlertUpdate): + """Removes scopes from this activity log alert rule. + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.all_of._registered = False + args_schema.action_groups._registered = False + args_schema.tags._registered = False + args_schema.description._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + required=True, + help="The scopes to remove.", + ) + args_schema.scope_ui.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + new_scopes = set(instance.properties.scopes.to_serialized_data()) + for scope in args.scope_ui.to_serialized_data(): + try: + new_scopes.remove(scope) + except KeyError: + pass + args.scopes = list(new_scopes) + + +def _normalize_names(cli_ctx, resource_names, resource_group, namespace, resource_type): + """Normalize a group of resource names. Returns a set of resource ids. Throws if any of the name can't be correctly + converted to a resource id.""" + from azure.mgmt.core.tools import is_valid_resource_id, resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + + rids = set() + # normalize the action group ids + for name in resource_names: + if is_valid_resource_id(name): + rids.add(name) + else: + rid = resource_id(subscription=get_subscription_id(cli_ctx), + resource_group=resource_group, + namespace=namespace, + type=resource_type, + name=name) + if not is_valid_resource_id(rid): + raise ValueError('The resource name {} is not valid.'.format(name)) + rids.add(rid) + + return rids diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale-parameters-template.json b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale-parameters-template.json new file mode 100644 index 00000000000..7de8a5dcb33 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale-parameters-template.json @@ -0,0 +1,38 @@ +{ + "autoscale_setting_resource_name": "{MyAutoscaleSettings}", + "location": "West US", + "tags": {}, + "profiles": [ + { + "name": "{AutoscaleProfile}", + "capacity": { + "minimum": "1", + "maximum": "5", + "default": "3" + }, + "rules": [ + { + "metric_trigger": { + "metric_name": "{name}", + "metric_resource_uri": "{FullyQualifiedAzureResourceID}", + "time_grain": "(duration in ISO8601 format)PT5M", + "statistic": "{Average|Min|Max|Sum}", + "time_window": "(duration in ISO8601 format)PT45M", + "time_aggregation": "{Average|Minimum|Maximum|Total|Count}", + "operator": "{Equals|NotEquals|GreaterThan|GreaterThanOrEqual|LessThan|LessThanOrEquals}", + "threshold": 100 + }, + "scale_action": { + "direction": "{None|Increase|Decrease}", + "type": "{ChangeCount|PercentChangeCount|ExactCount}", + "value": "2 (number of instances that are involved in the scaling)", + "cooldown": "(duration in ISO8601 format)PT20M" + } + } + ] + } + ], + "notifications": [], + "enabled": false, + "target_resource_uri": "{FullyQualifiedAzureResourceID}" +} diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale_settings.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale_settings.py new file mode 100644 index 00000000000..2e0c6344830 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/autoscale_settings.py @@ -0,0 +1,704 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=line-too-long, protected-access +import json +from knack.log import get_logger +from knack.util import CLIError +from azure.cli.core.aaz import has_value, AAZListArg, AAZStrArg, AAZIntArg, AAZBoolArg +from azure.cli.command_modules.monitor._legacy.actions import AAZCustomListArg +from azure.cli.command_modules.monitor._legacy._autoscale_util import get_autoscale_default_profile +from ..aaz.latest.monitor.autoscale import Create as _AutoScaleCreate, Update as _AutoScaleUpdate, \ + Show as _AutoScaleShow, List as _AutoScaleList +from azure.cli.command_modules.network.custom import _convert_to_snake_case +from azure.cli.core.azclierror import InvalidArgumentValueError + +logger = get_logger(__name__) + + +DEFAULT_PROFILE_NAME = 'default' + + +class AutoScaleCreate(_AutoScaleCreate): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + +class AutoScaleShow(_AutoScaleShow): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + +def update_add_actions(args): + add_actions = [] + for add_action_item in args.add_actions: + add_action_item_arr = add_action_item.to_serialized_data() + _type = add_action_item_arr[0].lower() + if _type == "email": + add_actions.append({ + "key": "email", + "value": { + "customEmails": add_action_item_arr[1:] + } + }) + elif _type == "webhook": + uri = add_action_item_arr[1] + try: + properties = dict(x.split('=', 1) for x in add_action_item_arr[2:]) + except ValueError: + raise InvalidArgumentValueError('webhook URI [KEY=VALUE ...]') + add_actions.append({ + "key": "webhook", + "value": { + "serviceUri": uri, + "properties": properties + } + }) + else: + raise InvalidArgumentValueError('TYPE KEY [ARGS]') + return add_actions + + +def update_remove_actions(args): + remove_actions = [] + for remove_action_item in args.remove_actions: + values = remove_action_item.to_serialized_data() + _type = values[0].lower() + if _type not in ['email', 'webhook']: + raise InvalidArgumentValueError('TYPE KEY [KEY ...]') + remove_actions.append(values[1:]) + return remove_actions + + +class AutoScaleUpdate(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.notifications._registered = False + args_schema.profiles._registered = False + args_schema.target_resource_location._registered = False + args_schema.target_resource_uri._registered = False + args_schema.count = AAZIntArg( + options=["--count"], + help='The numer of instances to use. If used with --min/max-count, the default number of instances to use.', + arg_group="Instance Limit", + ) + args_schema.min_count = AAZIntArg( + options=["--min-count"], + help='The minimum number of instances.', + arg_group="Instance Limit", + ) + args_schema.max_count = AAZIntArg( + options=["--max-count"], + help='The maximum number of instances.', + arg_group="Instance Limit", + ) + args_schema.add_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=['--add-action', '-a'], + help="Add an action to fire when a scaling event occurs." + ''' + Usage: --add-action TYPE KEY [ARG ...] + Email: --add-action email bob@contoso.com ann@contoso.com + Webhook: --add-action webhook https://www.contoso.com/alert apiKey=value + Webhook: --add-action webhook https://www.contoso.com/alert?apiKey=value + Multiple actions can be specified by using more than one `--add-action` argument. + ''', + arg_group="Notification", + ) + args_schema.add_actions.Element = AAZCustomListArg() + args_schema.add_actions.Element.Element = AAZStrArg() + + args_schema.remove_actions = AAZCustomListArg( + options=["--remove-actions"], + singular_options=['--remove-action', '-r'], + help="Remove one or more actions." + ''' + Usage: --remove-action TYPE KEY [KEY ...] + Email: --remove-action email bob@contoso.com ann@contoso.com + Webhook: --remove-action webhook https://contoso.com/alert https://alerts.contoso.com. + ''', + arg_group="Notification", + ) + args_schema.remove_actions.Element = AAZCustomListArg() + args_schema.remove_actions.Element.Element = AAZStrArg() + + args_schema.email_administrator = AAZBoolArg( + options=["--email-administrator"], + help='Send email to subscription administrator on scaling.', + arg_group="Notification", + ) + args_schema.email_coadministrators = AAZBoolArg( + options=["--email-coadministrators"], + help='Send email to subscription co-administrators on scaling.', + arg_group="Notification", + ) + + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + add_actions = update_add_actions(args) + remove_actions = update_remove_actions(args) + if has_value(args.count) or has_value(args.min_count) or has_value(args.max_count): + default_profile = get_autoscale_default_profile(instance) + curr_count = default_profile["capacity"]["default"] + curr_min = default_profile["capacity"]["minimum"] + curr_max = default_profile["capacity"]["maximum"] + is_fixed_count = curr_count == curr_min and curr_count == curr_max + + # check for special case where count is used to indicate fixed value and only + # count is updated + if has_value(args.count) and is_fixed_count and not has_value(args.min_count) and not has_value(args.max_count): + args.min_count = args.count.to_serialized_data() + args.max_count = args.count.to_serialized_data() + + count = curr_count if not has_value(args.count) else args.count.to_serialized_data() + min_count = curr_min if not has_value(args.min_count) else args.min_count.to_serialized_data() + max_count = curr_max if not has_value(args.max_count) else args.max_count.to_serialized_data() + + # There may be multiple "default" profiles. All need to updated. + for profile in instance.properties.profiles: + if has_value(profile.fixed_date): + continue + if has_value(profile.recurrence): + try: + # portal denotes the "default" pairs by using a JSON string for their name + # so if it can be decoded, we know this is a default profile + json.loads(profile.name.to_serialized_data()) + except ValueError: + continue + profile.capacity.default = str(count) + profile.capacity.minimum = str(min_count) + profile.capacity.maximum = str(max_count) + updated_notification = None + if instance.properties.notifications: + retained_notification = [] + for x in instance.properties.notifications: + note = x.to_serialized_data() + if note['operation'].lower() == 'scale': + updated_notification = note + else: + retained_notification.append(note) + instance.properties.notifications = retained_notification + else: + instance.properties.notifications = [] + + if updated_notification is None: + updated_notification = { + "operation": "scale", + "email": { + "customEmails": [] + }, + "webhooks": [] + } + + # process removals + if len(remove_actions) > 0: + removed_emails, removed_webhooks = _parse_action_removals(remove_actions) + updated_notification['email']['customEmails'] = \ + [x for x in updated_notification['email']['customEmails'] if x not in removed_emails] + updated_notification['webhooks'] = \ + [x for x in updated_notification['webhooks'] if x['serviceUri'] not in removed_webhooks] + + # process additions + for action in add_actions: + if action["key"] == "email": + for email in action["value"]["customEmails"]: + updated_notification['email']['customEmails'].append(email) + elif action["key"] == "webhook": + updated_notification['webhooks'].append(action["value"]) + if has_value(args.email_administrator): + updated_notification['email']['sendToSubscriptionAdministrator'] = args.email_administrator.to_serialized_data() + if has_value(args.email_coadministrators): + updated_notification['email']['sendToSubscriptionCoAdministrators'] = args.email_coadministrators.to_serialized_data() + + instance.properties.notifications.append(updated_notification) + + if has_value(args.scale_look_ahead_time) and not has_value(args.scale_mode) \ + and not has_value(instance.properties.predictive_autoscale_policy): + raise InvalidArgumentValueError('scale-mode is required for setting scale-look-ahead-time.') + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + +class AutoScaleList(_AutoScaleList): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + for value in self.ctx.vars.instance.value: + if has_value(value.properties): + value.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link + + +# pylint: disable=too-many-locals +def autoscale_create(cmd, 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, + scale_mode=None, scale_look_ahead_time=None): + + if not autoscale_name: + from azure.mgmt.core.tools import parse_resource_id + autoscale_name = parse_resource_id(resource)['name'] + min_count = min_count or count + max_count = max_count or count + args = {} + default_profile = { + "name": DEFAULT_PROFILE_NAME, + "capacity": { + "default": str(count), + "minimum": str(min_count), + "maximum": str(max_count) + }, + "rules": [] + } + + notification = { + "operation": "scale", + "email": { + "custom_emails": [], + "send_to_subscription_administrator": email_administrator, + "send_to_subscription_co_administrators": email_coadministrators, + }, + "webhooks": [] + } + + for action in actions or []: + key = action["key"] + value = action["value"] + if key == "email": + for email in value["custom_emails"]: + notification["email"]["custom_emails"].append(email) + elif key == "webhook": + notification["webhooks"].append(value) + + if scale_mode is not None and scale_look_ahead_time is not None: + args["scale_mode"] = scale_mode + args["scale_look_ahead_time"] = scale_look_ahead_time + elif scale_mode is not None: + args["scale_mode"] = scale_mode + elif scale_look_ahead_time is not None: + raise InvalidArgumentValueError('scale-mode is required for setting predictive autoscale policy.') + args["location"] = location + args["profiles"] = [default_profile] + args["tags"] = tags + args["notifications"] = [notification] + args["enabled"] = not disabled + args["autoscale_name"] = autoscale_name + args["target_resource_uri"] = resource + args["resource_group"] = resource_group_name + + if not (min_count == count and max_count == count): + logger.warning('Follow up with `az monitor autoscale rule create` to add scaling rules.') + return AutoScaleCreate(cli_ctx=cmd.cli_ctx)(command_args=args) + + +def _parse_action_removals(actions): + """ Separates the combined list of keys to remove into webhooks and emails. """ + flattened = list({x for sublist in actions for x in sublist}) + emails = [] + webhooks = [] + for item in flattened: + if item.startswith('http://') or item.startswith('https://'): + webhooks.append(item) + else: + emails.append(item) + return emails, webhooks + + +def _apply_copy_rules(autoscale_settings, new_profile, copy_rules): + if copy_rules: + copy_profile = next(x for x in autoscale_settings["profiles"] if x["name"] == copy_rules) + if copy_profile: + new_profile["rules"] = copy_profile["rules"] + + +def _create_fixed_profile(autoscale_settings, profile_name, start, end, capacity, copy_rules=None, timezone=None): + if not (start and end): + raise CLIError('usage error: fixed schedule: --start DATETIME --end DATETIME') + profile = { + "name": profile_name, + "capacity": capacity, + "rules": [], + "fixed_date": { + "start": start + "+00:00", # use UTC for AAZDateTimeArg timezone + "end": end + "+00:00", # use UTC for AAZDateTimeArg timezone + "time_zone": timezone + } + } + _apply_copy_rules(autoscale_settings, profile, copy_rules) + autoscale_settings["profiles"].append(profile) + + +# pylint: disable=unused-argument +def _create_recurring_profile(autoscale_settings, profile_name, start, end, recurrence, capacity, + copy_rules=None, timezone=None): + from azure.cli.command_modules.monitor._legacy._autoscale_util import build_autoscale_profile_dict, \ + validate_autoscale_profile_dict + import dateutil + from datetime import time + + def _build_recurrence(base, time): + recur = { + "frequency": base["frequency"], + "schedule": { + "time_zone": base["schedule"]["time_zone"], + "days": base["schedule"]["days"], + "hours": [time.hour], + "minutes": [time.minute] + } + } + return recur + + start_time = dateutil.parser.parse(start).time() if start else time(hour=0, minute=0) + end_time = dateutil.parser.parse(end).time() if end else time(hour=23, minute=59) + + default_profile, autoscale_profile = build_autoscale_profile_dict(autoscale_settings) + validate_autoscale_profile_dict(autoscale_profile, start_time, end_time, recurrence) + start_profile = { + "name": profile_name, + "capacity": capacity, + "rules": [], + "recurrence": _build_recurrence(recurrence, start_time) + } + + _apply_copy_rules(autoscale_settings, start_profile, copy_rules) + end_profile = { + "name": json.dumps({'name': default_profile["name"], 'for': profile_name}), + "capacity": default_profile["capacity"], + "rules": default_profile["rules"], + "recurrence": _build_recurrence(recurrence, end_time) + } + autoscale_settings["profiles"].append(start_profile) + autoscale_settings["profiles"].append(end_profile) + + +def get_autoscale_instance(cmd, resource_group_name, autoscale_name): + rets = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "autoscale_name": autoscale_name + }) + + rets = _convert_to_snake_case(rets) + autoscale_settings = { + "resource_group": resource_group_name, + "autoscale_name": autoscale_name, + "enabled": rets.get("enabled", False), + "tags": rets.get("tags", None), + "target_resource_location": rets.get("target_resource_location", None), + "target_resource_uri": rets.get("target_resource_uri", None) + } + scale_policy = rets.get("predictive_autoscale_policy", None) + if scale_policy: + autoscale_settings["scale_look_ahead_time"] = scale_policy.get("scale_look_ahead_time", None) + autoscale_settings["scale_mode"] = scale_policy.get("scale_mode", None) + if rets.get("notifications", None): + autoscale_settings["notifications"] = rets["notifications"] + if rets.get("profiles", None): + autoscale_settings["profiles"] = rets["profiles"] + return autoscale_settings + + +def autoscale_profile_create(cmd, autoscale_name, resource_group_name, profile_name, + count, timezone, start=None, end=None, copy_rules=None, min_count=None, + max_count=None, recurrence=None): + autoscale_settings = get_autoscale_instance(cmd, resource_group_name, autoscale_name) + capacity = { + "default": str(count), + "minimum": str(min_count) if min_count else str(count), + "maximum": str(max_count) if max_count else str(count) + } + if recurrence: + _create_recurring_profile(autoscale_settings, profile_name, start, end, recurrence, capacity, copy_rules, + timezone) + else: + _create_fixed_profile(autoscale_settings, profile_name, start, end, capacity, copy_rules, timezone) + updated_rets = AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) + profile = next(x for x in updated_rets["profiles"] if x["name"] == profile_name) + return profile + + +def autoscale_profile_list(cmd, autoscale_name, resource_group_name): + autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "autoscale_name": autoscale_name}) + return autoscale_settings["profiles"] + + +def autoscale_profile_list_timezones(cmd, client, offset=None, search_query=None): + from azure.cli.command_modules.monitor._legacy._autoscale_util import AUTOSCALE_TIMEZONES + timezones = [] + for zone in AUTOSCALE_TIMEZONES: + if search_query and search_query.lower() not in zone['name'].lower(): + continue + if offset and offset not in zone['offset']: + continue + timezones.append(zone) + return timezones + + +def autoscale_profile_show(cmd, autoscale_name, resource_group_name, profile_name): + autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "autoscale_name": autoscale_name}) + return _identify_profile_cg(autoscale_settings["profiles"], profile_name) + + +class AutoScaleProfileDelete(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.profile_name = AAZStrArg( + options=["--profile-name"], + help='Name of the autoscale profile.', + required=True, + registered=False, + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + profile_name = args.profile_name.to_serialized_data() + default_profile = get_autoscale_default_profile(instance) + + def _should_retain_profile(profile): + name = profile.name.to_serialized_data() + try: + name = json.loads(profile.name.to_serialized_data())['for'] + except ValueError: + pass + return name.lower() != profile_name.lower() + + retained_profiles = [x for x in instance.properties.profiles if _should_retain_profile(x)] + instance.properties.profiles = retained_profiles + + # if we removed the last "default" of a recurring pair, we need to preserve it + new_default = get_autoscale_default_profile(instance) + if not new_default: + instance.properties.profiles.append(default_profile) + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + +def autoscale_profile_delete(cmd, autoscale_name, resource_group_name, profile_name): + AutoScaleProfileDelete(cli_ctx=cmd.cli_ctx)(command_args={ + "autoscale_name": autoscale_name, + "resource_group": resource_group_name, + "profile_name": profile_name, + }) + + +def get_condition_from_model(condition): + condition_obj = { + "metric_name": condition.metric_name, + "metric_namespace": condition.metric_namespace, + "metric_resource_location": condition.metric_resource_location, + "metric_resource_uri": condition.metric_resource_uri, + "operator": condition.operator.value, + "statistic": condition.statistic.value, + "threshold": float(condition.threshold), + "time_aggregation": condition.time_aggregation.value, + "time_grain": condition.time_grain, + "time_window": condition.time_window + } + if condition.divide_per_instance is not None: + condition_obj["divide_per_instance"] = condition.divide_per_instance + if condition.dimensions: + dim_objs = [] + for dim in condition.dimensions: + dim_objs.append({ + "dimension_name": dim.dimension_name, + "operator": dim.operator, + "values": dim.values + }) + condition_obj["dimensions"] = dim_objs + return condition_obj + + +def autoscale_rule_create(cmd, autoscale_name, resource_group_name, condition, + scale, profile_name=DEFAULT_PROFILE_NAME, cooldown=5, source=None, + timegrain="avg 1m"): + from azure.mgmt.core.tools import parse_resource_id, resource_id + autoscale_settings = get_autoscale_instance(cmd, resource_group_name, autoscale_name) + profile = _identify_profile_cg(autoscale_settings["profiles"], profile_name) + condition.metric_resource_uri = source or autoscale_settings["target_resource_uri"] + condition.statistic = timegrain.statistic + condition.time_grain = timegrain.time_grain + + def preprocess_for_spring_cloud_service(): + try: + result = parse_resource_id(autoscale_settings["target_resource_uri"]) + if result['namespace'].lower() == 'microsoft.appplatform' and result['type'].lower() == 'spring': + if condition.metric_namespace is None: + condition.metric_namespace = "Microsoft.AppPlatform/Spring" + logger.warning('Set metricNamespace to Microsoft.AppPlatform/Spring') + if source is None: + condition.metric_resource_uri = resource_id( + subscription=result['subscription'], + resource_group=result['resource_group'], + namespace=result['namespace'], + type=result['type'], + name=result['name'] + ) + logger.warning('Set metricResourceUri to Spring Cloud service') + except KeyError: + pass + + preprocess_for_spring_cloud_service() + + condition_obj = get_condition_from_model(condition) + + rule = { + "metric_trigger": condition_obj, + "scale_action": { + "direction": scale.direction, + "type": scale.type, + "cooldown": 'PT{}M'.format(cooldown), + "value": scale.value + } + } + profile["rules"].append(rule) + updated_rets = AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) + updated_profile = _identify_profile_cg(updated_rets["profiles"], profile_name) + # determine if there are unbalanced rules + scale_out_rule_count = len([x for x in updated_profile["rules"] if x["scaleAction"]["direction"] == "Increase"]) + scale_in_rule_count = len([x for x in updated_profile["rules"] if x["scaleAction"]["direction"] == "Decrease"]) + if scale_out_rule_count and not scale_in_rule_count: + logger.warning("Profile '%s' has rules to scale out but none to scale in. " + "Recommend creating at least 1 scale in rule.", profile_name) + elif scale_in_rule_count and not scale_out_rule_count: + logger.warning("Profile '%s' has rules to scale in but none to scale out. " + "Recommend creating at least 1 scale out rule.", profile_name) + return updated_profile["rules"][-1] + + +def autoscale_rule_list(cmd, autoscale_name, resource_group_name, profile_name=DEFAULT_PROFILE_NAME): + autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "autoscale_name": autoscale_name}) + profile = _identify_profile_cg(autoscale_settings["profiles"], profile_name) + index = 0 + # we artificially add indices to the rules so the user can target them with the remove command + for rule in profile["rules"]: + rule["index"] = index + index += 1 + return profile["rules"] + + +def autoscale_rule_delete(cmd, autoscale_name, resource_group_name, index, profile_name=DEFAULT_PROFILE_NAME): + autoscale_settings = get_autoscale_instance(cmd, resource_group_name, autoscale_name) + profile = _identify_profile_cg(autoscale_settings["profiles"], profile_name) + if '*' in index: + profile["rules"] = [] + else: + remained_rule = [] + for i, rule in enumerate(profile["rules"]): + if str(i) in index: + continue + remained_rule.append(rule) + profile["rules"] = remained_rule + AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) + + +class AutoScaleRuleCopy(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.source_profile = AAZStrArg( + options=["--source-profile"], + help='Name of the autoscale profile.', + required=True, + registered=False, + default=DEFAULT_PROFILE_NAME + ) + args_schema.dest_profile = AAZStrArg( + options=["--dest-profile"], + help='Name of the autoscale profile.', + required=True, + registered=False, + ) + args_schema.index = AAZListArg( + options=["--index"], + help="Space-separated list of rule indices to remove, or '*' to clear all rules.", + registered=False, + ) + args_schema.index.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + source_profile_name = args.source_profile.to_serialized_data() + dest_profile_name = args.dest_profile.to_serialized_data() + index = args.index.to_serialized_data() + + src_profile = _identify_profile(instance.properties.profiles, source_profile_name) + dst_profile = _identify_profile(instance.properties.profiles, dest_profile_name) + if '*' in index: + dst_profile.rules = src_profile.rules + else: + for i in index: + dst_profile.rules.append(src_profile.rules[int(i)]) + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + + +def autoscale_rule_copy(cmd, autoscale_name, resource_group_name, dest_profile, index, + source_profile=DEFAULT_PROFILE_NAME): + AutoScaleRuleCopy(cli_ctx=cmd.cli_ctx)(command_args={ + "autoscale_name": autoscale_name, + "resource_group": resource_group_name, + "source_profile": source_profile, + "dest_profile": dest_profile, + "index": index + }) + + +def _identify_profile(profiles, profile_name): + try: + profile = next(x for x in profiles if x.name == profile_name) + except StopIteration: + raise CLIError('Cannot find profile {}. ' + 'Please double check the name of the autoscale profile.'.format(profile_name)) + return profile + + +def _identify_profile_cg(profiles, profile_name): + try: + profile = next(x for x in profiles if x["name"] == profile_name) + except StopIteration: + raise CLIError('Cannot find profile {}. ' + 'Please double check the name of the autoscale profile.'.format(profile_name)) + return profile diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/diagnostics_settings.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/diagnostics_settings.py new file mode 100644 index 00000000000..fc7ce2b4787 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/diagnostics_settings.py @@ -0,0 +1,255 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from ..aaz.latest.monitor.diagnostic_settings import Create as _DiagnosticSettingsCreate +from ..aaz.latest.monitor.diagnostic_settings import List as _DiagnosticSettingsList +from ..aaz.latest.monitor.diagnostic_settings import Show as _DiagnosticSettingsShow +from ..aaz.latest.monitor.diagnostic_settings import Delete as _DiagnosticSettingsDelete +from ..aaz.latest.monitor.diagnostic_settings import Update as _DiagnosticSettingsUpdate +from ..aaz.latest.monitor.diagnostic_settings.categories import List as _DiagnosticSettingsCategoryList +from ..aaz.latest.monitor.diagnostic_settings.categories import Show as _DiagnosticSettingsCategoryShow +from knack.util import CLIError +from azure.cli.core.azclierror import ArgumentUsageError + + +def create_resource_parameters(arg_schema, arg_group=None): + from azure.cli.core.aaz import AAZResourceGroupNameArg, AAZStrArg + arg_schema.resource_group_name = AAZResourceGroupNameArg(arg_group=arg_group) + arg_schema.namespace = AAZStrArg( + options=['--resource-namespace'], + help="Target resource provider namespace.", + arg_group=arg_group, + ) + arg_schema.parent = AAZStrArg( + options=['--resource-parent'], + help="Target resource parent path, if applicable.", + arg_group=arg_group, + ) + arg_schema.resource_type = AAZStrArg( + options=['--resource-type'], + help="Target resource type. Can also accept namespace/type format (Ex: 'Microsoft.Compute/virtualMachines')", + arg_group=arg_group, + ) + + +def update_resource_parameters(ctx, alias="resource"): + args = ctx.args + from azure.mgmt.core.tools import parse_resource_id, is_valid_resource_id + from azure.cli.core.aaz import has_value + name_or_id = args.resource.to_serialized_data() + usage_error = CLIError('usage error: --{0} ID | --{0} NAME --resource-group NAME ' + '--{0}-type TYPE [--{0}-parent PARENT] ' + '[--{0}-namespace NAMESPACE]'.format(alias)) + if not name_or_id: + raise usage_error + if is_valid_resource_id(name_or_id): + if has_value(args.namespace) or has_value(args.parent) or has_value(args.resource_type): + raise usage_error + parsed_id = parse_resource_id(name_or_id) + subscription_id = parsed_id.get('subscription', None) + if subscription_id: + # update subscription_id to support cross tenants + ctx.update_aux_subscriptions(subscription_id) + else: + res_ns = args.namespace.to_serialized_data() + rg = args.resource_group_name.to_serialized_data() + res_type = args.resource_type.to_serialized_data() + parent = args.parent.to_serialized_data() + if has_value(res_type): + if '/' in res_type: + res_ns = res_ns or res_type.rsplit('/', 1)[0] + res_type = res_type.rsplit('/', 1)[1] + + if not res_ns or not rg or not res_type or not name_or_id: + raise usage_error + + args.resource = f"/subscriptions/{ctx.subscription_id}/resourceGroups/{rg}/providers/{res_ns}/" \ + f"{parent + '/' if parent else ''}{res_type}/{name_or_id}" + + +class DiagnosticSettingsCreate(_DiagnosticSettingsCreate): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + + from azure.cli.core.aaz import AAZBoolArg + arg_schema.export_to_resource_specific = AAZBoolArg( + options=['--export-to-resource-specific'], + help="Indicate that the export to LA must be done to a resource specific table, a.k.a. " + "dedicated or fixed schema table, as opposed to the default dynamic schema table called " + "AzureDiagnostics. This argument is effective only when the argument --workspace is also given. " + "Allowed values: false, true." + ) + arg_schema.log_analytics_destination_type._registered = False # pylint:disable=protected-access + arg_schema.service_bus_rule_id._registered = False # pylint:disable=protected-access + return arg_schema + + def pre_operations(self): + ctx = self.ctx + from azure.cli.core.aaz import has_value + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + update_resource_parameters(ctx) + args = ctx.args + rg = args.resource_group_name.to_serialized_data() + + if not has_value(rg): + rg = parse_resource_id(args.resource.to_serialized_data())['resource_group'] + args.resource_group_name = rg + + storage_account = args.storage_account.to_serialized_data() + if has_value(storage_account) and not is_valid_resource_id(storage_account): + storage_account = resource_id(subscription=ctx.subscription_id, + resource_group=rg, + namespace='microsoft.Storage', + type='storageAccounts', + name=storage_account) + args.storage_account = storage_account + + workspace = args.workspace.to_serialized_data() + if has_value(workspace) and not is_valid_resource_id(workspace): + workspace = resource_id(subscription=ctx.subscription_id, + resource_group=rg, + namespace='microsoft.OperationalInsights', + type='workspaces', + name=workspace) + args.workspace = workspace + + event_hub = args.event_hub.to_serialized_data() + if has_value(event_hub) and is_valid_resource_id(event_hub): + event_hub = parse_resource_id(event_hub)['name'] + args.event_hub = event_hub + + event_hub_rule = args.event_hub_rule.to_serialized_data() + if has_value(event_hub_rule): + if not is_valid_resource_id(event_hub_rule): + if not has_value(event_hub): + raise CLIError('usage error: --event-hub-rule ID | --event-hub-rule NAME --event-hub NAME') + # use value from --event-hub if the rule is a name + event_hub_rule = resource_id( + subscription=ctx.subscription_id, + resource_group=rg, + namespace='Microsoft.EventHub', + type='namespaces', + name=event_hub, + child_type_1='AuthorizationRules', + child_name_1=event_hub_rule) + args.event_hub_rule = event_hub_rule + + elif not has_value(event_hub): + # extract the event hub name from `--event-hub-rule` if provided as an ID + event_hub = parse_resource_id(event_hub_rule)['name'] + args.event_hub = event_hub + if not (has_value(storage_account) or has_value(workspace) or has_value(event_hub)): + raise CLIError( + 'usage error - expected one or more: --storage-account NAME_OR_ID | --workspace NAME_OR_ID ' + '| --event-hub NAME_OR_ID | --event-hub-rule ID') + + export_to_resource_specific = args.export_to_resource_specific.to_serialized_data() + if has_value(export_to_resource_specific) and export_to_resource_specific: + args.log_analytics_destination_type = 'Dedicated' + if not has_value(workspace): + raise ArgumentUsageError('usage error: --workspace and --export-to-specific-resource') + else: + args.log_analytics_destination_type = None + + +class DiagnosticSettingsShow(_DiagnosticSettingsShow): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +class DiagnosticSettingsList(_DiagnosticSettingsList): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +class DiagnosticSettingsDelete(_DiagnosticSettingsDelete): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +class DiagnosticSettingsUpdate(_DiagnosticSettingsUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +class DiagnosticSettingsCategoryList(_DiagnosticSettingsCategoryList): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +class DiagnosticSettingsCategoryShow(_DiagnosticSettingsCategoryShow): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + ctx = self.ctx + update_resource_parameters(ctx) + + +# pylint: disable=unused-argument, line-too-long +def create_diagnostics_settings(client, name, resource_uri, + logs=None, + metrics=None, + event_hub=None, + event_hub_rule=None, + storage_account=None, + workspace=None, + export_to_resource_specific=None): + from azure.mgmt.monitor.models import DiagnosticSettingsResource + if export_to_resource_specific and workspace is None: + raise CLIError('usage error: --workspace and --export-to-specific-resource') + parameters = DiagnosticSettingsResource(storage_account_id=storage_account, + workspace_id=workspace, + event_hub_name=event_hub, + event_hub_authorization_rule_id=event_hub_rule, + metrics=metrics, + logs=logs, + log_analytics_destination_type='Dedicated' if export_to_resource_specific else None) + + return client.create_or_update(resource_uri=resource_uri, parameters=parameters, name=name) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/general_operations.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/general_operations.py new file mode 100644 index 00000000000..59ace8bc637 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/general_operations.py @@ -0,0 +1,13 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +from azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util import _clone_monitor_metrics_alerts + + +def clone_existed_settings(cmd, source_resource, target_resource, always_clone=False, monitor_types=None): + result = {} + monitor_types = set(monitor_types) + if "metricsAlert" in monitor_types: + result["metricsAlert"] = _clone_monitor_metrics_alerts(cmd, source_resource, target_resource, always_clone) + return result diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_linked_storage_account.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_linked_storage_account.py new file mode 100644 index 00000000000..0e4da220d34 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_linked_storage_account.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.linked_storage import \ + Create as _WorkspaceLinkedStorageAccountCreate, Update as _WorkspaceLinkedStorageAccountUpdate + + +class WorkspaceLinkedStorageAccountCreate(_WorkspaceLinkedStorageAccountCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZResourceIdArg, AAZResourceIdArgFormat + cls._args_schema = super()._build_arguments_schema(*args, **kwargs) + + storage_accounts = cls._args_schema.storage_accounts + storage_accounts._element = AAZResourceIdArg(fmt=AAZResourceIdArgFormat( # pylint: disable=protected-access + template='/subscriptions/{subscription}/resourceGroups/{resource_group}/' + 'providers/Microsoft.Storage/storageAccounts/{}')) + return cls._args_schema + + +def add_log_analytics_workspace_linked_storage_accounts(cmd, resource_group_name, workspace_name, + data_source_type, storage_account_ids): + class Add(_WorkspaceLinkedStorageAccountUpdate): + + def pre_instance_update(self, instance): + instance.properties.storage_account_ids.extend(storage_account_ids) + + return Add(cli_ctx=cmd.cli_ctx)(command_args={ + "data_source_type": data_source_type, + "resource_group": resource_group_name, + "workspace_name": workspace_name + }) + + +def remove_log_analytics_workspace_linked_storage_accounts(cmd, resource_group_name, workspace_name, + data_source_type, storage_account_ids): + class Remove(_WorkspaceLinkedStorageAccountUpdate): + + def pre_instance_update(self, instance): + storage_account_ids_set = set(str.lower(storage_account_id) for storage_account_id in storage_account_ids) + new_storage_account_ids = [] + for existed_storage_account_id in instance.properties.storage_account_ids: + if str(existed_storage_account_id).lower() in storage_account_ids_set: + continue + new_storage_account_ids.append(existed_storage_account_id) + instance.properties.storage_account_ids = new_storage_account_ids + + return Remove(cli_ctx=cmd.cli_ctx)(command_args={ + "data_source_type": data_source_type, + "resource_group": resource_group_name, + "workspace_name": workspace_name + }) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_workspace.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_workspace.py new file mode 100644 index 00000000000..dd2f80280ae --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_analytics_workspace.py @@ -0,0 +1,352 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.data_export import \ + Create as _WorkspaceDataExportCreate, \ + Update as _WorkspaceDataExportUpdate +from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.table import \ + Create as _WorkspaceTableCreate, \ + Update as _WorkspaceTableUpdate +from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.table.search_job \ + import Cancel as _WorkspaceTableSearchJobCancel + +from azure.cli.core.azclierror import ArgumentUsageError, InvalidArgumentValueError, RequiredArgumentMissingError +from azure.cli.core.commands.transform import _parse_id +from azure.cli.core.aaz import has_value + + +def list_deleted_log_analytics_workspaces(client, resource_group_name=None): + if resource_group_name: + return client.list_by_resource_group(resource_group_name) + return client.list() + + +def recover_log_analytics_workspace(cmd, workspace_name, resource_group_name=None, no_wait=False): + from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace import Create, \ + ListDeletedWorkspaces + + deleted_workspaces = ListDeletedWorkspaces(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name + }) + + for deleted_workspace in deleted_workspaces: + if deleted_workspace['name'].lower() == workspace_name.lower(): + resource_group_name = _parse_id(deleted_workspace['id'])['resource-group'] + location = deleted_workspace['location'] + return Create(cli_ctx=cmd.cli_ctx)(command_args={ + "workspace_name": deleted_workspace['name'], + "resource_group": resource_group_name, + "location": location, + "no_wait": no_wait, + }) + + raise InvalidArgumentValueError('{} is not a deleted workspace and you can only recover a deleted workspace ' + 'within 14 days.'.format(workspace_name)) + + +def _format_tags(tags): + if tags: + tags = [{"name": key, "value": value} for key, value in tags.items()] + return tags + + +def create_log_analytics_workspace_saved_search(cmd, workspace_name, resource_group_name, saved_search_id, + category, display_name, saved_query, + function_alias=None, function_parameters=None, + tags=None): + from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.saved_search import Create + + command_args = { + "resource_group": resource_group_name, + "saved_search_name": saved_search_id, + "workspace_name": workspace_name, + "category": category, + "display_name": display_name, + "saved_query": saved_query, + } + if function_alias is not None: + command_args['func_alias'] = function_alias + if function_parameters is not None: + command_args['func_param'] = function_parameters + if tags is not None: + command_args['tags'] = _format_tags(tags) + return Create(cli_ctx=cmd.cli_ctx)( + command_args=command_args + ) + + +def update_log_analytics_workspace_saved_search(cmd, workspace_name, resource_group_name, saved_search_id, + category=None, display_name=None, saved_query=None, + function_alias=None, function_parameters=None, + tags=None): + from azure.cli.command_modules.monitor._legacy.aaz.latest.monitor.log_analytics.workspace.saved_search import Update + command_args = { + "resource_group": resource_group_name, + "saved_search_name": saved_search_id, + "workspace_name": workspace_name, + } + + if category is not None: + command_args['category'] = category + if display_name is not None: + command_args['display_name'] = display_name + if saved_query is not None: + command_args['saved_query'] = saved_query + if function_alias is not None: + command_args['func_alias'] = function_alias + if function_parameters is not None: + command_args['func_param'] = function_parameters + if tags is not None: + command_args['tags'] = _format_tags(tags) + return Update(cli_ctx=cmd.cli_ctx)( + command_args=command_args + ) + + +class WorkspaceDataExportCreate(_WorkspaceDataExportCreate): + + def pre_operations(self): + args = self.ctx.args + destination = str(args.destination) + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + if not is_valid_resource_id(destination): + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + result = parse_resource_id(destination) + if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': + args.destination = resource_id( + subscription=result['subscription'], + resource_group=result['resource_group'], + namespace=result['namespace'], + type=result['type'], + name=result['name'] + ) + if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': + args.event_hub_name = result['child_name_1'] + elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': + pass + else: + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + + +class WorkspaceDataExportUpdate(_WorkspaceDataExportUpdate): + + def pre_operations(self): + args = self.ctx.args + if args.destination: + destination = str(args.destination) + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + if not is_valid_resource_id(destination): + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + result = parse_resource_id(destination) + if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': + args.destination = resource_id( + subscription=result['subscription'], + resource_group=result['resource_group'], + namespace=result['namespace'], + type=result['type'], + name=result['name'] + ) + if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': + args.event_hub_name = result['child_name_1'] + elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': + pass + else: + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + + +class WorkspaceTableCreate(_WorkspaceTableCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZIntArgFormat + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.total_retention_in_days._fmt = AAZIntArgFormat( + maximum=4383, + minimum=-1, + ) + args_schema.retention_in_days._fmt = AAZIntArgFormat( + maximum=730, + minimum=-1, + ) + return args_schema + + def pre_operations(self): + args = self.ctx.args + if has_value(args.retention_in_days): + retention_time = args.retention_in_days.to_serialized_data() + if retention_time == -1 or (4 <= retention_time <= 730): + pass + else: + raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " + "Otherwise setting this property to -1 will default to " + "workspace retention.") + + if has_value(args.total_retention_in_days): + total_retention_time = args.total_retention_in_days.to_serialized_data() + if total_retention_time == -1 or (4 <= total_retention_time <= 4383): + pass + else: + raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " + "Otherwise setting this property to -1 will default to " + "table retention.") + + +class WorkspaceTableUpdate(_WorkspaceTableUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZIntArgFormat + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.total_retention_in_days._fmt = AAZIntArgFormat( + maximum=4383, + minimum=-1, + ) + args_schema.retention_in_days._fmt = AAZIntArgFormat( + maximum=730, + minimum=-1, + ) + return args_schema + + def pre_operations(self): + args = self.ctx.args + if has_value(args.retention_in_days): + retention_time = args.retention_in_days.to_serialized_data() + if retention_time == -1 or (4 <= retention_time <= 730): + pass + else: + raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " + "Otherwise setting this property to -1 will default to " + "workspace retention.") + + if has_value(args.total_retention_in_days): + total_retention_time = args.total_retention_in_days.to_serialized_data() + if total_retention_time == -1 or (4 <= total_retention_time <= 4383): + pass + else: + raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " + "Otherwise setting this property to -1 will default to " + "table retention.") + + +class WorkspaceTableSearchJobCancel(_WorkspaceTableSearchJobCancel): + def pre_operations(self): + args = self.ctx.args + table_name = args.table_name.to_serialized_data() + + if table_name and not table_name.endswith("_SRCH"): + raise InvalidArgumentValueError('usage: The table name needs to end with _SRCH') + + +# pylint:disable=too-many-locals +def create_log_analytics_workspace_table(cmd, resource_group_name, workspace_name, table_name, columns=None, + retention_in_days=None, total_retention_in_days=None, plan=None, + description=None, no_wait=False): + if retention_in_days and total_retention_in_days: + if total_retention_in_days < retention_in_days: + raise InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time' + ' should be less than --total-retention-time') + columns_list = None + if columns: + columns_list = [] + for col in columns: + if '=' in col: + n, t = col.split('=', 1) + else: + raise ArgumentUsageError('Usage error: --columns should be provided in colunm_name=colunm_type format') + columns_list.append({"name": n, "type": t}) + + if columns or description is not None: + if not columns: + raise RequiredArgumentMissingError('Usage error: When using --description, --columns must be provided') + return WorkspaceTableCreate(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "table_name": table_name, + "workspace_name": workspace_name, + "retention_in_days": retention_in_days, + "total_retention_in_days": total_retention_in_days, + "plan": plan, + "schema": { + "columns": columns_list, + "description": description, + "name": table_name, + }, + "no_wait": no_wait, + }) + + +def create_log_analytics_workspace_table_search_job(cmd, resource_group_name, workspace_name, table_name, + search_query, start_search_time, end_search_time, + retention_in_days=None, total_retention_in_days=None, limit=None, + no_wait=False): + return WorkspaceTableCreate(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "table_name": table_name, + "workspace_name": workspace_name, + "retention_in_days": retention_in_days, + "total_retention_in_days": total_retention_in_days, + "search_results": { + "query": search_query, + "limit": limit, + "start_search_time": start_search_time, + "end_search_time": end_search_time, + }, + "no_wait": no_wait, + }) + + +def create_log_analytics_workspace_table_restore(cmd, resource_group_name, workspace_name, table_name, + start_restore_time, end_restore_time, restore_source_table, + no_wait=False): + return WorkspaceTableCreate(cli_ctx=cmd.cli_ctx)(command_args={ + "resource_group": resource_group_name, + "table_name": table_name, + "workspace_name": workspace_name, + "restored_logs": { + "start_restore_time": start_restore_time, + "end_restore_time": end_restore_time, + "source_table": restore_source_table, + }, + "no_wait": no_wait, + }) + + +def update_log_analytics_workspace_table(cmd, resource_group_name, workspace_name, table_name, columns=None, + retention_in_days=None, total_retention_in_days=None, plan=None, + description=None, no_wait=False): + columns_list = None + if columns: + columns_list = [] + for col in columns: + if '=' in col: + n, t = col.split('=', 1) + else: + raise ArgumentUsageError('Usage error: --columns should be provided in colunm_name=colunm_type format') + columns_list.append({"name": n, "type": t}) + + command_args = { + "resource_group": resource_group_name, + "table_name": table_name, + "workspace_name": workspace_name, + "no_wait": no_wait, + } + if retention_in_days is not None: + command_args["retention_in_days"] = retention_in_days + if total_retention_in_days is not None: + command_args["total_retention_in_days"] = total_retention_in_days + if plan is not None: + command_args["plan"] = plan + if columns_list or description is not None: + command_args["schema"] = {"name": table_name} + if columns_list is not None: + command_args["schema"]["columns"] = columns_list + if description is not None: + command_args["schema"]["description"] = description + return WorkspaceTableUpdate(cli_ctx=cmd.cli_ctx)(command_args=command_args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_profiles.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_profiles.py new file mode 100644 index 00000000000..66f3e93579e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/log_profiles.py @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +def create_log_profile_operations(client, name, location, locations, categories, days, enabled, tags=None, + storage_account_id=None, service_bus_rule_id=None): + from azure.mgmt.monitor.models import RetentionPolicy, LogProfileResource + parameters = LogProfileResource(location=location, locations=locations, categories=categories, + retention_policy=RetentionPolicy(days=days, enabled=enabled), + storage_account_id=storage_account_id, service_bus_rule_id=service_bus_rule_id, + tags=tags) + return client.create_or_update(log_profile_name=name, parameters=parameters) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/metric_alert.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/metric_alert.py new file mode 100644 index 00000000000..3e6cf902d83 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/metric_alert.py @@ -0,0 +1,381 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=too-many-locals, line-too-long, protected-access, too-many-nested-blocks +import antlr4 + +from azure.cli.command_modules.monitor._legacy.actions import AAZCustomListArg +from azure.cli.command_modules.monitor._legacy.grammar.metric_alert import MetricAlertConditionLexer, \ + MetricAlertConditionParser, MetricAlertConditionValidator +from azure.cli.core.aaz import has_value +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.mgmt.core.tools import is_valid_resource_id, resource_id +from knack.log import get_logger +from msrest.serialization import Serializer + +from ..aaz.latest.monitor.metrics.alert import Update as _MetricsAlertUpdate + +logger = get_logger(__name__) + +_metric_alert_dimension_prefix = '_where_' + + +def create_metric_alert(cmd, resource_group_name, rule_name, scopes, condition, disabled=False, description=None, + tags=None, actions=None, severity=2, window_size='5m', evaluation_frequency='1m', + auto_mitigate=None, target_resource_type=None, target_resource_region=None): + # generate metadata for the conditions + is_dynamic_threshold_criterion = False + all_of = [] + single_all_of = [] + for i, cond in enumerate(condition): + if "dynamic" in cond: + is_dynamic_threshold_criterion = True + item = cond["dynamic"] + item["name"] = f"cond{i}" + props = { + "alert_sensitivity": item.pop("alert_sensitivity", None), + "failing_periods": item.pop("failing_periods", None), + "operator": item.pop("operator", None), + "ignore_data_before": Serializer.serialize_iso(dt) if (dt := item.pop("ignore_data_before", None)) else None + } + + all_of.append({**item, **{"dynamic_threshold_criterion": props}}) + single_all_of.append({**item, **props}) + else: + item = cond["static"] + item["name"] = f"cond{i}" + props = { + "operator": item.pop("operator", None), + "threshold": item.pop("threshold", None) + } + + all_of.append({**item, **{"static_threshold_criterion": props}}) + single_all_of.append({**item, **props}) + + criteria = None + resource_type, scope_type = _parse_resource_and_scope_type(scopes) + if scope_type in ['resource_group', 'subscription']: + if target_resource_type is None or target_resource_region is None: + raise InvalidArgumentValueError('--target-resource-type and --target-resource-region must be provided.') + criteria = {"microsoft_azure_monitor_multiple_resource_multiple_metric_criteria": {"all_of": all_of}} + else: + if len(scopes) == 1: + if not is_dynamic_threshold_criterion: + criteria = {"microsoft_azure_monitor_single_resource_multiple_metric_criteria": {"all_of": single_all_of}} + else: + criteria = {"microsoft_azure_monitor_multiple_resource_multiple_metric_criteria": {"all_of": all_of}} + else: + criteria = {"microsoft_azure_monitor_multiple_resource_multiple_metric_criteria": {"all_of": all_of}} + target_resource_type = resource_type + target_resource_region = target_resource_region if target_resource_region else 'global' + + from ..aaz.latest.monitor.metrics.alert import Create + return Create(cli_ctx=cmd.cli_ctx)(command_args={ + 'resource_group': resource_group_name, + 'name': rule_name, + 'description': description, + 'severity': severity, + 'enabled': not disabled, + 'scopes': scopes, + 'evaluation_frequency': evaluation_frequency, + 'window_size': window_size, + 'criteria': criteria, + 'target_resource_type': target_resource_type, + 'target_resource_region': target_resource_region, + 'actions': actions, + 'tags': tags, + 'location': 'global', + 'auto_mitigate': auto_mitigate + }) + + +class MetricsAlertUpdate(_MetricsAlertUpdate): + def __init__(self, loader=None, cli_ctx=None, callbacks=None, **kwargs): + super().__init__(loader, cli_ctx, callbacks, **kwargs) + self.add_actions = [] + self.add_conditions = [] + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZListArg, AAZStrArg, AAZResourceIdArg, AAZResourceIdArgFormat + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.add_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action"], + arg_group="Action", + help="Add an action group and optional webhook properties to fire when the alert is triggered.\n\n" + "Usage: --add-action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]\n\n" + "Multiple action groups can be specified by using more than one `--add-action` argument." + ) + args_schema.add_actions.Element = AAZCustomListArg() + args_schema.add_actions.Element.Element = AAZStrArg() + args_schema.remove_actions = AAZListArg( + options=["--remove-actions"], + arg_group="Action", + help="Space-separated list of action group names to remove." + ) + args_schema.remove_actions.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Insights" + "/actionGroups/{}" + ) + ) + args_schema.add_conditions = AAZCustomListArg( + options=["--add-conditions"], + singular_options=["--add-condition"], + arg_group="Condition", + help="Add a condition which triggers the rule.\n\n" + "Usage: --add-condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n" + "[{=,!=,>,>=,<,<=} THRESHOLD]\n" + "[{>,><,<} dynamic SENSITIVITY VIOLATIONS of EVALUATIONS [since DATETIME]]\n" + "[where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n" + "[and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n\n" + "Sensitivity can be 'low', 'medium', 'high'.\n\n" + "Violations can be the number of violations to trigger an alert. It should be smaller or equal to evaluation.\n\n" + "Evaluations can be the number of evaluation periods for dynamic threshold.\n\n" + "Datetime can be the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format).\n\n" + "Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be queried by combining them with the 'and' keyword.\n\n" + "Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az monitor metrics list-definitions` command.\n\n" + "Due to server limitation, when an alert rule contains multiple criterias, the use of dimensions is limited to one value per dimension within each criterion.\n\n" + "Multiple conditions can be specified by using more than one `--add-condition` argument." + ) + args_schema.add_conditions.Element = AAZListArg() + args_schema.add_conditions.Element.Element = AAZStrArg() + args_schema.remove_conditions = AAZListArg( + options=["--remove-conditions"], + arg_group="Condition", + help="Space-separated list of condition names to remove." + ) + args_schema.remove_conditions.Element = AAZStrArg() + + return args_schema + + def pre_operations(self): + def complete_action_group_id(name): + if is_valid_resource_id(name): + return name + + return resource_id( + subscription=self.ctx.subscription_id, + resource_group=self.ctx.args.resource_group, + namespace="Microsoft.Insights", + type="actionGroups", + name=name + ) + + args = self.ctx.args + if has_value(args.add_actions): + self.add_actions = [] + for add_action in args.add_actions: + values = add_action.to_serialized_data()[0].split() + action_group_id = complete_action_group_id(values[0]) + try: + webhook_property_candidates = dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None + except ValueError: + err_msg = "Value of --add-action is invalid. Please refer to --help to get insight of correct format." + raise InvalidArgumentValueError(err_msg) + + action = { + "action_group_id": action_group_id, + "web_hook_properties": webhook_property_candidates + } + action["odatatype"] = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models." \ + "Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.Action" + + self.add_actions.append(action) + + if has_value(args.add_conditions): + err_msg = 'usage error: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n' \ + ' [{=,!=,>,>=,<,<=} THRESHOLD]\n' \ + ' [{<,>,><} dynamic SENSITIVITY VIOLATION of EVALUATION [since DATETIME]]\n' \ + ' [where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n' \ + ' [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n' \ + ' [with skipmetricvalidation]' + + self.add_conditions = [] + for add_condition in args.add_conditions: + string_val = add_condition.to_serialized_data()[0] + lexer = MetricAlertConditionLexer(antlr4.InputStream(string_val)) + stream = antlr4.CommonTokenStream(lexer) + parser = MetricAlertConditionParser(stream) + tree = parser.expression() + + try: + validator = MetricAlertConditionValidator() + walker = antlr4.ParseTreeWalker() + walker.walk(validator, tree) + metric_condition = validator.result() + if "static" in metric_condition: + # static metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'threshold']: + if item not in metric_condition["static"]: + raise InvalidArgumentValueError(err_msg) + elif "dynamic" in metric_condition: + # dynamic metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'alert_sensitivity', + 'failing_periods']: + if item not in metric_condition["dynamic"]: + raise InvalidArgumentValueError(err_msg) + else: + raise NotImplementedError() + except (AttributeError, TypeError, KeyError): + raise InvalidArgumentValueError(err_msg) + + self.add_conditions.append(metric_condition) + + def pre_instance_update(self, instance): + def get_next_name(): + idx = 0 + while True: + possible_name = f"cond{idx}" + match = next((cond for cond in instance.properties.criteria.all_of if cond.name == possible_name), None) + if match: + idx += 1 + continue + + return possible_name + + args = self.ctx.args + if has_value(args.remove_actions): + to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_actions)) + + new_actions = [] + for action in instance.properties.actions: + if action.action_group_id.to_serialized_data().lower() not in to_be_removed: + new_actions.append(action) + + instance.properties.actions = new_actions + + if has_value(args.add_actions): + to_be_added = set(map(lambda x: x["action_group_id"].lower(), self.add_actions)) + + new_actions = [] + for action in instance.properties.actions: + if action.action_group_id.to_serialized_data().lower() not in to_be_added: + new_actions.append(action) + new_actions.extend(self.add_actions) + + instance.properties.actions = new_actions + + if has_value(args.remove_conditions): + to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_conditions)) + + new_conditions = [] + for cond in instance.properties.criteria.all_of: + if cond.name.to_serialized_data().lower() not in to_be_removed: + new_conditions.append(cond) + + instance.properties.criteria.all_of = new_conditions + + if has_value(args.add_conditions): + for cond in self.add_conditions: + if "dynamic" in cond: + item = cond["dynamic"] + item["name"] = get_next_name() + item["criterion_type"] = "DynamicThresholdCriterion" + item["ignore_data_before"] = Serializer.serialize_iso(dt) if (dt := item.pop("ignore_data_before", None)) else None + + instance.properties.criteria.all_of.append(item) + else: + item = cond["static"] + item["name"] = get_next_name() + item["criterion_type"] = "StaticThresholdCriterion" + + instance.properties.criteria.all_of.append(item) + + +def create_metric_alert_dimension(dimension_name, value_list, operator=None): + values = ' or '.join(value_list) + return '{} {} {} {}'.format(_metric_alert_dimension_prefix, dimension_name, operator, values) + + +def create_metric_alert_condition(condition_type, aggregation, metric_name, operator, metric_namespace='', + dimension_list=None, threshold=None, alert_sensitivity=None, + number_of_evaluation_periods=None, min_failing_periods_to_alert=None, + ignore_data_before=None, skip_metric_validation=None): + if metric_namespace: + metric_namespace += '.' + condition = "{} {}'{}' {} ".format(aggregation, metric_namespace, metric_name, operator) + if condition_type == 'static': + condition += '{} '.format(threshold) + elif condition_type == 'dynamic': + dynamics = 'dynamic {} {} of {} '.format( + alert_sensitivity, min_failing_periods_to_alert, number_of_evaluation_periods) + if ignore_data_before: + dynamics += 'since {} '.format(ignore_data_before) + condition += dynamics + else: + raise NotImplementedError() + + if dimension_list: + dimensions = ' '.join([t for t in dimension_list if t.strip()]) + if dimensions.startswith(_metric_alert_dimension_prefix): + dimensions = [t for t in dimensions.split(_metric_alert_dimension_prefix) if t] + dimensions = 'where' + 'and'.join(dimensions) + condition += dimensions + + if skip_metric_validation: + condition += ' with skipmetricvalidation' + + return condition.strip() + + +def _parse_action_removals(actions): + """ Separates the combined list of keys to remove into webhooks and emails. """ + flattened = list({x for sublist in actions for x in sublist}) + emails = [] + webhooks = [] + for item in flattened: + if item.startswith('http://') or item.startswith('https://'): + webhooks.append(item) + else: + emails.append(item) + return emails, webhooks + + +def _parse_resource_and_scope_type(scopes): + from azure.mgmt.core.tools import parse_resource_id + + if not scopes: + raise InvalidArgumentValueError('scopes cannot be null.') + + namespace = '' + resource_type = '' + scope_type = None + + def validate_scope(item_namespace, item_resource_type, item_scope_type): + if namespace != item_namespace or resource_type != item_resource_type or scope_type != item_scope_type: + raise InvalidArgumentValueError('Multiple scopes should be the same resource type.') + + def store_scope(item_namespace, item_resource_type, item_scope_type): + nonlocal namespace + nonlocal resource_type + nonlocal scope_type + namespace = item_namespace + resource_type = item_resource_type + scope_type = item_scope_type + + def parse_one_scope_with_action(scope, operation_on_scope): + result = parse_resource_id(scope) + if 'namespace' in result and 'resource_type' in result: + resource_types = [result['type']] + child_idx = 1 + while 'child_type_{}'.format(child_idx) in result: + resource_types.append(result['child_type_{}'.format(child_idx)]) + child_idx += 1 + operation_on_scope(result['namespace'], '/'.join(resource_types), 'resource') + elif 'resource_group' in result: # It's a resource group. + operation_on_scope('', '', 'resource_group') + elif 'subscription' in result: # It's a subscription. + operation_on_scope('', '', 'subscription') + else: + raise InvalidArgumentValueError('Scope must be a valid resource id.') + + # Store the resource type and scope type from first scope + parse_one_scope_with_action(scopes[0], operation_on_scope=store_scope) + # Validate the following scopes + for item in scopes: + parse_one_scope_with_action(item, operation_on_scope=validate_scope) + + return namespace + '/' + resource_type, scope_type diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/monitor_clone_util.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/monitor_clone_util.py new file mode 100644 index 00000000000..34887588f89 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/monitor_clone_util.py @@ -0,0 +1,133 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=line-too-long, protected-access +from knack.log import get_logger +from knack.util import CLIError +from azure.mgmt.core.tools import parse_resource_id +from azure.cli.core.commands.transform import _parse_id +from azure.cli.command_modules.network.custom import _convert_to_snake_case +from azure.cli.command_modules.monitor._legacy.util import gen_guid + +logger = get_logger(__name__) +CLONED_NAME = "cloned-{}-{}" + + +def _get_metrics_alert_rules_clone_list(cmd, source_resource, target_resource): + subscription_id = parse_resource_id(source_resource)['subscription'] + from ..aaz.latest.monitor.metrics.alert import List + alert_rules = List(cli_ctx=cmd.cli_ctx)(command_args={"subscription": subscription_id}) + alert_rules = _convert_to_snake_case(alert_rules) + for alert_rule in alert_rules: + if source_resource in alert_rule['scopes']: + if target_resource not in alert_rule['scopes']: + yield alert_rule + else: + logger.warning('The target resource already has alert rule %s. ' + 'Skip cloning this one.', alert_rule['name']) + + +def _add_into_existing_scopes(cmd, source_resource, alert_rule, target_resource): + subscription_id = parse_resource_id(source_resource)['subscription'] + resource_group_name, name = _parse_id(alert_rule['id']).values() # pylint: disable=unbalanced-dict-unpacking + command_args = { + "subscription": subscription_id, + "resource_group": resource_group_name, + "name": name, + "scopes": alert_rule['scopes'] + [target_resource] + } + from ..aaz.latest.monitor.metrics.alert import Update + return Update(cli_ctx=cmd.cli_ctx)(command_args=command_args) + + +def _clone_and_replace_action_group(cmd, source_resource, alert_rule, action_group_mapping, target_resource): + source_subscription_id = parse_resource_id(source_resource)['subscription'] + target_subscription_id = parse_resource_id(target_resource)['subscription'] + for index, action in enumerate(alert_rule['actions']): + if action['action_group_id'] in action_group_mapping: + alert_rule['actions'][index] = action_group_mapping[action['action_group_id']][1] + else: + resource_group_name, name = _parse_id(action["action_group_id"]).values() # pylint: disable=unbalanced-dict-unpacking + from ..aaz.latest.monitor.action_group import Show + action_group = Show(cli_ctx=cmd.cli_ctx)(command_args={ + 'subscription': source_subscription_id, + "resource_group": resource_group_name, + "action_group_name": name, + }) + + from .action_groups import ActionGroupCreate + name = CLONED_NAME.format(name, gen_guid()) + resource_group_name, _ = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking + action_group["subscription"] = target_subscription_id + action_group["resource_group"] = resource_group_name + action_group["action_group_name"] = name + new_action_group = ActionGroupCreate(cli_ctx=cmd.cli_ctx)(command_args=action_group) + new_action = { + "action_group_id": new_action_group["id"], + "web_hook_properties": action.get("web_hook_properties", {}) + } + alert_rule['actions'][index] = new_action + action_group_mapping[action['action_group_id']] = [new_action_group['id'], new_action] + return alert_rule + + +def format_metrics_alert_req(alert_rule): + all_of = alert_rule["criteria"]["all_of"] + odata_type = alert_rule["criteria"]["odata.type"] + otype = odata_type.split(".")[-1] + type_snake = _convert_to_snake_case(otype) + if type_snake.find("single_resource_multiple_metric_criteria"): + alert_rule['criteria'] = { + "microsoft_azure_monitor_single_resource_multiple_metric_criteria": {"all_of": all_of} + } + else: + alert_rule['criteria'] = { + "microsoft_azure_monitor_multiple_resource_multiple_metric_criteria": {"all_of": all_of} + } + + +def _clone_alert_rule(cmd, alert_rule, target_resource): + alert_rule['scopes'] = [target_resource] + resource_group_name, name = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking + name = CLONED_NAME.format(name, gen_guid()) + subscription_id = parse_resource_id(target_resource)['subscription'] + alert_rule["subscription"] = subscription_id + alert_rule["resource_group"] = resource_group_name + alert_rule["name"] = name + format_metrics_alert_req(alert_rule) + from ..aaz.latest.monitor.metrics.alert import Create + return Create(cli_ctx=cmd.cli_ctx)(command_args=alert_rule) + + +def _clone_monitor_metrics_alerts(cmd, source_resource, target_resource, always_clone=False): + same_rp, same_sub = _is_resource_type_same_and_sub_same(source_resource, target_resource) + if not same_rp: + raise CLIError('The target resource should be the same type with the source resource') + updated_metrics_alert_rules = [] + action_group_mapping = {} + from azure.core.exceptions import HttpResponseError + for alert_rule in _get_metrics_alert_rules_clone_list(cmd, source_resource, target_resource): + if always_clone or not same_sub: + alert_rule = _clone_and_replace_action_group(cmd, source_resource, alert_rule, action_group_mapping, + target_resource) + alert_rule = _clone_alert_rule(cmd, alert_rule, target_resource) + else: + try: + alert_rule = _add_into_existing_scopes(cmd, source_resource, alert_rule, target_resource) + except HttpResponseError as ex: # Create new alert rule + if ex.status_code == 400: + alert_rule = _clone_alert_rule(cmd, alert_rule, target_resource) + else: + raise ex + updated_metrics_alert_rules.append(alert_rule) + + return updated_metrics_alert_rules + + +def _is_resource_type_same_and_sub_same(source_resource, target_resource): + source_dict = parse_resource_id(source_resource.lower()) + target_dict = parse_resource_id(target_resource.lower()) + same_rp = source_dict['namespace'] == target_dict['namespace'] and source_dict['type'] == target_dict['type'] + same_sub = source_dict['subscription'] == target_dict['subscription'] + return same_rp, same_sub diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/private_link_scope.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/private_link_scope.py new file mode 100644 index 00000000000..c55463d77b5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/operations/private_link_scope.py @@ -0,0 +1,126 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: disable=line-too-long, protected-access +from azure.cli.core.aaz import has_value, register_command +from azure.cli.core.azclierror import ArgumentUsageError +from azure.cli.core.util import parse_proxy_resource_id + +from ..aaz.latest.monitor.private_link_scope import Create as _PrivateLinkScopeCreate +from ..aaz.latest.monitor.private_link_scope.private_endpoint_connection import Delete as _ConnectionDelete, \ + Show as _ConnectionShow, Update + + +def validate_private_endpoint_connection_id(args): + if has_value(args.id): + data = parse_proxy_resource_id(args.id.to_serialized_data()) + args.name = data["child_name_1"] + args.resource_group = data["resource_group"] + args.scope_name = data["name"] + + if not all([has_value(args.name), has_value(args.resource_group), has_value(args.scope_name)]): + err_msg = "Incorrect usage. Please provide [--id ID] or [--n NAME -g NAME --scope-name NAME]." + raise ArgumentUsageError(error_msg=err_msg) + + +class PrivateLinkScopeCreate(_PrivateLinkScopeCreate): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.location._required = False + args_schema.location._registered = False + + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.location = "global" + + +class ConnectionDelete(_ConnectionDelete): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZStrArg + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.id = AAZStrArg( + options=["--id"], + help="ID of the private endpoint connection associated with the private link scope. " + "Values from `az monitor private-link-scope show`." + ) + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + validate_private_endpoint_connection_id(self.ctx.args) + + +class ConnectionShow(_ConnectionShow): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZStrArg + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.id = AAZStrArg( + options=["--id"], + help="ID of the private endpoint connection associated with the private link scope. " + "Values from `az monitor private-link-scope show`." + ) + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + validate_private_endpoint_connection_id(self.ctx.args) + + +@register_command("monitor private-link-scope private-endpoint-connection approve") +class ConnectionApprove(Update): + """ Approve a private endpoint connection of a private link scope resource. + + :example: Approve a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection approve --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.status._registered = False + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.status = "Approved" + validate_private_endpoint_connection_id(args) + + +@register_command("monitor private-link-scope private-endpoint-connection reject") +class ConnectionReject(Update): + """ Reject a private endpoint connection of a private link scope resource. + + :example: Reject a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection reject --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.status._registered = False + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.status = "Rejected" + validate_private_endpoint_connection_id(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/transformers.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/transformers.py new file mode 100644 index 00000000000..f6cd10dabef --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/transformers.py @@ -0,0 +1,111 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +"""The output transformers for monitor commands. The global import should be limited to improve performance.""" + + +def _item_to_ordered_dict(item, *properties): + from collections import OrderedDict + result = OrderedDict() + + for p in properties: + if isinstance(p, tuple): + property_name, display_name = p + else: + property_name = display_name = str(p) + + value = item.get(property_name) + + if isinstance(value, str): + result[display_name] = value + elif isinstance(value, list): + result[display_name] = str(len(value)) + elif value is not None: + result[display_name] = str(value) + + return result + + +def _generic_table_convert(source, row_convert_fn): + if not isinstance(source, list): + source = [source] + + return [row_convert_fn(each) for each in source] + + +def action_group_list_table(results): + if not isinstance(results, list): + results = [results] + + output_results = [] + for result in results: + data = _item_to_ordered_dict(result, 'name', 'resourceGroup', 'groupShortName', 'enabled', 'location', + ('emailReceivers', 'email'), ('smsReceivers', 'sms'), + ('webhookReceivers', 'webhook'), ('armRoleReceivers', 'armrole'), + ('azureAppPushReceivers', 'azureapppush'), ('itsmReceivers', 'itsm'), + ('automationRunbookReceivers', 'automationrunbook'), ('voiceReceivers', 'voice'), + ('logicAppReceivers', 'logicapp'), ('azureFunctionReceivers', 'azurefunction'), + ('eventHubReceivers', 'eventhub')) + + output_results.append(data) + + return output_results + + +def metrics_definitions_table(results): + def row_convert(item): + from collections import OrderedDict + result = OrderedDict() + result['Display Name'] = item['name']['localizedValue'] + result['Metric Name'] = item['name']['value'] + result['Unit'] = item['unit'] + result['Type'] = item['primaryAggregationType'] + result['Dimension Required'] = 'True' if item['isDimensionRequired'] else 'False' + result['Dimensions'] = ', '.join(d['value'] for d in item.get('dimensions', []) or []) + + return result + + return _generic_table_convert(results, row_convert) + + +def metrics_namespaces_table(results): + def row_convert(item): + from collections import OrderedDict + result = OrderedDict() + result['Classification'] = item['classification'] + result['Metric Namespace Name'] = item['properties']['metricNamespaceName'] + return result + return _generic_table_convert(results, row_convert) + + +def metrics_table(results): + from collections import OrderedDict + + def from_time(time_string): + from datetime import datetime + try: + return datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S+00:00').strftime('%Y-%m-%d %H:%M:%S') + except ValueError: + return time_string + + retval = [] + for value_group in results['value']: + name = value_group['name']['localizedValue'] + for series in value_group['timeseries']: + metadata = {m['name']['localizedValue']: m['value'] for m in series['metadatavalues']} + + for data in series['data']: + row = OrderedDict() + row['Timestamp'] = from_time(data['timeStamp']) + row['Name'] = name + for metadata_name, metadata_value in metadata.items(): + row[metadata_name] = metadata_value + + for field in data: + if field == 'timeStamp': + continue + row[field] = data[field] + retval.append(row) + return retval diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/util.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/util.py new file mode 100644 index 00000000000..521fa9268b1 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/util.py @@ -0,0 +1,49 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +# ISO format with explicit indication of timezone +DATE_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' + + +def get_resource_group_location(cli_ctx, name): + from azure.cli.core.commands.client_factory import get_mgmt_service_client + from azure.cli.core.profiles import ResourceType + + # pylint: disable=no-member + return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES).resource_groups.get(name).location + + +# region Autoscale Maps +def get_autoscale_statistic_map(): + from azure.mgmt.monitor.models import MetricStatisticType + return {'avg': MetricStatisticType.average, 'min': MetricStatisticType.min, + 'max': MetricStatisticType.max, 'sum': MetricStatisticType.sum} + + +def get_autoscale_operator_map(): + from azure.mgmt.monitor.models import ComparisonOperationType + return {'==': ComparisonOperationType.equals, '!=': ComparisonOperationType.not_equals, + '>': ComparisonOperationType.greater_than, '>=': ComparisonOperationType.greater_than_or_equal, + '<': ComparisonOperationType.less_than, '<=': ComparisonOperationType.less_than_or_equal} + + +def get_autoscale_aggregation_map(): + from azure.mgmt.monitor.models import TimeAggregationType + return {'avg': TimeAggregationType.average, 'min': TimeAggregationType.minimum, + 'max': TimeAggregationType.maximum, 'total': TimeAggregationType.total, + 'count': TimeAggregationType.count} + + +def get_autoscale_scale_direction_map(): + from azure.mgmt.monitor.models import ScaleDirection + return {'to': ScaleDirection.none, 'out': ScaleDirection.increase, + 'in': ScaleDirection.decrease} + + +def gen_guid(): + import uuid + return uuid.uuid4() +# endregion diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_legacy/validators.py b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/validators.py new file mode 100644 index 00000000000..5f1c53448c9 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/_legacy/validators.py @@ -0,0 +1,412 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.commands.validators import validate_tags, get_default_location_from_resource_group +from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError + +from knack.util import CLIError + + +def process_autoscale_create_namespace(cmd, namespace): + from azure.mgmt.core.tools import parse_resource_id + + validate_tags(namespace) + get_target_resource_validator('resource', required=True, preserve_resource_group_parameter=True)(cmd, namespace) + if not namespace.resource_group_name: + namespace.resource_group_name = parse_resource_id(namespace.resource).get('resource_group', None) + get_default_location_from_resource_group(cmd, namespace) + + +def validate_autoscale_recurrence(namespace): + + def _validate_weekly_recurrence(namespace): + # Construct days + valid_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + days = [] + for partial in namespace.recurrence[1:]: + if len(partial) < 2: + raise CLIError('specifying fewer than 2 characters for day is ambiguous.') + try: + match = next(x for x in valid_days if x.lower().startswith(partial.lower())) + except StopIteration: + raise CLIError("No match for day '{}'.".format(partial)) + days.append(match) + valid_days.remove(match) + + # validate, but don't process start and end time + recurrence_obj = { + "frequency": "Week", + "schedule": { + "time_zone": namespace.timezone, + "days": days, + "hours": [], # will be filled in during custom command + "minutes": [] # will be filled in during custom command + } + } + return recurrence_obj + + valid_recurrence = { + 'week': { + 'usage': '-r week [DAY DAY ...]', + 'validator': _validate_weekly_recurrence + } + } + if namespace.recurrence: + raw_values = namespace.recurrence + try: + delimiter = raw_values[0].lower() + usage = valid_recurrence[delimiter]['usage'] + try: + namespace.recurrence = valid_recurrence[delimiter]['validator'](namespace) + except CLIError as ex: + raise CLIError('{} invalid usage: {}'.format(ex, usage)) + except KeyError: + raise CLIError('invalid usage: -r {{{}}} [ARG ARG ...]'.format(','.join(valid_recurrence))) + + +def validate_autoscale_timegrain(namespace): + from azure.mgmt.monitor.models import MetricTrigger + from azure.cli.command_modules.monitor._legacy.actions import get_period_type + from azure.cli.command_modules.monitor._legacy.util import get_autoscale_statistic_map + + values = namespace.timegrain + if len(values) == 1: + # workaround because CMD.exe eats > character... Allows condition to be + # specified as a quoted expression + values = values[0].split(' ') + name_offset = 0 + try: + time_grain = get_period_type()(values[1]) + name_offset += 1 + except ValueError: + time_grain = get_period_type()('1m') + try: + statistic = get_autoscale_statistic_map()[values[0]] + name_offset += 1 + except KeyError: + statistic = get_autoscale_statistic_map()['avg'] + timegrain = MetricTrigger( + metric_name=None, + metric_resource_uri=None, + time_grain=time_grain, + statistic=statistic, + time_window=None, + time_aggregation=None, + operator=None, + threshold=None + ) + namespace.timegrain = timegrain + + +def get_target_resource_validator(dest, required, preserve_resource_group_parameter=False, alias='resource'): + def _validator(cmd, namespace): + from azure.mgmt.core.tools import is_valid_resource_id + name_or_id = getattr(namespace, dest) + rg = namespace.resource_group_name + res_ns = namespace.namespace + parent = namespace.parent + res_type = namespace.resource_type + + usage_error = CLIError('usage error: --{0} ID | --{0} NAME --resource-group NAME ' + '--{0}-type TYPE [--{0}-parent PARENT] ' + '[--{0}-namespace NAMESPACE]'.format(alias)) + if not name_or_id and required: + raise usage_error + if name_or_id: + if is_valid_resource_id(name_or_id) and any((res_ns, parent, res_type)): + raise usage_error + if not is_valid_resource_id(name_or_id): + from azure.cli.core.commands.client_factory import get_subscription_id + if res_type and '/' in res_type: + res_ns = res_ns or res_type.rsplit('/', 1)[0] + res_type = res_type.rsplit('/', 1)[1] + if not all((rg, res_ns, res_type, name_or_id)): + raise usage_error + + setattr(namespace, dest, + '/subscriptions/{}/resourceGroups/{}/providers/{}/{}{}/{}'.format( + get_subscription_id(cmd.cli_ctx), rg, res_ns, parent + '/' if parent else '', + res_type, name_or_id)) + + del namespace.namespace + del namespace.parent + del namespace.resource_type + if not preserve_resource_group_parameter: + del namespace.resource_group_name + + return _validator + + +def validate_metrics_alert_dimension(namespace): + from azure.cli.command_modules.monitor._legacy.grammar.metric_alert.MetricAlertConditionValidator import dim_op_conversion + for keyword, value in dim_op_conversion.items(): + if namespace.operator == value: + namespace.operator = keyword + + +def validate_metrics_alert_condition(namespace): + from azure.cli.command_modules.monitor._legacy.grammar.metric_alert.MetricAlertConditionValidator import op_conversion, \ + agg_conversion, sens_conversion + for keyword, value in agg_conversion.items(): + if namespace.aggregation == value: + namespace.aggregation = keyword + break + for keyword, value in op_conversion.items(): + if namespace.operator == value: + namespace.operator = keyword + break + + if namespace.condition_type == 'static': + if namespace.threshold is None: + raise RequiredArgumentMissingError('Parameter --threshold is required for static threshold.') + if namespace.operator not in ('=', '!=', '>', '>=', '<', '<='): + raise InvalidArgumentValueError('Parameter --operator {} is invalid for static threshold.'.format( + op_conversion[namespace.operator] + )) + elif namespace.condition_type == 'dynamic': + if namespace.operator not in ('>', '<', '><'): + raise InvalidArgumentValueError('Parameter --operator {} is invalid for dynamic threshold.'.format( + op_conversion[namespace.operator] + )) + if namespace.alert_sensitivity is None: + raise RequiredArgumentMissingError('Parameter --sensitivity is required for dynamic threshold.') + for keyword, value in sens_conversion.items(): + if namespace.alert_sensitivity == value: + namespace.alert_sensitivity = keyword + break + + if namespace.number_of_evaluation_periods is None: + setattr(namespace, 'number_of_evaluation_periods', 4) + + if namespace.number_of_evaluation_periods < 1 or namespace.number_of_evaluation_periods > 6: + raise InvalidArgumentValueError('Parameter --num-periods {} should in range 1-6.'.format( + namespace.number_of_evaluation_periods + )) + + if namespace.min_failing_periods_to_alert is None: + setattr(namespace, 'min_failing_periods_to_alert', min(4, namespace.number_of_evaluation_periods)) + + if namespace.min_failing_periods_to_alert < 1 or namespace.min_failing_periods_to_alert > 6: + raise InvalidArgumentValueError('Parameter --num-violations {} should in range 1-6.'.format( + namespace.min_failing_periods_to_alert + )) + + if namespace.min_failing_periods_to_alert > namespace.number_of_evaluation_periods: + raise InvalidArgumentValueError( + 'Parameter --num-violations {} should be less than or equal to parameter --num-periods {}.'.format( + namespace.min_failing_periods_to_alert, namespace.number_of_evaluation_periods)) + else: + raise NotImplementedError() + + +def validate_diagnostic_settings(cmd, namespace): + from azure.cli.core.commands.client_factory import get_subscription_id + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + + get_target_resource_validator('resource_uri', required=True, preserve_resource_group_parameter=True)(cmd, namespace) + if not namespace.resource_group_name: + namespace.resource_group_name = parse_resource_id(namespace.resource_uri)['resource_group'] + + if namespace.storage_account and not is_valid_resource_id(namespace.storage_account): + namespace.storage_account = resource_id(subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='microsoft.Storage', + type='storageAccounts', + name=namespace.storage_account) + + if namespace.workspace and not is_valid_resource_id(namespace.workspace): + namespace.workspace = resource_id(subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='microsoft.OperationalInsights', + type='workspaces', + name=namespace.workspace) + + if namespace.event_hub and is_valid_resource_id(namespace.event_hub): + namespace.event_hub = parse_resource_id(namespace.event_hub)['name'] + + if namespace.event_hub_rule: + if not is_valid_resource_id(namespace.event_hub_rule): + if not namespace.event_hub: + raise CLIError('usage error: --event-hub-rule ID | --event-hub-rule NAME --event-hub NAME') + # use value from --event-hub if the rule is a name + namespace.event_hub_rule = resource_id( + subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='Microsoft.EventHub', + type='namespaces', + name=namespace.event_hub, + child_type_1='AuthorizationRules', + child_name_1=namespace.event_hub_rule) + elif not namespace.event_hub: + # extract the event hub name from `--event-hub-rule` if provided as an ID + namespace.event_hub = parse_resource_id(namespace.event_hub_rule)['name'] + + if not any([namespace.storage_account, namespace.workspace, namespace.event_hub]): + raise CLIError( + 'usage error - expected one or more: --storage-account NAME_OR_ID | --workspace NAME_OR_ID ' + '| --event-hub NAME_OR_ID | --event-hub-rule ID') + + try: + del namespace.resource_group_name + except AttributeError: + pass + + +def _validate_tags(namespace): + """ Extracts multiple space-separated tags in key[=value] format """ + if isinstance(namespace.tags, list): + tags_dict = {} + for item in namespace.tags: + tags_dict.update(_validate_tag(item)) + namespace.tags = tags_dict + + +def _validate_tag(string): + """ Extracts a single tag in key[=value] format """ + result = {} + if string: + comps = string.split('=', 1) + result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''} + return result + + +def process_action_group_detail_for_creation(namespace): + from azure.mgmt.monitor.models import ActionGroupResource, EmailReceiver, SmsReceiver, WebhookReceiver, \ + ArmRoleReceiver, AzureAppPushReceiver, ItsmReceiver, AutomationRunbookReceiver, \ + VoiceReceiver, LogicAppReceiver, AzureFunctionReceiver, EventHubReceiver + + _validate_tags(namespace) + + ns = vars(namespace) + name = ns['action_group_name'] + receivers = ns.pop('receivers') or [] + action_group_resource_properties = { + 'location': ns.pop('location') or 'Global', # both inputed or 'global' location are available for action group + 'group_short_name': ns.pop('short_name') or name[:12], # '12' is the short name length limitation + 'email_receivers': [r for r in receivers if isinstance(r, EmailReceiver)], + 'sms_receivers': [r for r in receivers if isinstance(r, SmsReceiver)], + 'webhook_receivers': [r for r in receivers if isinstance(r, WebhookReceiver)], + 'arm_role_receivers': [r for r in receivers if isinstance(r, ArmRoleReceiver)], + 'itsm_receivers': [r for r in receivers if isinstance(r, ItsmReceiver)], + 'azure_app_push_receivers': [r for r in receivers if isinstance(r, AzureAppPushReceiver)], + 'automation_runbook_receivers': [r for r in receivers if isinstance(r, AutomationRunbookReceiver)], + 'voice_receivers': [r for r in receivers if isinstance(r, VoiceReceiver)], + 'logic_app_receivers': [r for r in receivers if isinstance(r, LogicAppReceiver)], + 'azure_function_receivers': [r for r in receivers if isinstance(r, AzureFunctionReceiver)], + 'event_hub_receivers': [r for r in receivers if isinstance(r, EventHubReceiver)], + 'tags': ns.get('tags') or None + } + if hasattr(namespace, 'tags'): + del namespace.tags + + ns['action_group'] = ActionGroupResource(**action_group_resource_properties) + + +def validate_metric_dimension(namespace): + + if not namespace.dimension: + return + + if namespace.filters: + raise CLIError('usage: --dimension and --filter parameters are mutually exclusive.') + + namespace.filters = ' and '.join("{} eq '*'".format(d) for d in namespace.dimension) + + +def process_webhook_prop(namespace): + if not isinstance(namespace.webhook_properties, list): + return + + result = {} + for each in namespace.webhook_properties: + if each: + if '=' in each: + key, value = each.split('=', 1) + else: + key, value = each, '' + result[key] = value + + namespace.webhook_properties = result + + +def get_action_group_validator(dest): + def validate_action_groups(cmd, namespace): + action_groups = getattr(namespace, dest, None) + + if not action_groups: + return + + from azure.mgmt.core.tools import is_valid_resource_id, resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + + subscription = get_subscription_id(cmd.cli_ctx) + resource_group = namespace.resource_group_name + for group in action_groups: + if not is_valid_resource_id(group["action_group_id"]): + group["action_group_id"] = resource_id( + subscription=subscription, + resource_group=resource_group, + namespace='microsoft.insights', + type='actionGroups', + name=group["action_group_id"] + ) + return validate_action_groups + + +def get_action_group_id_validator(dest): + def validate_action_group_ids(cmd, namespace): + action_groups = getattr(namespace, dest, None) + + if not action_groups: + return + + from azure.mgmt.core.tools import is_valid_resource_id, resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + + action_group_ids = [] + subscription = get_subscription_id(cmd.cli_ctx) + resource_group = namespace.resource_group_name + for group in action_groups: + if not is_valid_resource_id(group): + group = resource_id( + subscription=subscription, + resource_group=resource_group, + namespace='microsoft.insights', + type='actionGroups', + name=group + ) + action_group_ids.append(group.lower()) + setattr(namespace, dest, action_group_ids) + return validate_action_group_ids + + +def validate_storage_accounts_name_or_id(cmd, namespace): + if namespace.storage_account_ids: + from azure.mgmt.core.tools import is_valid_resource_id, resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + for index, storage_account_id in enumerate(namespace.storage_account_ids): + if not is_valid_resource_id(storage_account_id): + namespace.storage_account_ids[index] = resource_id( + subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, + namespace='Microsoft.Storage', + type='storageAccounts', + name=storage_account_id + ) + + +def validate_loganalytics_workspace_search_table_name(namespace): + if namespace.table_name and not namespace.table_name.endswith("_SRCH"): + raise CLIError('usage: The table name needs to end with _SRCH') + + +def validate_loganalytics_workspace_restore_table_name(namespace): + if namespace.table_name and not namespace.table_name.endswith("_RST"): + raise CLIError('usage: The table name needs to end with _RST') + + +def process_subscription_id(cmd, namespace): + from azure.cli.core.commands.client_factory import get_subscription_id + namespace.subscription_id = get_subscription_id(cmd.cli_ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/_params.py b/src/azure-cli/azure/cli/command_modules/monitor/_params.py index 639b90f9dff..86acc6d47b9 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/_params.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/_params.py @@ -15,7 +15,7 @@ from azure.cli.command_modules.monitor.validators import ( validate_loganalytics_workspace_search_table_name, validate_loganalytics_workspace_restore_table_name, validate_autoscale_recurrence, validate_autoscale_timegrain, get_action_group_validator, - get_action_group_id_validator, validate_metric_dimension, validate_storage_accounts_name_or_id) + validate_metric_dimension, validate_storage_accounts_name_or_id) from azure.cli.command_modules.monitor.actions import get_date_midnight_type from knack.arguments import CLIArgumentType @@ -88,14 +88,6 @@ def load_arguments(self, _): with self.argument_context('monitor metrics alert create', arg_group=None) as c: c.argument('actions', options_list=['--action', '-a'], action=MetricAlertAddAction, nargs='+', validator=get_action_group_validator('actions')) - with self.argument_context('monitor metrics alert update', arg_group='Action') as c: - c.argument('add_actions', options_list='--add-action', action=MetricAlertAddAction, nargs='+', validator=get_action_group_validator('add_actions')) - c.argument('remove_actions', nargs='+', validator=get_action_group_id_validator('remove_actions')) - - with self.argument_context('monitor metrics alert update', arg_group='Condition') as c: - c.argument('add_conditions', options_list='--add-condition', action=MetricAlertConditionAction, nargs='+') - c.argument('remove_conditions', nargs='+') - with self.argument_context('monitor metrics alert dimension create', arg_group=None) as c: c.argument('dimension_name', options_list=['--name', '-n'], help='Name of the dimension.') diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/__init__.py index 5a9d61963d6..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/__init__.py @@ -6,6 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/account/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/account/__init__.py index db73033039b..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/account/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/account/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/__init__.py index 38254460a56..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._enable_receiver import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/identity/__init__.py index 6e361c3c498..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/identity/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/identity/__init__.py @@ -6,9 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._assign import * -from ._remove import * -from ._show import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/test_notifications/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/test_notifications/__init__.py index a6df9f5a835..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/test_notifications/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/action_group/test_notifications/__init__.py @@ -6,7 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/__init__.py index fb13093004c..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/__init__.py @@ -6,8 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._list import * -from ._list_categories import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/alert/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/alert/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/activity_log/alert/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/autoscale/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/autoscale/__init__.py index 56240e6757e..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/autoscale/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/autoscale/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._show_predictive_metric import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/dashboard/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/dashboard/__init__.py index 2d1a2078686..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/dashboard/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/dashboard/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/categories/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/categories/__init__.py index 2df85698253..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/categories/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/categories/__init__.py @@ -6,8 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._list import * -from ._show import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/diagnostic_settings/subscription/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/__init__.py index 5a9d61963d6..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/__init__.py @@ -6,6 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/__init__.py index db73033039b..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py index 3a074471e35..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/cluster/identity/__init__.py @@ -6,10 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._assign import * -from ._remove import * -from ._show import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py index 10a024b2268..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/query_pack/query/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._search import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/__init__.py index 2a09dda8590..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/__init__.py @@ -6,21 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._failback import * -from ._failover import * -from ._get_schema import * -from ._get_shared_keys import * -from ._list import * -from ._list_available_service_tier import * -from ._list_deleted_workspaces import * -from ._list_link_target import * -from ._list_management_groups import * -from ._list_usages import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/data_export/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py index 3a074471e35..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/identity/__init__.py @@ -6,10 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._assign import * -from ._remove import * -from ._show import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py index db73033039b..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_service/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/linked_storage/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py index edd1a889c3c..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/pack/__init__.py @@ -6,9 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._disable import * -from ._enable import * -from ._list import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/saved_search/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/__init__.py index eb0a528490b..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/__init__.py @@ -6,13 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._migrate import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py index 77a46665663..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_analytics/workspace/table/search_job/__init__.py @@ -6,7 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._cancel import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_profiles/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_profiles/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_profiles/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/log_profiles/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/__init__.py index 92c07af8d7c..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._list import * -from ._list_definitions import * -from ._list_namespaces import * -from ._list_sub import * -from ._list_sub_definitions import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/alert/__init__.py index c401f439385..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/alert/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/metrics/alert/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/__init__.py index db73033039b..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/__init__.py @@ -6,12 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py index f32b66e3eeb..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._delete import * -from ._list import * -from ._show import * -from ._update import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py index 2df85698253..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/private_link_resource/__init__.py @@ -6,8 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._list import * -from ._show import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py index 2d1a2078686..754cbc4a253 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/aaz/latest/monitor/private_link_scope/scoped_resource/__init__.py @@ -6,11 +6,4 @@ # -------------------------------------------------------------------------------------------- # pylint: skip-file -# flake8: noqa - -from .__cmd_group import * -from ._create import * -from ._delete import * -from ._list import * -from ._show import * -from ._wait import * +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/commands.py b/src/azure-cli/azure/cli/command_modules/monitor/commands.py index 9e34e4f4f32..30b5d8eaf49 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/commands.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/commands.py @@ -11,7 +11,6 @@ def load_command_table(self, _): cf_autoscale, cf_action_groups, cf_event_categories, cf_metric_alerts, cf_log_analytics_workspace, cf_log_analytics_linked_storage) - from .transformers import (action_group_list_table) from .validators import (process_autoscale_create_namespace) from ._exception_handler import exception_handler @@ -78,48 +77,12 @@ def load_command_table(self, _): with self.command_group('monitor action-group', action_group_sdk, custom_command_type=action_group_custom) as g: g.wait_command('wait') - from .operations.action_groups import ActionGroupCreate, ActionGroupUpdate, ActionGroupTestNotificationCreate - from .aaz.latest.monitor.action_group import Show, List, EnableReceiver - self.command_table['monitor action-group create'] = ActionGroupCreate(loader=self, - table_transformer=action_group_list_table) - self.command_table['monitor action-group show'] = Show(loader=self, - table_transformer=action_group_list_table) - self.command_table['monitor action-group list'] = List(loader=self, - table_transformer=action_group_list_table) - self.command_table['monitor action-group update'] = ActionGroupUpdate(loader=self, - table_transformer=action_group_list_table) - self.command_table['monitor action-group enable-receiver'] = \ - EnableReceiver(loader=self, table_transformer=action_group_list_table) - - self.command_table['monitor action-group test-notifications create'] = \ - ActionGroupTestNotificationCreate(loader=self, table_transformer=action_group_list_table) - - from .operations.action_groups_identity import AGIdentityAssign, AGIdentityRemove, AGIdentityShow - self.command_table['monitor action-group identity assign'] = AGIdentityAssign(loader=self) - self.command_table['monitor action-group identity remove'] = AGIdentityRemove(loader=self) - self.command_table['monitor action-group identity show'] = AGIdentityShow(loader=self) - with self.command_group('monitor activity-log', activity_log_sdk) as g: g.custom_command('list', 'list_activity_log') - from .operations.activity_log_alerts import ActivityLogAlertCreate, ActivityLogAlertUpdate, \ - ActivityLogAlertActionGroupAdd, ActivityLogAlertActionGroupRemove, \ - ActivityLogAlertScopeAdd, ActivityLogAlertScopeRemove - self.command_table['monitor activity-log alert create'] = ActivityLogAlertCreate(loader=self) - self.command_table['monitor activity-log alert update'] = ActivityLogAlertUpdate(loader=self) - self.command_table['monitor activity-log alert action-group add'] = ActivityLogAlertActionGroupAdd(loader=self) - self.command_table['monitor activity-log alert action-group remove'] = \ - ActivityLogAlertActionGroupRemove(loader=self) - self.command_table['monitor activity-log alert scope add'] = ActivityLogAlertScopeAdd(loader=self) - self.command_table['monitor activity-log alert scope remove'] = ActivityLogAlertScopeRemove(loader=self) - with self.command_group('monitor autoscale', autoscale_sdk, custom_command_type=autoscale_custom) as g: g.custom_command('create', 'autoscale_create', validator=process_autoscale_create_namespace) - # g.generic_update_command('update', custom_func_name='autoscale_update', custom_func_type=autoscale_custom) - from .operations.autoscale_settings import AutoScaleShow, AutoScaleList, AutoScaleUpdate - self.command_table['monitor autoscale show'] = AutoScaleShow(loader=self) - self.command_table['monitor autoscale list'] = AutoScaleList(loader=self) - self.command_table['monitor autoscale update'] = AutoScaleUpdate(loader=self) + # autoscale show/list/update are auto-discovered from operations tree with self.command_group('monitor autoscale profile', autoscale_sdk, custom_command_type=autoscale_custom) as g: g.custom_command('create', 'autoscale_profile_create') @@ -134,17 +97,7 @@ def load_command_table(self, _): g.custom_command('delete', 'autoscale_rule_delete') g.custom_command('copy', 'autoscale_rule_copy') - from .operations.diagnostics_settings import DiagnosticSettingsCreate, DiagnosticSettingsShow, \ - DiagnosticSettingsList, DiagnosticSettingsDelete, DiagnosticSettingsUpdate - self.command_table['monitor diagnostic-settings create'] = DiagnosticSettingsCreate(loader=self) - self.command_table['monitor diagnostic-settings show'] = DiagnosticSettingsShow(loader=self) - self.command_table['monitor diagnostic-settings list'] = DiagnosticSettingsList(loader=self) - self.command_table['monitor diagnostic-settings delete'] = DiagnosticSettingsDelete(loader=self) - self.command_table['monitor diagnostic-settings update'] = DiagnosticSettingsUpdate(loader=self) - - from .operations.diagnostics_settings import DiagnosticSettingsCategoryShow, DiagnosticSettingsCategoryList - self.command_table['monitor diagnostic-settings categories show'] = DiagnosticSettingsCategoryShow(loader=self) - self.command_table['monitor diagnostic-settings categories list'] = DiagnosticSettingsCategoryList(loader=self) + # diagnostic-settings commands are auto-discovered from operations tree with self.command_group('monitor metrics') as g: from .transformers import metrics_table, metrics_definitions_table, metrics_namespaces_table @@ -153,8 +106,7 @@ def load_command_table(self, _): g.command('list-namespaces', 'list_namespaces', is_preview=True, command_type=monitor_custom, table_transformer=metrics_namespaces_table) with self.command_group("monitor metrics alert") as g: - from .operations.metric_alert import MetricsAlertUpdate - self.command_table["monitor metrics alert update"] = MetricsAlertUpdate(loader=self) + # metrics alert update is auto-discovered from operations tree g.custom_command("create", "create_metric_alert", custom_command_type=alert_custom) with self.command_group('monitor metrics alert dimension') as g: @@ -177,26 +129,20 @@ def load_command_table(self, _): with self.command_group('monitor log-analytics workspace table search-job', custom_command_type=log_analytics_workspace_custom) as g: g.custom_command('create', 'create_log_analytics_workspace_table_search_job', supports_no_wait=True) - from .operations.log_analytics_workspace import WorkspaceTableSearchJobCancel - self.command_table['monitor log-analytics workspace table search-job cancel'] = \ - WorkspaceTableSearchJobCancel(loader=self) + # table search-job cancel is auto-discovered from operations tree with self.command_group('monitor log-analytics workspace table restore', custom_command_type=log_analytics_workspace_custom) as g: g.custom_command('create', 'create_log_analytics_workspace_table_restore', supports_no_wait=True) - from .operations.log_analytics_workspace import WorkspaceDataExportCreate, WorkspaceDataExportUpdate - self.command_table['monitor log-analytics workspace data-export create'] = WorkspaceDataExportCreate(loader=self) - self.command_table['monitor log-analytics workspace data-export update'] = WorkspaceDataExportUpdate(loader=self) + # workspace data-export create/update are auto-discovered from operations tree with self.command_group('monitor log-analytics workspace saved-search', custom_command_type=log_analytics_workspace_custom) as g: g.custom_command('create', 'create_log_analytics_workspace_saved_search') g.custom_command('update', 'update_log_analytics_workspace_saved_search') - from .operations.log_analytics_linked_storage_account import WorkspaceLinkedStorageAccountCreate - self.command_table['monitor log-analytics workspace linked-storage create'] = WorkspaceLinkedStorageAccountCreate( - loader=self) + # workspace linked-storage create is auto-discovered from operations tree with self.command_group('monitor log-analytics workspace linked-storage', custom_command_type=log_analytics_linked_storage_custom) as g: g.custom_command('add', 'add_log_analytics_workspace_linked_storage_accounts') @@ -205,9 +151,4 @@ def load_command_table(self, _): with self.command_group('monitor', metric_alert_sdk, custom_command_type=monitor_general_custom) as g: g.custom_command('clone', 'clone_existed_settings', is_preview=True) - from .operations.private_link_scope import PrivateLinkScopeCreate, ConnectionDelete, ConnectionShow, ConnectionApprove, ConnectionReject - self.command_table["monitor private-link-scope create"] = PrivateLinkScopeCreate(loader=self) - self.command_table["monitor private-link-scope private-endpoint-connection delete"] = ConnectionDelete(loader=self) - self.command_table["monitor private-link-scope private-endpoint-connection show"] = ConnectionShow(loader=self) - self.command_table["monitor private-link-scope private-endpoint-connection approve"] = ConnectionApprove(loader=self) - self.command_table["monitor private-link-scope private-endpoint-connection reject"] = ConnectionReject(loader=self) + # private-link-scope commands are auto-discovered from operations tree diff --git a/src/azure-cli/azure/cli/command_modules/monitor/custom.py b/src/azure-cli/azure/cli/command_modules/monitor/custom.py index 7c37796989c..e94e814d847 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/custom.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/custom.py @@ -21,7 +21,7 @@ def list_activity_log(cmd, correlation_id=None, resource_group=None, resource_id logger.info('OData Filter: %s', odata_filters) logger.info('Select Filter: %s', select_filters) - from .aaz.latest.monitor.activity_log import List + from .aaz.latest.monitor.activity_log._list import List # activity_log = client.list(filter=odata_filters, select=select_filters) activity_log = List(cli_ctx=cmd.cli_ctx)(command_args={ "filter": odata_filters, @@ -124,7 +124,7 @@ def list_metrics(cmd, resource, timespan = '{}/{}'.format(start_time, end_time) - from .aaz.latest.monitor.metrics import List + from .aaz.latest.monitor.metrics._list import List return List(cli_ctx=cmd.cli_ctx)(command_args={ "resource_uri": resource, "timespan": quote_plus(timespan), @@ -140,7 +140,7 @@ def list_metrics(cmd, resource, def list_definations(cmd, resource_uri, metricnamespace=None): - from .aaz.latest.monitor.metrics import ListDefinitions + from .aaz.latest.monitor.metrics._list_definitions import ListDefinitions return ListDefinitions(cli_ctx=cmd.cli_ctx)(command_args={ "resource_uri": resource_uri, "metricnamespace": metricnamespace @@ -148,7 +148,7 @@ def list_definations(cmd, resource_uri, metricnamespace=None): def list_namespaces(cmd, resource_uri, start_time=None): - from .aaz.latest.monitor.metrics import ListNamespaces + from .aaz.latest.monitor.metrics._list_namespaces import ListNamespaces return ListNamespaces(cli_ctx=cmd.cli_ctx)(command_args={ "resource_uri": resource_uri, "start_time": start_time diff --git a/src/azure-cli/azure/cli/command_modules/monitor/linter_exclusions.yml b/src/azure-cli/azure/cli/command_modules/monitor/linter_exclusions.yml index 32987c1ce93..cdf6469514e 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/linter_exclusions.yml +++ b/src/azure-cli/azure/cli/command_modules/monitor/linter_exclusions.yml @@ -1,4 +1,5 @@ --- +# Pre-existing parameter exclusions monitor activity-log alert update: parameters: enabled: @@ -31,4 +32,167 @@ monitor action-group update: azure_function_receivers: rule_exclusions: - option_length_too_long -... \ No newline at end of file +# Commands below are not new — they were re-registered via AAZ operations/latest/ +# during the optimized-loading refactor, causing the linter diff to flag them. +monitor activity-log alert scope add: + rule_exclusions: + - missing_command_example +monitor activity-log alert action-group add: + rule_exclusions: + - missing_command_example +monitor log-profiles update: + rule_exclusions: + - missing_command_example +monitor diagnostic-settings update: + rule_exclusions: + - missing_command_example +monitor action-group enable-receiver: + rule_exclusions: + - missing_command_example +monitor diagnostic-settings subscription update: + rule_exclusions: + - missing_command_example +monitor activity-log list: + rule_exclusions: + - missing_command_test_coverage +monitor action-group wait: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale create: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale profile create: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale profile delete: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale profile list: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale profile list-timezones: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale profile show: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale rule copy: + rule_exclusions: + - missing_command_test_coverage + - missing_command_example +monitor autoscale rule create: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale rule delete: + rule_exclusions: + - missing_command_test_coverage +monitor autoscale rule list: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace recover: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace linked-storage add: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace linked-storage remove: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace saved-search create: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace saved-search update: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace table create: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace table update: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace table restore create: + rule_exclusions: + - missing_command_test_coverage +monitor log-analytics workspace table search-job create: + rule_exclusions: + - missing_command_test_coverage +monitor metrics list: + rule_exclusions: + - missing_command_test_coverage + parameters: + metadata: + rule_exclusions: + - missing_parameter_test_coverage + dimension: + rule_exclusions: + - missing_parameter_test_coverage + aggregation: + rule_exclusions: + - missing_parameter_test_coverage + metrics: + rule_exclusions: + - missing_parameter_test_coverage + orderby: + rule_exclusions: + - missing_parameter_test_coverage + top: + rule_exclusions: + - missing_parameter_test_coverage + start_time: + rule_exclusions: + - missing_parameter_test_coverage + end_time: + rule_exclusions: + - missing_parameter_test_coverage + offset: + rule_exclusions: + - missing_parameter_test_coverage + interval: + rule_exclusions: + - missing_parameter_test_coverage +monitor metrics list-definitions: + rule_exclusions: + - missing_command_test_coverage +monitor metrics list-namespaces: + rule_exclusions: + - missing_command_test_coverage + parameters: + resource_uri: + rule_exclusions: + - missing_parameter_test_coverage + start_time: + rule_exclusions: + - missing_parameter_test_coverage +monitor metrics "create": + rule_exclusions: + - missing_command_test_coverage +monitor: + parameters: + location: + rule_exclusions: + - missing_parameter_test_coverage + tags: + rule_exclusions: + - missing_parameter_test_coverage +monitor metrics: + parameters: + namespace: + rule_exclusions: + - missing_parameter_test_coverage +monitor metrics alert: + parameters: + rule_name: + rule_exclusions: + - missing_parameter_test_coverage + severity: + rule_exclusions: + - missing_parameter_test_coverage + window_size: + rule_exclusions: + - missing_parameter_test_coverage + evaluation_frequency: + rule_exclusions: + - missing_parameter_test_coverage + auto_mitigate: + rule_exclusions: + - missing_parameter_test_coverage diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups.py index f25bcaa605f..c10aabccb6b 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/action_groups.py @@ -3,15 +3,11 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=protected-access -from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg -from azure.cli.core.commands.validators import validate_tags -from azure.cli.core.azclierror import ValidationError -from azure.cli.command_modules.monitor.actions import AAZCustomListArg -from ..aaz.latest.monitor.action_group import Create as _ActionGroupCreate, Update as _ActionGroupUpdate -from ..aaz.latest.monitor.action_group.test_notifications import Create as _ActionGroupTestNotificationCreate def update_action_group_receivers(args): + from azure.cli.core.azclierror import ValidationError + syntax = { 'email': 'NAME EMAIL_ADDRESS [usecommonalertschema]', 'sms': 'NAME COUNTRY_CODE PHONE_NUMBER', @@ -122,266 +118,3 @@ def update_action_group_receivers(args): except IndexError: raise ValidationError('--action {}'.format(syntax[type_name])) - - -class ActionGroupCreate(_ActionGroupCreate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.receiver_actions = AAZCustomListArg( - options=["--actions"], - singular_options=["--action", "-a"], - help=''' - Add receivers to the action group during the creation.\n\n - Usage: --action TYPE NAME [ARG ...]\n\n - Email:\n\n - Format: --action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n - Example: --action email bob bob@contoso.com\n\n - SMS:\n\n - Format: --action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --action sms charli 1 5551234567\n\n - Webhook:\n\n - Format: --action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n - Example: --action webhook alert_hook https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n - Arm Role:\n\n - Format: --action armrole NAME ROLE_ID [usecommonalertschema]\n\n - Example: --action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n - Azure App Push:\n\n - Format: --action azureapppush NAME EMAIL_ADDRESS\n\n - Example: --action azureapppush test_apppush bob@contoso.com\n\n - ITSM:\n\n - Format: --action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n - Example: --action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n - Automation runbook:\n\n - Format: --action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n - Example: --action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n - Voice:\n\n - Format: --action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --action voice charli 1 4441234567\n\n - Logic App:\n\n - Format: --action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n - Example: --action logicapp test_logicapp test_rsrc http://callback\n\n - Azure Function:\n\n - Format: --action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n - Example: --action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n - Event Hub:\n\n - Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n - Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n - Multiple actions can be specified by using more than one `--add-action` argument.\n\n - 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n - If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well. - ''', - arg_group="Actions", - ) - args_schema.receiver_actions.Element = AAZCustomListArg() - args_schema.receiver_actions.Element.Element = AAZStrArg() - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.enabled = True - validate_tags(args) - action_group_name = args.action_group_name.to_serialized_data() - if not has_value(args.location): - # both inputed or 'global' location are available for action group - args.location = "Global" - if not has_value(args.group_short_name): - # '12' is the short name length limitation - args.group_short_name = action_group_name[:12] - if not has_value(args.receiver_actions): - return - update_action_group_receivers(args) - - -class ActionGroupUpdate(_ActionGroupUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.receiver_actions = AAZCustomListArg( - options=["--add-actions"], - singular_options=["--add-action", "-a"], - help=''' - Add receivers to the action group.\n\n - Usage: --add-action TYPE NAME [ARG ...]\n\n - Email:\n\n - Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n - Example: --add-action email bob bob@contoso.com\n\n - SMS:\n\n - Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --add-action sms charli 1 5551234567\n\n - Webhook:\n\n - Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n - Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n - Arm Role:\n\n - Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n - Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n - Azure App Push:\n\n - Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n - Example: --add-action azureapppush test_apppush bob@contoso.com\n\n - ITSM:\n\n - Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n - Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n - Automation runbook:\n\n - Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n - Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n - Voice:\n\n - Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --add-action voice charli 1 4441234567\n\n - Logic App:\n\n - Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n - Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n - Azure Function:\n\n - Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n - Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n - Event Hub:\n\n - Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n - Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n - Multiple actions can be specified by using more than one `--add-action` argument.\n\n - 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n - If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', - arg_group="Actions", - ) - args_schema.receiver_actions.Element = AAZListArg() - args_schema.receiver_actions.Element.Element = AAZStrArg() - - args_schema.receiver_remove_list = AAZListArg( - options=["--remove-action", "-r"], - help="Remove receivers from the action group. Accept space-separated list of receiver names.", - arg_group="Actions", - ) - args_schema.receiver_remove_list.Element = AAZStrArg() - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.enabled = True - update_action_group_receivers(args) - - def pre_instance_update(self, instance): - args = self.ctx.args - receiver_remove_list = set() - if has_value(args.receiver_remove_list): - receiver_remove_list = set(args.receiver_remove_list.to_serialized_data()) - - def filter_receivers(collection): - return [item for item in collection if item.name.to_serialized_data() not in receiver_remove_list] - - instance.properties.incident_receivers = filter_receivers(instance.properties.incident_receivers) - instance.properties.incident_receivers.extend(args.incident_receivers) - args.incident_receivers = instance.properties.incident_receivers - - instance.properties.email_receivers = filter_receivers(instance.properties.email_receivers) - instance.properties.email_receivers.extend(args.email_receivers) - args.email_receivers = instance.properties.email_receivers - - instance.properties.sms_receivers = filter_receivers(instance.properties.sms_receivers) - instance.properties.sms_receivers.extend(args.sms_receivers) - args.sms_receivers = instance.properties.sms_receivers - - instance.properties.webhook_receivers = filter_receivers(instance.properties.webhook_receivers) - instance.properties.webhook_receivers.extend(args.webhook_receivers) - args.webhook_receivers = instance.properties.webhook_receivers - - instance.properties.arm_role_receivers = filter_receivers(instance.properties.arm_role_receivers) - instance.properties.arm_role_receivers.extend(args.arm_role_receivers) - args.arm_role_receivers = instance.properties.arm_role_receivers - - instance.properties.azure_app_push_receivers = filter_receivers(instance.properties.azure_app_push_receivers) - instance.properties.azure_app_push_receivers.extend(args.azure_app_push_receivers) - args.azure_app_push_receivers = instance.properties.azure_app_push_receivers - - instance.properties.itsm_receivers = filter_receivers(instance.properties.itsm_receivers) - instance.properties.itsm_receivers.extend(args.itsm_receivers) - args.itsm_receivers = instance.properties.itsm_receivers - - instance.properties.automation_runbook_receivers = \ - filter_receivers(instance.properties.automation_runbook_receivers) - instance.properties.automation_runbook_receivers.extend(args.automation_runbook_receivers) - args.automation_runbook_receivers = instance.properties.automation_runbook_receivers - - instance.properties.voice_receivers = filter_receivers(instance.properties.voice_receivers) - instance.properties.voice_receivers.extend(args.voice_receivers) - args.voice_receivers = instance.properties.voice_receivers - - instance.properties.logic_app_receivers = filter_receivers(instance.properties.logic_app_receivers) - instance.properties.logic_app_receivers.extend(args.logic_app_receivers) - args.logic_app_receivers = instance.properties.logic_app_receivers - - instance.properties.azure_function_receivers = filter_receivers(instance.properties.azure_function_receivers) - instance.properties.azure_function_receivers.extend(args.azure_function_receivers) - args.azure_function_receivers = instance.properties.azure_function_receivers - - instance.properties.event_hub_receivers = filter_receivers(instance.properties.event_hub_receivers) - instance.properties.event_hub_receivers.extend(args.event_hub_receivers) - args.event_hub_receivers = instance.properties.event_hub_receivers - - -class ActionGroupTestNotificationCreate(_ActionGroupTestNotificationCreate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.arm_role_receivers._registered = False - args_schema.automation_runbook_receivers._registered = False - args_schema.azure_app_push_receivers._registered = False - args_schema.azure_function_receivers._registered = False - args_schema.email_receivers._registered = False - - args_schema.event_hub_receivers._registered = False - args_schema.itsm_receivers._registered = False - args_schema.logic_app_receivers._registered = False - args_schema.sms_receivers._registered = False - args_schema.voice_receivers._registered = False - args_schema.webhook_receivers._registered = False - args_schema.receiver_actions = AAZCustomListArg( - options=["--add-actions"], - singular_options=["--add-action", "-a"], - help=''' - Add receivers to the action group.\n\n - Usage: --add-action TYPE NAME [ARG ...]\n\n - Email:\n\n - Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n - Example: --add-action email bob bob@contoso.com\n\n - SMS:\n\n - Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --add-action sms charli 1 5551234567\n\n - Webhook:\n\n - Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n - Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n - Arm Role:\n\n - Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n - Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n - Azure App Push:\n\n - Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n - Example: --add-action azureapppush test_apppush bob@contoso.com\n\n - ITSM:\n\n - Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n - Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n - Automation runbook:\n\n - Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n - Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n - Voice:\n\n - Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n - Example: --add-action voice charli 1 4441234567\n\n - Logic App:\n\n - Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n - Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n - Azure Function:\n\n - Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n - Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n - Event Hub:\n\n - Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n - Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n - Multiple actions can be specified by using more than one `--add-action` argument.\n\n - 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n - If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', - ) - args_schema.receiver_actions.Element = AAZListArg() - args_schema.receiver_actions.Element.Element = AAZStrArg() - return args_schema - - def pre_operations(self): - args = self.ctx.args - update_action_group_receivers(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py index 7bd9158d0a6..5c355166e17 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py @@ -3,17 +3,12 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=protected-access, line-too-long -from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg, AAZBoolArg, register_command, \ - AAZResourceIdArg, AAZResourceIdArgFormat -from azure.cli.command_modules.monitor.actions import AAZCustomListArg -from azure.cli.core.azclierror import ValidationError -from ..aaz.latest.monitor.activity_log.alert import Create as _ActivityLogAlertCreate, \ - Update as _ActivityLogAlertUpdate def _get_alert_settings_for_alert(cmd, resource_group_name, activity_log_alert_name, throw_if_missing=True): from azure.core.exceptions import HttpResponseError - from ..aaz.latest.monitor.activity_log.alert import Show as ActivityLogAlertGet + from azure.cli.core.azclierror import ValidationError + from ..aaz.latest.monitor.activity_log.alert._show import Show as ActivityLogAlertGet try: return ActivityLogAlertGet(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, @@ -44,6 +39,9 @@ def _normalize_condition_for_alert(condition_instance): def process_condition_parameter_for_alert(args): + from azure.cli.core.aaz import has_value + from azure.cli.core.azclierror import ValidationError + if not has_value(args.condition): return expression = args.condition.to_serialized_data() @@ -74,6 +72,8 @@ def process_condition_parameter_for_alert(args): def process_webhook_properties(args): + from azure.cli.core.aaz import has_value + result = {} if not has_value(args.webhook_properties_list): return result @@ -88,387 +88,7 @@ def process_webhook_properties(args): return result -class ActivityLogAlertCreate(_ActivityLogAlertCreate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.enabled._registered = False - args_schema.location._registered = False - args_schema.action_groups._registered = False - args_schema.scopes._registered = False - args_schema.scope_ui = AAZListArg( - options=["--scope", "-s"], - help="A list of strings that will be used as prefixes." + ''' - The alert rule will only apply to activity logs with resourceIDs that fall under one of - these prefixes. If not provided, the subscriptionId will be used. - ''', - ) - args_schema.scope_ui.Element = AAZStrArg() - - args_schema.disable = AAZBoolArg( - options=["--disable"], - help="Disable the activity log alert rule after it is created.", - default=False, - ) - args_schema.condition = AAZCustomListArg( - options=["--condition", "-c"], - help="The condition that will cause the alert rule to activate. " - "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' - The possible values for the field are 'resourceId', 'category', 'caller', - 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', - 'subStatus', 'resourceType', or anything beginning with 'properties'. - ''' - ) - args_schema.condition.Element = AAZStrArg() - - args_schema.action_group_ids = AAZListArg( - options=["--action-group", "-a"], - help="Add an action group. Accepts space-separated action group identifiers. " - "The identifier can be the action group's name or its resource ID.", - ) - args_schema.action_group_ids.Element = AAZResourceIdArg( - fmt=AAZResourceIdArgFormat( - template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", - ) - ) - - args_schema.webhook_properties_list = AAZCustomListArg( - options=['--webhook-properties', '-w'], - help="Space-separated webhook properties in 'key[=value]' format. " - "These properties are associated with the action groups added in this command." + ''' - For any webhook receiver in these action group, this data is appended to the webhook - payload. To attach different webhook properties to different action groups, add the - action groups in separate update-action commands. - ''' - ) - args_schema.webhook_properties_list.Element = AAZStrArg() - - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.location = "Global" - process_condition_parameter_for_alert(args) - webhook_properties = process_webhook_properties(args) - if not has_value(args.scope_ui): - from azure.mgmt.core.tools import resource_id - from azure.cli.core.commands.client_factory import get_subscription_id - # args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx), - # resource_group=args.resource_group)] - # service check - args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx))] - else: - args.scopes = args.scope_ui.to_serialized_data() - if _get_alert_settings_for_alert(self, args.resource_group, args.activity_log_alert_name, - throw_if_missing=False): - raise ValidationError( - 'The activity log alert {} already exists in resource group {}.'.format(args.activity_log_alert_name, - args.resource_group)) - if not has_value(args.all_of): - args.all_of.append({ - "field": "category", - "equals": "ServiceHealth", - }) - else: - current_all_of = args.all_of.to_serialized_data() - category_found = False - for item in current_all_of: - if item.get("field", None) == "category": - category_found = True - break - if not category_found: - args.all_of.append({ - "field": "category", - "equals": "ServiceHealth", - }) - # Add action groups - action_group_rids = set() - if has_value(args.action_group_ids): - action_group_rids = set(args.action_group_ids.to_serialized_data()) - args.action_groups = [] - for i in action_group_rids: - args.action_groups.append({ - "action_group_id": i, - "webhook_properties": webhook_properties - }) - if has_value(args.disable): - args.enabled = not args.disable - - -class ActivityLogAlertUpdate(_ActivityLogAlertUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.action_groups._registered = False - args_schema.scopes._registered = False - args_schema.condition = AAZCustomListArg( - options=["--condition", "-c"], - help="The condition that will cause the alert rule to activate. " - "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' - The possible values for the field are 'resourceId', 'category', 'caller', - 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', - 'subStatus', 'resourceType', or anything beginning with 'properties'. - ''' - ) - args_schema.condition.Element = AAZStrArg() - return args_schema - - def pre_operations(self): - args = self.ctx.args - process_condition_parameter_for_alert(args) - if not has_value(args.all_of): - args.all_of.append({ - "field": "category", - "equals": "ServiceHealth", - }) - else: - current_all_of = args.all_of.to_serialized_data() - category_found = False - for item in current_all_of: - if item.get("field", None) == "category": - category_found = True - break - if not category_found: - args.all_of.append({ - "field": "category", - "equals": "ServiceHealth", - }) - - -@register_command("monitor activity-log alert action-group add") -class ActivityLogAlertActionGroupAdd(_ActivityLogAlertUpdate): - """Add action groups to this activity log alert rule. It can also be used to overwrite existing webhook properties of particular action groups. - - :example: Add an action group and specify webhook properties. - az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ - --action /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insight - s/actionGroups/{ActionGroup} \\ - --webhook-properties usage=test owner=jane - - :example: Overwite an existing action group's webhook properties. - az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ - -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti - onGroups/{ActionGroup} \\ - --webhook-properties usage=test owner=john - - :example: Remove webhook properties from an existing action group. - az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ - -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti - onGroups/{ActionGroup} - - :example: Add new action groups but prevent the command from accidently overwrite existing webhook properties - az monitor activity-log alert action-group add -n AlertName -g ResourceGroup --strict \\ - --action-group ResourceIDList - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.action_groups._registered = False - args_schema.all_of._registered = False - args_schema.description._registered = False - args_schema.enabled._registered = False - args_schema.scopes._registered = False - args_schema.tags._registered = False - - args_schema.action_group_ids = AAZListArg( - options=["--action-group", "-a"], - help="The names or the resource ids of the action groups to be added.", - required=True - ) - args_schema.action_group_ids.Element = AAZResourceIdArg( - fmt=AAZResourceIdArgFormat( - template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", - ) - ) - - args_schema.webhook_properties_list = AAZCustomListArg( - options=['--webhook-properties', '-w'], - help="Space-separated webhook properties in 'key[=value]' format. " - "These properties are associated with the action groups added in this command." + ''' - For any webhook receiver in these action group, these data are appended to the webhook - payload. To attach different webhook properties to different action groups, add the - action groups in separate update-action commands. - ''' - ) - args_schema.webhook_properties_list.Element = AAZStrArg() - - args_schema.reset = AAZBoolArg( - options=["--reset"], - help="Remove all the existing action groups before add new conditions.", - default=False - ) - args_schema.strict = AAZBoolArg( - options=["--strict"], - help="Fails the command if an action group to be added will change existing webhook properties.", - default=False, - ) - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - webhook_properties = process_webhook_properties(args) - - rids = args.action_group_ids.to_serialized_data() - - if has_value(args.reset) and args.reset: - action_groups = [] - for rid in rids: - action_groups.append({ - "action_group_id": rid, - "webhook_properties": webhook_properties - }) - instance.properties.actions.action_groups = action_groups - else: - action_groups_map = {} - for item in instance.properties.actions.action_groups: - ac_id = item.actionGroupId.to_serialized_data() - # service returned action group id can be uppercase - action_groups_map[ac_id.lower()] = { - "action_group_id": ac_id, - "webhook_properties": dict(item.webhookProperties) - } - - for rid in rids: - if args.strict: - for key, item in action_groups_map.items(): - if key.lower() == rid.lower() and webhook_properties != item["webhook_properties"]: - raise ValueError( - 'Fails to override webhook properties of action group {} in strict mode.'.format(rid)) - - action_groups_map[rid.lower()] = { - "action_group_id": rid, - "webhook_properties": webhook_properties - } - - action_groups = list(action_groups_map.values()) - instance.properties.actions.action_groups = action_groups - - -@register_command("monitor activity-log alert action-group remove") -class ActivityLogAlertActionGroupRemove(_ActivityLogAlertUpdate): - """Remove action groups from this activity log alert rule. - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.action_groups._registered = False - args_schema.all_of._registered = False - args_schema.description._registered = False - args_schema.enabled._registered = False - args_schema.scopes._registered = False - args_schema.tags._registered = False - args_schema.action_group_ids = AAZListArg( - options=["--action-group", "-a"], - required=True, - help="The names or the resource ids of the action groups to be added.", - ) - args_schema.action_group_ids.Element = AAZStrArg() - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - action_group_ids = args.action_group_ids.to_serialized_data() - if len(action_group_ids) == 1 and action_group_ids[0] == '*': - instance.properties.actions.actionGroups = [] - else: - # normalize the action group ids - rids = _normalize_names(self.cli_ctx, args.action_group_ids.to_serialized_data(), args.resource_group, - 'microsoft.insights', 'actionGroups') - action_groups = [] - for item in instance.properties.actions.actionGroups: - ac_id = item.actionGroupId.to_serialized_data() - found = False - for rid in rids: - if ac_id.lower() == rid.lower(): # service returned action group id can be uppercase - found = True - break - if not found: - action_groups.append(item) - instance.properties.actions.actionGroups = action_groups - - -@register_command("monitor activity-log alert scope add") -class ActivityLogAlertScopeAdd(_ActivityLogAlertUpdate): - """Add scopes to this activity log alert rule. - - :example: Add scopes to this activity log alert rule. - az monitor activity-log alert scope add --name MyActivityLogAlerts --resource-group - MyResourceGroup --scope /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myRG - /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx- - xxxxxxxxxxxx/resourceGroups/myRG/Microsoft.KeyVault/vaults/mykey - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.enabled._registered = False - args_schema.all_of._registered = False - args_schema.action_groups._registered = False - args_schema.tags._registered = False - args_schema.description._registered = False - args_schema.scopes._registered = False - args_schema.scope_ui = AAZListArg( - options=["--scope", "-s"], - required=True, - help="List of scopes to add. Each scope could be a resource ID or a subscription ID.", - ) - args_schema.scope_ui.Element = AAZStrArg() - - args_schema.reset = AAZBoolArg( - options=["--reset"], - help="Remove all the existing action groups before add new conditions.", - default=False - ) - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - new_scopes = set() if args.reset else set(instance.properties.scopes.to_serialized_data()) - for scope in args.scope_ui.to_serialized_data(): - new_scopes.add(scope) - - args.scopes = list(new_scopes) - - -@register_command("monitor activity-log alert scope remove") -class ActivityLogAlertScopeRemove(_ActivityLogAlertUpdate): - """Removes scopes from this activity log alert rule. - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.enabled._registered = False - args_schema.all_of._registered = False - args_schema.action_groups._registered = False - args_schema.tags._registered = False - args_schema.description._registered = False - args_schema.scopes._registered = False - args_schema.scope_ui = AAZListArg( - options=["--scope", "-s"], - required=True, - help="The scopes to remove.", - ) - args_schema.scope_ui.Element = AAZStrArg() - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - new_scopes = set(instance.properties.scopes.to_serialized_data()) - for scope in args.scope_ui.to_serialized_data(): - try: - new_scopes.remove(scope) - except KeyError: - pass - args.scopes = list(new_scopes) - - -def _normalize_names(cli_ctx, resource_names, resource_group, namespace, resource_type): +def normalize_names(cli_ctx, resource_names, resource_group, namespace, resource_type): """Normalize a group of resource names. Returns a set of resource ids. Throws if any of the name can't be correctly converted to a resource id.""" from azure.mgmt.core.tools import is_valid_resource_id, resource_id diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py index 0320c0e0c4d..20af97cf9ce 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py @@ -6,12 +6,6 @@ import json from knack.log import get_logger from knack.util import CLIError -from azure.cli.core.aaz import has_value, AAZListArg, AAZStrArg, AAZIntArg, AAZBoolArg -from azure.cli.command_modules.monitor.actions import AAZCustomListArg -from azure.cli.command_modules.monitor._autoscale_util import get_autoscale_default_profile -from ..aaz.latest.monitor.autoscale import Create as _AutoScaleCreate, Update as _AutoScaleUpdate, \ - Show as _AutoScaleShow, List as _AutoScaleList -from azure.cli.command_modules.network.custom import _convert_to_snake_case from azure.cli.core.azclierror import InvalidArgumentValueError logger = get_logger(__name__) @@ -20,27 +14,6 @@ DEFAULT_PROFILE_NAME = 'default' -class AutoScaleCreate(_AutoScaleCreate): - - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - if has_value(self.ctx.vars.instance.properties.name): - self.ctx.vars.instance.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) - return result - - -class AutoScaleShow(_AutoScaleShow): - - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied - if has_value(self.ctx.vars.instance.properties.name): - self.ctx.vars.instance.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) - return result - - def update_add_actions(args): add_actions = [] for add_action_item in args.add_actions: @@ -82,176 +55,6 @@ def update_remove_actions(args): return remove_actions -class AutoScaleUpdate(_AutoScaleUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.notifications._registered = False - args_schema.profiles._registered = False - args_schema.target_resource_location._registered = False - args_schema.target_resource_uri._registered = False - args_schema.count = AAZIntArg( - options=["--count"], - help='The numer of instances to use. If used with --min/max-count, the default number of instances to use.', - arg_group="Instance Limit", - ) - args_schema.min_count = AAZIntArg( - options=["--min-count"], - help='The minimum number of instances.', - arg_group="Instance Limit", - ) - args_schema.max_count = AAZIntArg( - options=["--max-count"], - help='The maximum number of instances.', - arg_group="Instance Limit", - ) - args_schema.add_actions = AAZCustomListArg( - options=["--add-actions"], - singular_options=['--add-action', '-a'], - help="Add an action to fire when a scaling event occurs." + ''' - Usage: --add-action TYPE KEY [ARG ...] - Email: --add-action email bob@contoso.com ann@contoso.com - Webhook: --add-action webhook https://www.contoso.com/alert apiKey=value - Webhook: --add-action webhook https://www.contoso.com/alert?apiKey=value - Multiple actions can be specified by using more than one `--add-action` argument. - ''', - arg_group="Notification", - ) - args_schema.add_actions.Element = AAZCustomListArg() - args_schema.add_actions.Element.Element = AAZStrArg() - - args_schema.remove_actions = AAZCustomListArg( - options=["--remove-actions"], - singular_options=['--remove-action', '-r'], - help="Remove one or more actions." + ''' - Usage: --remove-action TYPE KEY [KEY ...] - Email: --remove-action email bob@contoso.com ann@contoso.com - Webhook: --remove-action webhook https://contoso.com/alert https://alerts.contoso.com. - ''', - arg_group="Notification", - ) - args_schema.remove_actions.Element = AAZCustomListArg() - args_schema.remove_actions.Element.Element = AAZStrArg() - - args_schema.email_administrator = AAZBoolArg( - options=["--email-administrator"], - help='Send email to subscription administrator on scaling.', - arg_group="Notification", - ) - args_schema.email_coadministrators = AAZBoolArg( - options=["--email-coadministrators"], - help='Send email to subscription co-administrators on scaling.', - arg_group="Notification", - ) - - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - add_actions = update_add_actions(args) - remove_actions = update_remove_actions(args) - if has_value(args.count) or has_value(args.min_count) or has_value(args.max_count): - default_profile = get_autoscale_default_profile(instance) - curr_count = default_profile["capacity"]["default"] - curr_min = default_profile["capacity"]["minimum"] - curr_max = default_profile["capacity"]["maximum"] - is_fixed_count = curr_count == curr_min and curr_count == curr_max - - # check for special case where count is used to indicate fixed value and only - # count is updated - if has_value(args.count) and is_fixed_count and not has_value(args.min_count) and not has_value(args.max_count): - args.min_count = args.count.to_serialized_data() - args.max_count = args.count.to_serialized_data() - - count = curr_count if not has_value(args.count) else args.count.to_serialized_data() - min_count = curr_min if not has_value(args.min_count) else args.min_count.to_serialized_data() - max_count = curr_max if not has_value(args.max_count) else args.max_count.to_serialized_data() - - # There may be multiple "default" profiles. All need to updated. - for profile in instance.properties.profiles: - if has_value(profile.fixed_date): - continue - if has_value(profile.recurrence): - try: - # portal denotes the "default" pairs by using a JSON string for their name - # so if it can be decoded, we know this is a default profile - json.loads(profile.name.to_serialized_data()) - except ValueError: - continue - profile.capacity.default = str(count) - profile.capacity.minimum = str(min_count) - profile.capacity.maximum = str(max_count) - updated_notification = None - if instance.properties.notifications: - retained_notification = [] - for x in instance.properties.notifications: - note = x.to_serialized_data() - if note['operation'].lower() == 'scale': - updated_notification = note - else: - retained_notification.append(note) - instance.properties.notifications = retained_notification - else: - instance.properties.notifications = [] - - if updated_notification is None: - updated_notification = { - "operation": "scale", - "email": { - "customEmails": [] - }, - "webhooks": [] - } - - # process removals - if len(remove_actions) > 0: - removed_emails, removed_webhooks = _parse_action_removals(remove_actions) - updated_notification['email']['customEmails'] = \ - [x for x in updated_notification['email']['customEmails'] if x not in removed_emails] - updated_notification['webhooks'] = \ - [x for x in updated_notification['webhooks'] if x['serviceUri'] not in removed_webhooks] - - # process additions - for action in add_actions: - if action["key"] == "email": - for email in action["value"]["customEmails"]: - updated_notification['email']['customEmails'].append(email) - elif action["key"] == "webhook": - updated_notification['webhooks'].append(action["value"]) - if has_value(args.email_administrator): - updated_notification['email']['sendToSubscriptionAdministrator'] = args.email_administrator.to_serialized_data() - if has_value(args.email_coadministrators): - updated_notification['email']['sendToSubscriptionCoAdministrators'] = args.email_coadministrators.to_serialized_data() - - instance.properties.notifications.append(updated_notification) - - if has_value(args.scale_look_ahead_time) and not has_value(args.scale_mode) \ - and not has_value(instance.properties.predictive_autoscale_policy): - raise InvalidArgumentValueError('scale-mode is required for setting scale-look-ahead-time.') - - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied - if has_value(self.ctx.vars.instance.properties.name): - self.ctx.vars.instance.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) - return result - - -class AutoScaleList(_AutoScaleList): - - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied - for value in self.ctx.vars.instance.value: - if has_value(value.properties): - value.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance.value, client_flatten=True) - next_link = self.deserialize_output(self.ctx.vars.instance.next_link) - return result, next_link - - # pylint: disable=too-many-locals def autoscale_create(cmd, resource, count, autoscale_name=None, resource_group_name=None, min_count=None, max_count=None, location=None, tags=None, disabled=None, @@ -311,6 +114,7 @@ def autoscale_create(cmd, resource, count, autoscale_name=None, resource_group_n if not (min_count == count and max_count == count): logger.warning('Follow up with `az monitor autoscale rule create` to add scaling rules.') + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._create import AutoScaleCreate return AutoScaleCreate(cli_ctx=cmd.cli_ctx)(command_args=args) @@ -395,6 +199,9 @@ def _build_recurrence(base, time): def get_autoscale_instance(cmd, resource_group_name, autoscale_name): + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._show import AutoScaleShow + from azure.cli.command_modules.network.custom import _convert_to_snake_case + rets = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "autoscale_name": autoscale_name @@ -434,12 +241,14 @@ def autoscale_profile_create(cmd, autoscale_name, resource_group_name, profile_n timezone) else: _create_fixed_profile(autoscale_settings, profile_name, start, end, capacity, copy_rules, timezone) + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._update import AutoScaleUpdate updated_rets = AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) profile = next(x for x in updated_rets["profiles"] if x["name"] == profile_name) return profile def autoscale_profile_list(cmd, autoscale_name, resource_group_name): + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._show import AutoScaleShow autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "autoscale_name": autoscale_name}) @@ -459,55 +268,57 @@ def autoscale_profile_list_timezones(cmd, client, offset=None, search_query=None def autoscale_profile_show(cmd, autoscale_name, resource_group_name, profile_name): + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._show import AutoScaleShow autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "autoscale_name": autoscale_name}) return _identify_profile_cg(autoscale_settings["profiles"], profile_name) -class AutoScaleProfileDelete(_AutoScaleUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.profile_name = AAZStrArg( - options=["--profile-name"], - help='Name of the autoscale profile.', - required=True, - registered=False, - ) - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - profile_name = args.profile_name.to_serialized_data() - default_profile = get_autoscale_default_profile(instance) - - def _should_retain_profile(profile): - name = profile.name.to_serialized_data() - try: - name = json.loads(profile.name.to_serialized_data())['for'] - except ValueError: - pass - return name.lower() != profile_name.lower() +def autoscale_profile_delete(cmd, autoscale_name, resource_group_name, profile_name): + from azure.cli.core.aaz import has_value, AAZStrArg, AAZUndefined + from azure.cli.command_modules.monitor._autoscale_util import get_autoscale_default_profile + from ..aaz.latest.monitor.autoscale._update import Update as _AutoScaleUpdate + + class AutoScaleProfileDelete(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.profile_name = AAZStrArg( + options=["--profile-name"], + help='Name of the autoscale profile.', + required=True, + registered=False, + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + profile_name_val = args.profile_name.to_serialized_data() + default_profile = get_autoscale_default_profile(instance) - retained_profiles = [x for x in instance.properties.profiles if _should_retain_profile(x)] - instance.properties.profiles = retained_profiles + def _should_retain_profile(profile): + name = profile.name.to_serialized_data() + try: + name = json.loads(profile.name.to_serialized_data())['for'] + except ValueError: + pass + return name.lower() != profile_name_val.lower() - # if we removed the last "default" of a recurring pair, we need to preserve it - new_default = get_autoscale_default_profile(instance) - if not new_default: - instance.properties.profiles.append(default_profile) + retained_profiles = [x for x in instance.properties.profiles if _should_retain_profile(x)] + instance.properties.profiles = retained_profiles - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - if has_value(self.ctx.vars.instance.properties.name): - self.ctx.vars.instance.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) - return result + new_default = get_autoscale_default_profile(instance) + if not new_default: + instance.properties.profiles.append(default_profile) + def _output(self, *args, **kwargs): + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result -def autoscale_profile_delete(cmd, autoscale_name, resource_group_name, profile_name): AutoScaleProfileDelete(cli_ctx=cmd.cli_ctx)(command_args={ "autoscale_name": autoscale_name, "resource_group": resource_group_name, @@ -585,6 +396,7 @@ def preprocess_for_spring_cloud_service(): } } profile["rules"].append(rule) + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._update import AutoScaleUpdate updated_rets = AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) updated_profile = _identify_profile_cg(updated_rets["profiles"], profile_name) # determine if there are unbalanced rules @@ -600,6 +412,7 @@ def preprocess_for_spring_cloud_service(): def autoscale_rule_list(cmd, autoscale_name, resource_group_name, profile_name=DEFAULT_PROFILE_NAME): + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._show import AutoScaleShow autoscale_settings = AutoScaleShow(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "autoscale_name": autoscale_name}) @@ -624,59 +437,61 @@ def autoscale_rule_delete(cmd, autoscale_name, resource_group_name, index, profi continue remained_rule.append(rule) profile["rules"] = remained_rule + from azure.cli.command_modules.monitor.operations.latest.monitor.autoscale._update import AutoScaleUpdate AutoScaleUpdate(cli_ctx=cmd.cli_ctx)(command_args=autoscale_settings) -class AutoScaleRuleCopy(_AutoScaleUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.source_profile = AAZStrArg( - options=["--source-profile"], - help='Name of the autoscale profile.', - required=True, - registered=False, - default=DEFAULT_PROFILE_NAME - ) - args_schema.dest_profile = AAZStrArg( - options=["--dest-profile"], - help='Name of the autoscale profile.', - required=True, - registered=False, - ) - args_schema.index = AAZListArg( - options=["--index"], - help="Space-separated list of rule indices to remove, or '*' to clear all rules.", - registered=False, - ) - args_schema.index.Element = AAZStrArg() - return args_schema - - def pre_instance_update(self, instance): - args = self.ctx.args - source_profile_name = args.source_profile.to_serialized_data() - dest_profile_name = args.dest_profile.to_serialized_data() - index = args.index.to_serialized_data() - - src_profile = _identify_profile(instance.properties.profiles, source_profile_name) - dst_profile = _identify_profile(instance.properties.profiles, dest_profile_name) - if '*' in index: - dst_profile.rules = src_profile.rules - else: - for i in index: - dst_profile.rules.append(src_profile.rules[int(i)]) - - def _output(self, *args, **kwargs): - from azure.cli.core.aaz import AAZUndefined - if has_value(self.ctx.vars.instance.properties.name): - self.ctx.vars.instance.properties.name = AAZUndefined - result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) - return result - - def autoscale_rule_copy(cmd, autoscale_name, resource_group_name, dest_profile, index, source_profile=DEFAULT_PROFILE_NAME): + from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg, AAZUndefined + from ..aaz.latest.monitor.autoscale._update import Update as _AutoScaleUpdate + + class AutoScaleRuleCopy(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.source_profile = AAZStrArg( + options=["--source-profile"], + help='Name of the autoscale profile.', + required=True, + registered=False, + default=DEFAULT_PROFILE_NAME + ) + args_schema.dest_profile = AAZStrArg( + options=["--dest-profile"], + help='Name of the autoscale profile.', + required=True, + registered=False, + ) + args_schema.index = AAZListArg( + options=["--index"], + help="Space-separated list of rule indices to remove, or '*' to clear all rules.", + registered=False, + ) + args_schema.index.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + source_profile_name = args.source_profile.to_serialized_data() + dest_profile_name = args.dest_profile.to_serialized_data() + index_val = args.index.to_serialized_data() + + src_profile = _identify_profile(instance.properties.profiles, source_profile_name) + dst_profile = _identify_profile(instance.properties.profiles, dest_profile_name) + if '*' in index_val: + dst_profile.rules = src_profile.rules + else: + for i in index_val: + dst_profile.rules.append(src_profile.rules[int(i)]) + + def _output(self, *args, **kwargs): + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result + AutoScaleRuleCopy(cli_ctx=cmd.cli_ctx)(command_args={ "autoscale_name": autoscale_name, "resource_group": resource_group_name, diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/diagnostics_settings.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/diagnostics_settings.py index fc7ce2b4787..d3c33a388f8 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/diagnostics_settings.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/diagnostics_settings.py @@ -3,15 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from ..aaz.latest.monitor.diagnostic_settings import Create as _DiagnosticSettingsCreate -from ..aaz.latest.monitor.diagnostic_settings import List as _DiagnosticSettingsList -from ..aaz.latest.monitor.diagnostic_settings import Show as _DiagnosticSettingsShow -from ..aaz.latest.monitor.diagnostic_settings import Delete as _DiagnosticSettingsDelete -from ..aaz.latest.monitor.diagnostic_settings import Update as _DiagnosticSettingsUpdate -from ..aaz.latest.monitor.diagnostic_settings.categories import List as _DiagnosticSettingsCategoryList -from ..aaz.latest.monitor.diagnostic_settings.categories import Show as _DiagnosticSettingsCategoryShow from knack.util import CLIError -from azure.cli.core.azclierror import ArgumentUsageError def create_resource_parameters(arg_schema, arg_group=None): @@ -69,169 +61,6 @@ def update_resource_parameters(ctx, alias="resource"): f"{parent + '/' if parent else ''}{res_type}/{name_or_id}" -class DiagnosticSettingsCreate(_DiagnosticSettingsCreate): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema, arg_group="Target Resource") - - from azure.cli.core.aaz import AAZBoolArg - arg_schema.export_to_resource_specific = AAZBoolArg( - options=['--export-to-resource-specific'], - help="Indicate that the export to LA must be done to a resource specific table, a.k.a. " - "dedicated or fixed schema table, as opposed to the default dynamic schema table called " - "AzureDiagnostics. This argument is effective only when the argument --workspace is also given. " - "Allowed values: false, true." - ) - arg_schema.log_analytics_destination_type._registered = False # pylint:disable=protected-access - arg_schema.service_bus_rule_id._registered = False # pylint:disable=protected-access - return arg_schema - - def pre_operations(self): - ctx = self.ctx - from azure.cli.core.aaz import has_value - from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id - update_resource_parameters(ctx) - args = ctx.args - rg = args.resource_group_name.to_serialized_data() - - if not has_value(rg): - rg = parse_resource_id(args.resource.to_serialized_data())['resource_group'] - args.resource_group_name = rg - - storage_account = args.storage_account.to_serialized_data() - if has_value(storage_account) and not is_valid_resource_id(storage_account): - storage_account = resource_id(subscription=ctx.subscription_id, - resource_group=rg, - namespace='microsoft.Storage', - type='storageAccounts', - name=storage_account) - args.storage_account = storage_account - - workspace = args.workspace.to_serialized_data() - if has_value(workspace) and not is_valid_resource_id(workspace): - workspace = resource_id(subscription=ctx.subscription_id, - resource_group=rg, - namespace='microsoft.OperationalInsights', - type='workspaces', - name=workspace) - args.workspace = workspace - - event_hub = args.event_hub.to_serialized_data() - if has_value(event_hub) and is_valid_resource_id(event_hub): - event_hub = parse_resource_id(event_hub)['name'] - args.event_hub = event_hub - - event_hub_rule = args.event_hub_rule.to_serialized_data() - if has_value(event_hub_rule): - if not is_valid_resource_id(event_hub_rule): - if not has_value(event_hub): - raise CLIError('usage error: --event-hub-rule ID | --event-hub-rule NAME --event-hub NAME') - # use value from --event-hub if the rule is a name - event_hub_rule = resource_id( - subscription=ctx.subscription_id, - resource_group=rg, - namespace='Microsoft.EventHub', - type='namespaces', - name=event_hub, - child_type_1='AuthorizationRules', - child_name_1=event_hub_rule) - args.event_hub_rule = event_hub_rule - - elif not has_value(event_hub): - # extract the event hub name from `--event-hub-rule` if provided as an ID - event_hub = parse_resource_id(event_hub_rule)['name'] - args.event_hub = event_hub - if not (has_value(storage_account) or has_value(workspace) or has_value(event_hub)): - raise CLIError( - 'usage error - expected one or more: --storage-account NAME_OR_ID | --workspace NAME_OR_ID ' - '| --event-hub NAME_OR_ID | --event-hub-rule ID') - - export_to_resource_specific = args.export_to_resource_specific.to_serialized_data() - if has_value(export_to_resource_specific) and export_to_resource_specific: - args.log_analytics_destination_type = 'Dedicated' - if not has_value(workspace): - raise ArgumentUsageError('usage error: --workspace and --export-to-specific-resource') - else: - args.log_analytics_destination_type = None - - -class DiagnosticSettingsShow(_DiagnosticSettingsShow): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema, arg_group="Target Resource") - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - -class DiagnosticSettingsList(_DiagnosticSettingsList): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema) - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - -class DiagnosticSettingsDelete(_DiagnosticSettingsDelete): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema, arg_group="Target Resource") - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - -class DiagnosticSettingsUpdate(_DiagnosticSettingsUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema, arg_group="Target Resource") - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - -class DiagnosticSettingsCategoryList(_DiagnosticSettingsCategoryList): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema) - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - -class DiagnosticSettingsCategoryShow(_DiagnosticSettingsCategoryShow): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - arg_schema = super()._build_arguments_schema(*args, **kwargs) - create_resource_parameters(arg_schema) - return arg_schema - - def pre_operations(self): - ctx = self.ctx - update_resource_parameters(ctx) - - # pylint: disable=unused-argument, line-too-long def create_diagnostics_settings(client, name, resource_uri, logs=None, diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/general_operations.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/general_operations.py index be42b4f2fac..d30eb706fb2 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/general_operations.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/general_operations.py @@ -2,10 +2,11 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.command_modules.monitor.operations.monitor_clone_util import _clone_monitor_metrics_alerts def clone_existed_settings(cmd, source_resource, target_resource, always_clone=False, monitor_types=None): + from azure.cli.command_modules.monitor.operations.monitor_clone_util import _clone_monitor_metrics_alerts + result = {} monitor_types = set(monitor_types) if "metricsAlert" in monitor_types: diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_create.py new file mode 100644 index 00000000000..3548f135f2c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_create.py @@ -0,0 +1,87 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import has_value, AAZStrArg +from azure.cli.core.commands.validators import validate_tags +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group._create import Create as _ActionGroupCreate +from azure.cli.command_modules.monitor.operations.action_groups import update_action_group_receivers + + +class ActionGroupCreate(_ActionGroupCreate): + + def __init__(self, *args, **kwargs): + from azure.cli.command_modules.monitor.transformers import action_group_list_table + super().__init__(*args, **kwargs) + self.table_transformer = action_group_list_table + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.receiver_actions = AAZCustomListArg( + options=["--actions"], + singular_options=["--action", "-a"], + help=''' + Add receivers to the action group during the creation.\n\n + Usage: --action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --action webhook alert_hook https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well. + ''', + arg_group="Actions", + ) + args_schema.receiver_actions.Element = AAZCustomListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.enabled = True + validate_tags(args) + action_group_name = args.action_group_name.to_serialized_data() + if not has_value(args.location): + # both inputed or 'global' location are available for action group + args.location = "Global" + if not has_value(args.group_short_name): + # '12' is the short name length limitation + args.group_short_name = action_group_name[:12] + if not has_value(args.receiver_actions): + return + update_action_group_receivers(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_update.py new file mode 100644 index 00000000000..04df53f3035 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/_update.py @@ -0,0 +1,140 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group._update import Update as _ActionGroupUpdate +from azure.cli.command_modules.monitor.operations.action_groups import update_action_group_receivers + + +class ActionGroupUpdate(_ActionGroupUpdate): + + def __init__(self, *args, **kwargs): + from azure.cli.command_modules.monitor.transformers import action_group_list_table + super().__init__(*args, **kwargs) + self.table_transformer = action_group_list_table + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.receiver_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action", "-a"], + help=''' + Add receivers to the action group.\n\n + Usage: --add-action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --add-action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --add-action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', + arg_group="Actions", + ) + args_schema.receiver_actions.Element = AAZListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + + args_schema.receiver_remove_list = AAZListArg( + options=["--remove-action", "-r"], + help="Remove receivers from the action group. Accept space-separated list of receiver names.", + arg_group="Actions", + ) + args_schema.receiver_remove_list.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.enabled = True + update_action_group_receivers(args) + + def pre_instance_update(self, instance): + args = self.ctx.args + receiver_remove_list = set() + if has_value(args.receiver_remove_list): + receiver_remove_list = set(args.receiver_remove_list.to_serialized_data()) + + def filter_receivers(collection): + return [item for item in collection if item.name.to_serialized_data() not in receiver_remove_list] + + instance.properties.incident_receivers = filter_receivers(instance.properties.incident_receivers) + instance.properties.incident_receivers.extend(args.incident_receivers) + args.incident_receivers = instance.properties.incident_receivers + + instance.properties.email_receivers = filter_receivers(instance.properties.email_receivers) + instance.properties.email_receivers.extend(args.email_receivers) + args.email_receivers = instance.properties.email_receivers + + instance.properties.sms_receivers = filter_receivers(instance.properties.sms_receivers) + instance.properties.sms_receivers.extend(args.sms_receivers) + args.sms_receivers = instance.properties.sms_receivers + + instance.properties.webhook_receivers = filter_receivers(instance.properties.webhook_receivers) + instance.properties.webhook_receivers.extend(args.webhook_receivers) + args.webhook_receivers = instance.properties.webhook_receivers + + instance.properties.arm_role_receivers = filter_receivers(instance.properties.arm_role_receivers) + instance.properties.arm_role_receivers.extend(args.arm_role_receivers) + args.arm_role_receivers = instance.properties.arm_role_receivers + + instance.properties.azure_app_push_receivers = filter_receivers(instance.properties.azure_app_push_receivers) + instance.properties.azure_app_push_receivers.extend(args.azure_app_push_receivers) + args.azure_app_push_receivers = instance.properties.azure_app_push_receivers + + instance.properties.itsm_receivers = filter_receivers(instance.properties.itsm_receivers) + instance.properties.itsm_receivers.extend(args.itsm_receivers) + args.itsm_receivers = instance.properties.itsm_receivers + + instance.properties.automation_runbook_receivers = \ + filter_receivers(instance.properties.automation_runbook_receivers) + instance.properties.automation_runbook_receivers.extend(args.automation_runbook_receivers) + args.automation_runbook_receivers = instance.properties.automation_runbook_receivers + + instance.properties.voice_receivers = filter_receivers(instance.properties.voice_receivers) + instance.properties.voice_receivers.extend(args.voice_receivers) + args.voice_receivers = instance.properties.voice_receivers + + instance.properties.logic_app_receivers = filter_receivers(instance.properties.logic_app_receivers) + instance.properties.logic_app_receivers.extend(args.logic_app_receivers) + args.logic_app_receivers = instance.properties.logic_app_receivers + + instance.properties.azure_function_receivers = filter_receivers(instance.properties.azure_function_receivers) + instance.properties.azure_function_receivers.extend(args.azure_function_receivers) + args.azure_function_receivers = instance.properties.azure_function_receivers + + instance.properties.event_hub_receivers = filter_receivers(instance.properties.event_hub_receivers) + instance.properties.event_hub_receivers.extend(args.event_hub_receivers) + args.event_hub_receivers = instance.properties.event_hub_receivers diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_assign.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_assign.py new file mode 100644 index 00000000000..48c606fa49f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_assign.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group.identity._assign \ + import Assign as _AGIdentityAssign + + +class AGIdentityAssign(_AGIdentityAssign): + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + self.ActionGroupsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class InstanceUpdateByJson(_AGIdentityAssign.InstanceUpdateByJson): + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_remove.py new file mode 100644 index 00000000000..66a5d113dcc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_remove.py @@ -0,0 +1,28 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group.identity._remove \ + import Remove as _AGIdentityRemove + + +class AGIdentityRemove(_AGIdentityRemove): + def _execute_operations(self): + self.pre_operations() + self.ActionGroupsGet(ctx=self.ctx)() + self.pre_instance_update(self.ctx.selectors.subresource.get()) + self.InstanceUpdateByJson(ctx=self.ctx)() + self.post_instance_update(self.ctx.selectors.subresource.get()) + self.ActionGroupsCreateOrUpdate(ctx=self.ctx)() + self.post_operations() + + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result + + class InstanceUpdateByJson(_AGIdentityRemove.InstanceUpdateByJson): + def __call__(self, *args, **kwargs): + self._update_instance(self.ctx.selectors.subresource.get()) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_show.py new file mode 100644 index 00000000000..22d46282742 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/identity/_show.py @@ -0,0 +1,15 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group.identity._show \ + import Show as _AGIdentityShow + + +class AGIdentityShow(_AGIdentityShow): + def _output(self, *args, **kwargs): + result = self.deserialize_output(self.ctx.selectors.subresource.get(), client_flatten=True) + return result diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/_create.py new file mode 100644 index 00000000000..5ee6ec01def --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/action_group/test_notifications/_create.py @@ -0,0 +1,86 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import AAZStrArg, AAZListArg +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.action_group.test_notifications._create \ + import Create as _ActionGroupTestNotificationCreate +from azure.cli.command_modules.monitor.operations.action_groups import update_action_group_receivers + + +class ActionGroupTestNotificationCreate(_ActionGroupTestNotificationCreate): + + def __init__(self, *args, **kwargs): + from azure.cli.command_modules.monitor.transformers import action_group_list_table + super().__init__(*args, **kwargs) + self.table_transformer = action_group_list_table + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.arm_role_receivers._registered = False + args_schema.automation_runbook_receivers._registered = False + args_schema.azure_app_push_receivers._registered = False + args_schema.azure_function_receivers._registered = False + args_schema.email_receivers._registered = False + + args_schema.event_hub_receivers._registered = False + args_schema.itsm_receivers._registered = False + args_schema.logic_app_receivers._registered = False + args_schema.sms_receivers._registered = False + args_schema.voice_receivers._registered = False + args_schema.webhook_receivers._registered = False + args_schema.receiver_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action", "-a"], + help=''' + Add receivers to the action group.\n\n + Usage: --add-action TYPE NAME [ARG ...]\n\n + Email:\n\n + Format: --add-action email NAME EMAIL_ADDRESS [usecommonalertschema]\n\n + Example: --add-action email bob bob@contoso.com\n\n + SMS:\n\n + Format: --add-action sms NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action sms charli 1 5551234567\n\n + Webhook:\n\n + Format: --add-action webhook NAME URI [useaadauth OBJECT_ID IDENTIFIER URI] [usecommonalertschema]\n\n + Example: --add-action https://www.contoso.com/alert useaadauth testobj http://identifier usecommonalertschema\n\n + Arm Role:\n\n + Format: --add-action armrole NAME ROLE_ID [usecommonalertschema]\n\n + Example: --add-action armole owner_role 8e3af657-a8ff-443c-a75c-2fe8c4bcb635\n\n + Azure App Push:\n\n + Format: --add-action azureapppush NAME EMAIL_ADDRESS\n\n + Example: --add-action azureapppush test_apppush bob@contoso.com\n\n + ITSM:\n\n + Format: --add-action itsm NAME WORKSPACE_ID CONNECTION_ID TICKET_CONFIGURATION REGION\n\n + Example: --add-action itsm test_itsm test_workspace test_conn ticket_blob useast\n\n + Automation runbook:\n\n + Format: --add-action automationrunbook NAME AUTOMATION_ACCOUNT_ID RUNBOOK_NAME WEBHOOK_RESOURCE_ID SERVICE_URI [isglobalrunbook] [usecommonalertschema]\n\n + Example: --add-action automationrunbook test_runbook test_acc test_book test_webhook test_rsrc http://example.com isglobalrunbook usecommonalertschema\n\n + Voice:\n\n + Format: --add-action voice NAME COUNTRY_CODE PHONE_NUMBER\n\n + Example: --add-action voice charli 1 4441234567\n\n + Logic App:\n\n + Format: --add-action logicapp NAME RESOURCE_ID CALLBACK_URL [usecommonalertschema]\n\n + Example: --add-action logicapp test_logicapp test_rsrc http://callback\n\n + Azure Function:\n\n + Format: --add-action azurefunction NAME FUNCTION_APP_RESOURCE_ID FUNCTION_NAME HTTP_TRIGGER_URL [usecommonalertschema]\n\n + Example: --add-action azurefunction test_function test_rsrc test_func http://trigger usecommonalertschema\n\n + Event Hub:\n\n + Format: --action eventhub NAME SUBSCRIPTION_ID EVENT_HUB_NAME_SPACE EVENT_HUB_NAME [usecommonalertschema]\n\n + Example: --action eventhub test_eventhub 5def922a-3ed4-49c1-b9fd-05ec533819a3 eventhubNameSpace testEventHubName usecommonalertschema\n\n + Multiple actions can be specified by using more than one `--add-action` argument.\n\n + 'useaadauth', 'isglobalrunbook' and 'usecommonalertschema' are optional arguements that only need to be passed to set the respective parameter to True.\n\n + If the 'useaadauth' argument is passed, then the OBJECT_ID and IDENTIFIER_URI values are required as well.''', + ) + args_schema.receiver_actions.Element = AAZListArg() + args_schema.receiver_actions.Element.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + update_action_group_receivers(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_create.py new file mode 100644 index 00000000000..533acadf315 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_create.py @@ -0,0 +1,126 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg, AAZBoolArg, \ + AAZResourceIdArg, AAZResourceIdArgFormat +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._create \ + import Create as _ActivityLogAlertCreate +from azure.cli.command_modules.monitor.operations.activity_log_alerts import ( + _get_alert_settings_for_alert, + process_condition_parameter_for_alert, + process_webhook_properties, +) +from azure.cli.core.azclierror import ValidationError + + +class ActivityLogAlertCreate(_ActivityLogAlertCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.location._registered = False + args_schema.action_groups._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + help="A list of strings that will be used as prefixes." + ''' + The alert rule will only apply to activity logs with resourceIDs that fall under one of + these prefixes. If not provided, the subscriptionId will be used. + ''', + ) + args_schema.scope_ui.Element = AAZStrArg() + + args_schema.disable = AAZBoolArg( + options=["--disable"], + help="Disable the activity log alert rule after it is created.", + default=False, + ) + args_schema.condition = AAZCustomListArg( + options=["--condition", "-c"], + help="The condition that will cause the alert rule to activate. " + "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' + The possible values for the field are 'resourceId', 'category', 'caller', + 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', + 'subStatus', 'resourceType', or anything beginning with 'properties'. + ''' + ) + args_schema.condition.Element = AAZStrArg() + + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + help="Add an action group. Accepts space-separated action group identifiers. " + "The identifier can be the action group's name or its resource ID.", + ) + args_schema.action_group_ids.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", + ) + ) + + args_schema.webhook_properties_list = AAZCustomListArg( + options=['--webhook-properties', '-w'], + help="Space-separated webhook properties in 'key[=value]' format. " + "These properties are associated with the action groups added in this command." + ''' + For any webhook receiver in these action group, this data is appended to the webhook + payload. To attach different webhook properties to different action groups, add the + action groups in separate update-action commands. + ''' + ) + args_schema.webhook_properties_list.Element = AAZStrArg() + + return args_schema + + def pre_operations(self): + args = self.ctx.args + args.location = "Global" + process_condition_parameter_for_alert(args) + webhook_properties = process_webhook_properties(args) + if not has_value(args.scope_ui): + from azure.mgmt.core.tools import resource_id + from azure.cli.core.commands.client_factory import get_subscription_id + # args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx), + # resource_group=args.resource_group)] + # service check + args.scopes = [resource_id(subscription=get_subscription_id(self.cli_ctx))] + else: + args.scopes = args.scope_ui.to_serialized_data() + if _get_alert_settings_for_alert(self, args.resource_group, args.activity_log_alert_name, + throw_if_missing=False): + raise ValidationError( + 'The activity log alert {} already exists in resource group {}.'.format(args.activity_log_alert_name, + args.resource_group)) + if not has_value(args.all_of): + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + else: + current_all_of = args.all_of.to_serialized_data() + category_found = False + for item in current_all_of: + if item.get("field", None) == "category": + category_found = True + break + if not category_found: + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + # Add action groups + action_group_rids = set() + if has_value(args.action_group_ids): + action_group_rids = set(args.action_group_ids.to_serialized_data()) + args.action_groups = [] + for i in action_group_rids: + args.action_groups.append({ + "action_group_id": i, + "webhook_properties": webhook_properties + }) + if has_value(args.disable): + args.enabled = not args.disable diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_update.py new file mode 100644 index 00000000000..162082382fc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/_update.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import has_value, AAZStrArg +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._update \ + import Update as _ActivityLogAlertUpdate +from azure.cli.command_modules.monitor.operations.activity_log_alerts import ( + process_condition_parameter_for_alert, +) + + +class ActivityLogAlertUpdate(_ActivityLogAlertUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.scopes._registered = False + args_schema.condition = AAZCustomListArg( + options=["--condition", "-c"], + help="The condition that will cause the alert rule to activate. " + "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' + The possible values for the field are 'resourceId', 'category', 'caller', + 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', + 'subStatus', 'resourceType', or anything beginning with 'properties'. + ''' + ) + args_schema.condition.Element = AAZStrArg() + return args_schema + + def pre_operations(self): + args = self.ctx.args + process_condition_parameter_for_alert(args) + if not has_value(args.all_of): + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) + else: + current_all_of = args.all_of.to_serialized_data() + category_found = False + for item in current_all_of: + if item.get("field", None) == "category": + category_found = True + break + if not category_found: + args.all_of.append({ + "field": "category", + "equals": "ServiceHealth", + }) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__cmd_group.py new file mode 100644 index 00000000000..327013ee7e6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__cmd_group.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.aaz import AAZCommandGroup, register_command_group + + +@register_command_group( + "monitor activity-log alert action-group", +) +class __CMDGroup(AAZCommandGroup): # pylint: disable=too-few-public-methods + """Manage action groups for activity log alert rules. + """ + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_add.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_add.py new file mode 100644 index 00000000000..1e0154012c6 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_add.py @@ -0,0 +1,117 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import has_value, AAZStrArg, AAZListArg, AAZBoolArg, register_command, \ + AAZResourceIdArg, AAZResourceIdArgFormat +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._update \ + import Update as _ActivityLogAlertUpdate +from azure.cli.command_modules.monitor.operations.activity_log_alerts import process_webhook_properties + + +@register_command("monitor activity-log alert action-group add") +class ActivityLogAlertActionGroupAdd(_ActivityLogAlertUpdate): + """Add action groups to this activity log alert rule. It can also be used to overwrite existing webhook properties of particular action groups. + + :example: Add an action group and specify webhook properties. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + --action /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insight + s/actionGroups/{ActionGroup} \\ + --webhook-properties usage=test owner=jane + + :example: Overwite an existing action group's webhook properties. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti + onGroups/{ActionGroup} \\ + --webhook-properties usage=test owner=john + + :example: Remove webhook properties from an existing action group. + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup \\ + -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/acti + onGroups/{ActionGroup} + + :example: Add new action groups but prevent the command from accidently overwrite existing webhook properties + az monitor activity-log alert action-group add -n AlertName -g ResourceGroup --strict \\ + --action-group ResourceIDList + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.all_of._registered = False + args_schema.description._registered = False + args_schema.enabled._registered = False + args_schema.scopes._registered = False + args_schema.tags._registered = False + + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + help="The names or the resource ids of the action groups to be added.", + required=True + ) + args_schema.action_group_ids.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", + ) + ) + + args_schema.webhook_properties_list = AAZCustomListArg( + options=['--webhook-properties', '-w'], + help="Space-separated webhook properties in 'key[=value]' format. " + "These properties are associated with the action groups added in this command." + ''' + For any webhook receiver in these action group, these data are appended to the webhook + payload. To attach different webhook properties to different action groups, add the + action groups in separate update-action commands. + ''' + ) + args_schema.webhook_properties_list.Element = AAZStrArg() + + args_schema.reset = AAZBoolArg( + options=["--reset"], + help="Remove all the existing action groups before add new conditions.", + default=False + ) + args_schema.strict = AAZBoolArg( + options=["--strict"], + help="Fails the command if an action group to be added will change existing webhook properties.", + default=False, + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + webhook_properties = process_webhook_properties(args) + rids = args.action_group_ids.to_serialized_data() + + if has_value(args.reset) and args.reset: + action_groups = [] + for rid in rids: + action_groups.append({ + "action_group_id": rid, + "webhook_properties": webhook_properties + }) + instance.properties.actions.action_groups = action_groups + else: + action_groups_map = {} + for item in instance.properties.actions.action_groups: + ac_id = item.actionGroupId.to_serialized_data() + action_groups_map[ac_id.lower()] = { + "action_group_id": ac_id, + "webhook_properties": dict(item.webhookProperties) + } + for rid in rids: + if args.strict: + for key, item in action_groups_map.items(): + if key.lower() == rid.lower() and webhook_properties != item["webhook_properties"]: + raise ValueError( + 'Fails to override webhook properties of action group {} in strict mode.'.format(rid)) + action_groups_map[rid.lower()] = { + "action_group_id": rid, + "webhook_properties": webhook_properties + } + instance.properties.actions.action_groups = list(action_groups_map.values()) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_remove.py new file mode 100644 index 00000000000..86cf067391c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/action_group/_remove.py @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import AAZStrArg, AAZListArg, register_command +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._update \ + import Update as _ActivityLogAlertUpdate +from azure.cli.command_modules.monitor.operations.activity_log_alerts import normalize_names + + +@register_command("monitor activity-log alert action-group remove") +class ActivityLogAlertActionGroupRemove(_ActivityLogAlertUpdate): + """Remove action groups from this activity log alert rule. + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.action_groups._registered = False + args_schema.all_of._registered = False + args_schema.description._registered = False + args_schema.enabled._registered = False + args_schema.scopes._registered = False + args_schema.tags._registered = False + args_schema.action_group_ids = AAZListArg( + options=["--action-group", "-a"], + required=True, + help="The names or the resource ids of the action groups to be added.", + ) + args_schema.action_group_ids.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + action_group_ids = args.action_group_ids.to_serialized_data() + if len(action_group_ids) == 1 and action_group_ids[0] == '*': + instance.properties.actions.actionGroups = [] + else: + # normalize the action group ids + rids = normalize_names(self.cli_ctx, args.action_group_ids.to_serialized_data(), args.resource_group, + 'microsoft.insights', 'actionGroups') + action_groups = [] + for item in instance.properties.actions.actionGroups: + ac_id = item.actionGroupId.to_serialized_data() + found = False + for rid in rids: + if ac_id.lower() == rid.lower(): # service returned action group id can be uppercase + found = True + break + if not found: + action_groups.append(item) + instance.properties.actions.actionGroups = action_groups diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__cmd_group.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__cmd_group.py new file mode 100644 index 00000000000..484c82f4fad --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__cmd_group.py @@ -0,0 +1,17 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from azure.cli.core.aaz import AAZCommandGroup, register_command_group + + +@register_command_group( + "monitor activity-log alert scope", +) +class __CMDGroup(AAZCommandGroup): # pylint: disable=too-few-public-methods + """Manage scopes for activity log alert rules. + """ + + +__all__ = ["__CMDGroup"] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_add.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_add.py new file mode 100644 index 00000000000..694ac35ee05 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_add.py @@ -0,0 +1,54 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import AAZStrArg, AAZListArg, AAZBoolArg, register_command +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._update \ + import Update as _ActivityLogAlertUpdate + + +@register_command("monitor activity-log alert scope add") +class ActivityLogAlertScopeAdd(_ActivityLogAlertUpdate): + """Add scopes to this activity log alert rule. + + :example: Add scopes to this activity log alert rule. + az monitor activity-log alert scope add --name MyActivityLogAlerts --resource-group + MyResourceGroup --scope /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myRG + /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx- + xxxxxxxxxxxx/resourceGroups/myRG/Microsoft.KeyVault/vaults/mykey + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.all_of._registered = False + args_schema.action_groups._registered = False + args_schema.tags._registered = False + args_schema.description._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + required=True, + help="List of scopes to add. Each scope could be a resource ID or a subscription ID.", + ) + args_schema.scope_ui.Element = AAZStrArg() + + args_schema.reset = AAZBoolArg( + options=["--reset"], + help="Remove all the existing action groups before add new conditions.", + default=False + ) + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + new_scopes = set() if args.reset else set(instance.properties.scopes.to_serialized_data()) + for scope in args.scope_ui.to_serialized_data(): + new_scopes.add(scope) + + args.scopes = list(new_scopes) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_remove.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_remove.py new file mode 100644 index 00000000000..fe997e0ba89 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/activity_log/alert/scope/_remove.py @@ -0,0 +1,43 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import AAZStrArg, AAZListArg, register_command +from azure.cli.command_modules.monitor.aaz.latest.monitor.activity_log.alert._update \ + import Update as _ActivityLogAlertUpdate + + +@register_command("monitor activity-log alert scope remove") +class ActivityLogAlertScopeRemove(_ActivityLogAlertUpdate): + """Removes scopes from this activity log alert rule. + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.enabled._registered = False + args_schema.all_of._registered = False + args_schema.action_groups._registered = False + args_schema.tags._registered = False + args_schema.description._registered = False + args_schema.scopes._registered = False + args_schema.scope_ui = AAZListArg( + options=["--scope", "-s"], + required=True, + help="The scopes to remove.", + ) + args_schema.scope_ui.Element = AAZStrArg() + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + new_scopes = set(instance.properties.scopes.to_serialized_data()) + for scope in args.scope_ui.to_serialized_data(): + try: + new_scopes.remove(scope) + except KeyError: + pass + args.scopes = list(new_scopes) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_create.py new file mode 100644 index 00000000000..1ec1fff58e4 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_create.py @@ -0,0 +1,19 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import has_value +from azure.cli.command_modules.monitor.aaz.latest.monitor.autoscale._create import Create as _AutoScaleCreate + + +class AutoScaleCreate(_AutoScaleCreate): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_list.py new file mode 100644 index 00000000000..09882316e87 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_list.py @@ -0,0 +1,22 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import has_value +from azure.cli.command_modules.monitor.aaz.latest.monitor.autoscale._list import List as _AutoScaleList + + +class AutoScaleList(_AutoScaleList): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + for value in self.ctx.vars.instance.value: + if has_value(value.properties): + value.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance.value, client_flatten=True) + next_link = self.deserialize_output(self.ctx.vars.instance.next_link) + return result, next_link diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_show.py new file mode 100644 index 00000000000..d0fce150ed5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_show.py @@ -0,0 +1,20 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import has_value +from azure.cli.command_modules.monitor.aaz.latest.monitor.autoscale._show import Show as _AutoScaleShow + + +class AutoScaleShow(_AutoScaleShow): + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_update.py new file mode 100644 index 00000000000..1c9acd1644b --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/autoscale/_update.py @@ -0,0 +1,174 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long, too-many-statements + +import json + +from azure.cli.core.aaz import has_value, AAZIntArg, AAZBoolArg, AAZStrArg +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.command_modules.monitor._autoscale_util import get_autoscale_default_profile +from azure.cli.command_modules.monitor.aaz.latest.monitor.autoscale._update import Update as _AutoScaleUpdate +from azure.cli.command_modules.monitor.operations.autoscale_settings import ( + update_add_actions, update_remove_actions, _parse_action_removals, +) +from azure.cli.core.azclierror import InvalidArgumentValueError + + +class AutoScaleUpdate(_AutoScaleUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.notifications._registered = False + args_schema.profiles._registered = False + args_schema.target_resource_location._registered = False + args_schema.target_resource_uri._registered = False + args_schema.count = AAZIntArg( + options=["--count"], + help='The numer of instances to use. If used with --min/max-count, the default number of instances to use.', + arg_group="Instance Limit", + ) + args_schema.min_count = AAZIntArg( + options=["--min-count"], + help='The minimum number of instances.', + arg_group="Instance Limit", + ) + args_schema.max_count = AAZIntArg( + options=["--max-count"], + help='The maximum number of instances.', + arg_group="Instance Limit", + ) + args_schema.add_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=['--add-action', '-a'], + help="Add an action to fire when a scaling event occurs." + ''' + Usage: --add-action TYPE KEY [ARG ...] + Email: --add-action email bob@contoso.com ann@contoso.com + Webhook: --add-action webhook https://www.contoso.com/alert apiKey=value + Webhook: --add-action webhook https://www.contoso.com/alert?apiKey=value + Multiple actions can be specified by using more than one `--add-action` argument. + ''', + arg_group="Notification", + ) + args_schema.add_actions.Element = AAZCustomListArg() + args_schema.add_actions.Element.Element = AAZStrArg() + + args_schema.remove_actions = AAZCustomListArg( + options=["--remove-actions"], + singular_options=['--remove-action', '-r'], + help="Remove one or more actions." + ''' + Usage: --remove-action TYPE KEY [KEY ...] + Email: --remove-action email bob@contoso.com ann@contoso.com + Webhook: --remove-action webhook https://contoso.com/alert https://alerts.contoso.com. + ''', + arg_group="Notification", + ) + args_schema.remove_actions.Element = AAZCustomListArg() + args_schema.remove_actions.Element.Element = AAZStrArg() + + args_schema.email_administrator = AAZBoolArg( + options=["--email-administrator"], + help='Send email to subscription administrator on scaling.', + arg_group="Notification", + ) + args_schema.email_coadministrators = AAZBoolArg( + options=["--email-coadministrators"], + help='Send email to subscription co-administrators on scaling.', + arg_group="Notification", + ) + + return args_schema + + def pre_instance_update(self, instance): + args = self.ctx.args + add_actions = update_add_actions(args) + remove_actions = update_remove_actions(args) + if has_value(args.count) or has_value(args.min_count) or has_value(args.max_count): + default_profile = get_autoscale_default_profile(instance) + curr_count = default_profile["capacity"]["default"] + curr_min = default_profile["capacity"]["minimum"] + curr_max = default_profile["capacity"]["maximum"] + is_fixed_count = curr_count == curr_min and curr_count == curr_max + + # check for special case where count is used to indicate fixed value and only + # count is updated + if has_value(args.count) and is_fixed_count and not has_value(args.min_count) and not has_value(args.max_count): + args.min_count = args.count.to_serialized_data() + args.max_count = args.count.to_serialized_data() + + count = curr_count if not has_value(args.count) else args.count.to_serialized_data() + min_count = curr_min if not has_value(args.min_count) else args.min_count.to_serialized_data() + max_count = curr_max if not has_value(args.max_count) else args.max_count.to_serialized_data() + + # There may be multiple "default" profiles. All need to updated. + for profile in instance.properties.profiles: + if has_value(profile.fixed_date): + continue + if has_value(profile.recurrence): + try: + # portal denotes the "default" pairs by using a JSON string for their name + # so if it can be decoded, we know this is a default profile + json.loads(profile.name.to_serialized_data()) + except ValueError: + continue + profile.capacity.default = str(count) + profile.capacity.minimum = str(min_count) + profile.capacity.maximum = str(max_count) + updated_notification = None + if instance.properties.notifications: + retained_notification = [] + for x in instance.properties.notifications: + note = x.to_serialized_data() + if note['operation'].lower() == 'scale': + updated_notification = note + else: + retained_notification.append(note) + instance.properties.notifications = retained_notification + else: + instance.properties.notifications = [] + + if updated_notification is None: + updated_notification = { + "operation": "scale", + "email": { + "customEmails": [] + }, + "webhooks": [] + } + + # process removals + if len(remove_actions) > 0: + removed_emails, removed_webhooks = _parse_action_removals(remove_actions) + updated_notification['email']['customEmails'] = \ + [x for x in updated_notification['email']['customEmails'] if x not in removed_emails] + updated_notification['webhooks'] = \ + [x for x in updated_notification['webhooks'] if x['serviceUri'] not in removed_webhooks] + + # process additions + for action in add_actions: + if action["key"] == "email": + for email in action["value"]["customEmails"]: + updated_notification['email']['customEmails'].append(email) + elif action["key"] == "webhook": + updated_notification['webhooks'].append(action["value"]) + if has_value(args.email_administrator): + updated_notification['email']['sendToSubscriptionAdministrator'] = args.email_administrator.to_serialized_data() + if has_value(args.email_coadministrators): + updated_notification['email']['sendToSubscriptionCoAdministrators'] = args.email_coadministrators.to_serialized_data() + + instance.properties.notifications.append(updated_notification) + + if has_value(args.scale_look_ahead_time) and not has_value(args.scale_mode) \ + and not has_value(instance.properties.predictive_autoscale_policy): + raise InvalidArgumentValueError('scale-mode is required for setting scale-look-ahead-time.') + + def _output(self, *args, **kwargs): + from azure.cli.core.aaz import AAZUndefined + # When the name field conflicts, the name in inner layer is ignored and the outer layer is applied + if has_value(self.ctx.vars.instance.properties.name): + self.ctx.vars.instance.properties.name = AAZUndefined + result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True) + return result diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_create.py new file mode 100644 index 00000000000..d97b8d8d68c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_create.py @@ -0,0 +1,101 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings._create \ + import Create as _DiagnosticSettingsCreate +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) +from azure.cli.core.azclierror import ArgumentUsageError +from knack.util import CLIError + + +class DiagnosticSettingsCreate(_DiagnosticSettingsCreate): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + + from azure.cli.core.aaz import AAZBoolArg + arg_schema.export_to_resource_specific = AAZBoolArg( + options=['--export-to-resource-specific'], + help="Indicate that the export to LA must be done to a resource specific table, a.k.a. " + "dedicated or fixed schema table, as opposed to the default dynamic schema table called " + "AzureDiagnostics. This argument is effective only when the argument --workspace is also given. " + "Allowed values: false, true." + ) + arg_schema.log_analytics_destination_type._registered = False + arg_schema.service_bus_rule_id._registered = False + return arg_schema + + def pre_operations(self): + ctx = self.ctx + from azure.cli.core.aaz import has_value + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + update_resource_parameters(ctx) + args = ctx.args + rg = args.resource_group_name.to_serialized_data() + + if not has_value(rg): + rg = parse_resource_id(args.resource.to_serialized_data())['resource_group'] + args.resource_group_name = rg + + storage_account = args.storage_account.to_serialized_data() + if has_value(storage_account) and not is_valid_resource_id(storage_account): + storage_account = resource_id(subscription=ctx.subscription_id, + resource_group=rg, + namespace='microsoft.Storage', + type='storageAccounts', + name=storage_account) + args.storage_account = storage_account + + workspace = args.workspace.to_serialized_data() + if has_value(workspace) and not is_valid_resource_id(workspace): + workspace = resource_id(subscription=ctx.subscription_id, + resource_group=rg, + namespace='microsoft.OperationalInsights', + type='workspaces', + name=workspace) + args.workspace = workspace + + event_hub = args.event_hub.to_serialized_data() + if has_value(event_hub) and is_valid_resource_id(event_hub): + event_hub = parse_resource_id(event_hub)['name'] + args.event_hub = event_hub + + event_hub_rule = args.event_hub_rule.to_serialized_data() + if has_value(event_hub_rule): + if not is_valid_resource_id(event_hub_rule): + if not has_value(event_hub): + raise CLIError('usage error: --event-hub-rule ID | --event-hub-rule NAME --event-hub NAME') + # use value from --event-hub if the rule is a name + event_hub_rule = resource_id( + subscription=ctx.subscription_id, + resource_group=rg, + namespace='Microsoft.EventHub', + type='namespaces', + name=event_hub, + child_type_1='AuthorizationRules', + child_name_1=event_hub_rule) + args.event_hub_rule = event_hub_rule + + elif not has_value(event_hub): + # extract the event hub name from `--event-hub-rule` if provided as an ID + event_hub = parse_resource_id(event_hub_rule)['name'] + args.event_hub = event_hub + if not (has_value(storage_account) or has_value(workspace) or has_value(event_hub)): + raise CLIError( + 'usage error - expected one or more: --storage-account NAME_OR_ID | --workspace NAME_OR_ID ' + '| --event-hub NAME_OR_ID | --event-hub-rule ID') + + export_to_resource_specific = args.export_to_resource_specific.to_serialized_data() + if has_value(export_to_resource_specific) and export_to_resource_specific: + args.log_analytics_destination_type = 'Dedicated' + if not has_value(workspace): + raise ArgumentUsageError('usage error: --workspace and --export-to-specific-resource') + else: + args.log_analytics_destination_type = None diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_delete.py new file mode 100644 index 00000000000..5c24e15a935 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_delete.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings._delete \ + import Delete as _DiagnosticSettingsDelete +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsDelete(_DiagnosticSettingsDelete): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_list.py new file mode 100644 index 00000000000..e5e58ee5ef8 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_list.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings._list \ + import List as _DiagnosticSettingsList +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsList(_DiagnosticSettingsList): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_show.py new file mode 100644 index 00000000000..2fe543d6e2f --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_show.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings._show \ + import Show as _DiagnosticSettingsShow +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsShow(_DiagnosticSettingsShow): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_update.py new file mode 100644 index 00000000000..e2608b8e727 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/_update.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings._update \ + import Update as _DiagnosticSettingsUpdate +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsUpdate(_DiagnosticSettingsUpdate): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema, arg_group="Target Resource") + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_list.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_list.py new file mode 100644 index 00000000000..af276b4bd62 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_list.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings.categories._list \ + import List as _DiagnosticSettingsCategoryList +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsCategoryList(_DiagnosticSettingsCategoryList): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_show.py new file mode 100644 index 00000000000..a7264545c2d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/diagnostic_settings/categories/_show.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.diagnostic_settings.categories._show \ + import Show as _DiagnosticSettingsCategoryShow +from azure.cli.command_modules.monitor.operations.diagnostics_settings import ( + create_resource_parameters, update_resource_parameters, +) + + +class DiagnosticSettingsCategoryShow(_DiagnosticSettingsCategoryShow): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + arg_schema = super()._build_arguments_schema(*args, **kwargs) + create_resource_parameters(arg_schema) + return arg_schema + + def pre_operations(self): + update_resource_parameters(self.ctx) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_create.py new file mode 100644 index 00000000000..662b66bb418 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_create.py @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.data_export._create \ + import Create as _WorkspaceDataExportCreate + + +class WorkspaceDataExportCreate(_WorkspaceDataExportCreate): + + def pre_operations(self): + args = self.ctx.args + destination = str(args.destination) + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + if not is_valid_resource_id(destination): + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + result = parse_resource_id(destination) + if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': + args.destination = resource_id( + subscription=result['subscription'], + resource_group=result['resource_group'], + namespace=result['namespace'], + type=result['type'], + name=result['name'] + ) + if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': + args.event_hub_name = result['child_name_1'] + elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': + pass + else: + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_update.py new file mode 100644 index 00000000000..d550620a0cc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/data_export/_update.py @@ -0,0 +1,38 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.data_export._update \ + import Update as _WorkspaceDataExportUpdate + + +class WorkspaceDataExportUpdate(_WorkspaceDataExportUpdate): + + def pre_operations(self): + args = self.ctx.args + if args.destination: + destination = str(args.destination) + from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id + if not is_valid_resource_id(destination): + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') + result = parse_resource_id(destination) + if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': + args.destination = resource_id( + subscription=result['subscription'], + resource_group=result['resource_group'], + namespace=result['namespace'], + type=result['type'], + name=result['name'] + ) + if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': + args.event_hub_name = result['child_name_1'] + elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': + pass + else: + raise InvalidArgumentValueError('usage error: --destination should be a storage account,' + ' an evenhug namespace or an event hub resource id.') diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/_create.py new file mode 100644 index 00000000000..abd635e4c1a --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/linked_storage/_create.py @@ -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. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.linked_storage._create \ + import Create as _WorkspaceLinkedStorageAccountCreate + + +class WorkspaceLinkedStorageAccountCreate(_WorkspaceLinkedStorageAccountCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZResourceIdArg, AAZResourceIdArgFormat + cls._args_schema = super()._build_arguments_schema(*args, **kwargs) + + storage_accounts = cls._args_schema.storage_accounts + storage_accounts._element = AAZResourceIdArg(fmt=AAZResourceIdArgFormat( + template='/subscriptions/{subscription}/resourceGroups/{resource_group}/' + 'providers/Microsoft.Storage/storageAccounts/{}')) + return cls._args_schema diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_create.py new file mode 100644 index 00000000000..aecb418cf25 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_create.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.aaz import has_value +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.table._create \ + import Create as _WorkspaceTableCreate + + +class WorkspaceTableCreate(_WorkspaceTableCreate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZIntArgFormat + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.total_retention_in_days._fmt = AAZIntArgFormat( + maximum=4383, + minimum=-1, + ) + args_schema.retention_in_days._fmt = AAZIntArgFormat( + maximum=730, + minimum=-1, + ) + return args_schema + + def pre_operations(self): + args = self.ctx.args + if has_value(args.retention_in_days): + retention_time = args.retention_in_days.to_serialized_data() + if retention_time == -1 or (4 <= retention_time <= 730): + pass + else: + raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " + "Otherwise setting this property to -1 will default to " + "workspace retention.") + + if has_value(args.total_retention_in_days): + total_retention_time = args.total_retention_in_days.to_serialized_data() + if total_retention_time == -1 or (4 <= total_retention_time <= 4383): + pass + else: + raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " + "Otherwise setting this property to -1 will default to " + "table retention.") diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_update.py new file mode 100644 index 00000000000..5421567ec05 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/_update.py @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.core.aaz import has_value +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.table._update \ + import Update as _WorkspaceTableUpdate + + +class WorkspaceTableUpdate(_WorkspaceTableUpdate): + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + from azure.cli.core.aaz import AAZIntArgFormat + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.total_retention_in_days._fmt = AAZIntArgFormat( + maximum=4383, + minimum=-1, + ) + args_schema.retention_in_days._fmt = AAZIntArgFormat( + maximum=730, + minimum=-1, + ) + return args_schema + + def pre_operations(self): + args = self.ctx.args + if has_value(args.retention_in_days): + retention_time = args.retention_in_days.to_serialized_data() + if retention_time == -1 or (4 <= retention_time <= 730): + pass + else: + raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " + "Otherwise setting this property to -1 will default to " + "workspace retention.") + + if has_value(args.total_retention_in_days): + total_retention_time = args.total_retention_in_days.to_serialized_data() + if total_retention_time == -1 or (4 <= total_retention_time <= 4383): + pass + else: + raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " + "Otherwise setting this property to -1 will default to " + "table retention.") diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py new file mode 100644 index 00000000000..3fe62398edf --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/log_analytics/workspace/table/search_job/_cancel.py @@ -0,0 +1,19 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.table.search_job._cancel \ + import Cancel as _WorkspaceTableSearchJobCancel + + +class WorkspaceTableSearchJobCancel(_WorkspaceTableSearchJobCancel): + def pre_operations(self): + args = self.ctx.args + table_name = args.table_name.to_serialized_data() + + if table_name and not table_name.endswith("_SRCH"): + raise InvalidArgumentValueError('usage: The table name needs to end with _SRCH') diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/__init__.py new file mode 100644 index 00000000000..34913fb394d --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/__init__.py @@ -0,0 +1,4 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/_update.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/_update.py new file mode 100644 index 00000000000..70891c8147c --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/metrics/alert/_update.py @@ -0,0 +1,220 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long, too-many-statements, too-many-locals, too-many-nested-blocks + +from knack.log import get_logger + +from azure.cli.command_modules.monitor.aaz.latest.monitor.metrics.alert._update import Update as _MetricsAlertUpdate +from azure.cli.command_modules.monitor.actions import AAZCustomListArg +from azure.cli.core.aaz import AAZListArg, AAZResourceIdArg, AAZResourceIdArgFormat, AAZStrArg, has_value +from azure.cli.core.azclierror import InvalidArgumentValueError +from azure.mgmt.core.tools import is_valid_resource_id, resource_id + +logger = get_logger(__name__) + + +class MetricsAlertUpdate(_MetricsAlertUpdate): + def __init__(self, loader=None, cli_ctx=None, callbacks=None, **kwargs): + super().__init__(loader, cli_ctx, callbacks, **kwargs) + self.add_actions = [] + self.add_conditions = [] + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.add_actions = AAZCustomListArg( + options=["--add-actions"], + singular_options=["--add-action"], + arg_group="Action", + help="Add an action group and optional webhook properties to fire when the alert is triggered.\n\n" + "Usage: --add-action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]\n\n" + "Multiple action groups can be specified by using more than one `--add-action` argument." + ) + args_schema.add_actions.Element = AAZCustomListArg() + args_schema.add_actions.Element.Element = AAZStrArg() + args_schema.remove_actions = AAZListArg( + options=["--remove-actions"], + arg_group="Action", + help="Space-separated list of action group names to remove." + ) + args_schema.remove_actions.Element = AAZResourceIdArg( + fmt=AAZResourceIdArgFormat( + template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Insights" + "/actionGroups/{}" + ) + ) + args_schema.add_conditions = AAZCustomListArg( + options=["--add-conditions"], + singular_options=["--add-condition"], + arg_group="Condition", + help="Add a condition which triggers the rule.\n\n" + "Usage: --add-condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n" + "[{=,!=,>,>=,<,<=} THRESHOLD]\n" + "[{>,><,<} dynamic SENSITIVITY VIOLATIONS of EVALUATIONS [since DATETIME]]\n" + "[where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n" + "[and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n\n" + "Sensitivity can be 'low', 'medium', 'high'.\n\n" + "Violations can be the number of violations to trigger an alert. It should be smaller or equal to evaluation.\n\n" + "Evaluations can be the number of evaluation periods for dynamic threshold.\n\n" + "Datetime can be the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format).\n\n" + "Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be queried by combining them with the 'and' keyword.\n\n" + "Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az monitor metrics list-definitions` command.\n\n" + "Due to server limitation, when an alert rule contains multiple criterias, the use of dimensions is limited to one value per dimension within each criterion.\n\n" + "Multiple conditions can be specified by using more than one `--add-condition` argument." + ) + args_schema.add_conditions.Element = AAZListArg() + args_schema.add_conditions.Element.Element = AAZStrArg() + args_schema.remove_conditions = AAZListArg( + options=["--remove-conditions"], + arg_group="Condition", + help="Space-separated list of condition names to remove." + ) + args_schema.remove_conditions.Element = AAZStrArg() + + return args_schema + + def pre_operations(self): + import antlr4 + + from azure.cli.command_modules.monitor.grammar.metric_alert import ( + MetricAlertConditionLexer, + MetricAlertConditionParser, + MetricAlertConditionValidator, + ) + + def complete_action_group_id(name): + if is_valid_resource_id(name): + return name + + return resource_id( + subscription=self.ctx.subscription_id, + resource_group=self.ctx.args.resource_group, + namespace="Microsoft.Insights", + type="actionGroups", + name=name + ) + + args = self.ctx.args + if has_value(args.add_actions): + self.add_actions = [] + for add_action in args.add_actions: + values = add_action.to_serialized_data()[0].split() + action_group_id = complete_action_group_id(values[0]) + try: + webhook_property_candidates = dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None + except ValueError: + err_msg = "Value of --add-action is invalid. Please refer to --help to get insight of correct format." + raise InvalidArgumentValueError(err_msg) + + action = { + "action_group_id": action_group_id, + "web_hook_properties": webhook_property_candidates + } + action["odatatype"] = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models." \ + "Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.Action" + + self.add_actions.append(action) + + if has_value(args.add_conditions): + err_msg = 'usage error: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n' \ + ' [{=,!=,>,>=,<,<=} THRESHOLD]\n' \ + ' [{<,>,><} dynamic SENSITIVITY VIOLATION of EVALUATION [since DATETIME]]\n' \ + ' [where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n' \ + ' [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n' \ + ' [with skipmetricvalidation]' + + self.add_conditions = [] + for add_condition in args.add_conditions: + string_val = add_condition.to_serialized_data()[0] + lexer = MetricAlertConditionLexer(antlr4.InputStream(string_val)) + stream = antlr4.CommonTokenStream(lexer) + parser = MetricAlertConditionParser(stream) + tree = parser.expression() + + try: + validator = MetricAlertConditionValidator() + walker = antlr4.ParseTreeWalker() + walker.walk(validator, tree) + metric_condition = validator.result() + if "static" in metric_condition: + # static metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'threshold']: + if item not in metric_condition["static"]: + raise InvalidArgumentValueError(err_msg) + elif "dynamic" in metric_condition: + # dynamic metric criteria + for item in ['time_aggregation', 'metric_name', 'operator', 'alert_sensitivity', + 'failing_periods']: + if item not in metric_condition["dynamic"]: + raise InvalidArgumentValueError(err_msg) + else: + raise NotImplementedError() + except (AttributeError, TypeError, KeyError): + raise InvalidArgumentValueError(err_msg) + + self.add_conditions.append(metric_condition) + + def pre_instance_update(self, instance): + from msrest.serialization import Serializer + + def get_next_name(): + idx = 0 + while True: + possible_name = f"cond{idx}" + match = next((cond for cond in instance.properties.criteria.all_of if cond.name == possible_name), None) + if match: + idx += 1 + continue + + return possible_name + + args = self.ctx.args + if has_value(args.remove_actions): + to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_actions)) + + new_actions = [] + for action in instance.properties.actions: + if action.action_group_id.to_serialized_data().lower() not in to_be_removed: + new_actions.append(action) + + instance.properties.actions = new_actions + + if has_value(args.add_actions): + to_be_added = set(map(lambda x: x["action_group_id"].lower(), self.add_actions)) + + new_actions = [] + for action in instance.properties.actions: + if action.action_group_id.to_serialized_data().lower() not in to_be_added: + new_actions.append(action) + new_actions.extend(self.add_actions) + + instance.properties.actions = new_actions + + if has_value(args.remove_conditions): + to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_conditions)) + + new_conditions = [] + for cond in instance.properties.criteria.all_of: + if cond.name.to_serialized_data().lower() not in to_be_removed: + new_conditions.append(cond) + + instance.properties.criteria.all_of = new_conditions + + if has_value(args.add_conditions): + for cond in self.add_conditions: + if "dynamic" in cond: + item = cond["dynamic"] + item["name"] = get_next_name() + item["criterion_type"] = "DynamicThresholdCriterion" + item["ignore_data_before"] = Serializer.serialize_iso(dt) if (dt := item.pop("ignore_data_before", None)) else None + + instance.properties.criteria.all_of.append(item) + else: + item = cond["static"] + item["name"] = get_next_name() + item["criterion_type"] = "StaticThresholdCriterion" + + instance.properties.criteria.all_of.append(item) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/_create.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/_create.py new file mode 100644 index 00000000000..9f4bf928338 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/_create.py @@ -0,0 +1,21 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.command_modules.monitor.aaz.latest.monitor.private_link_scope._create \ + import Create as _PrivateLinkScopeCreate + + +class PrivateLinkScopeCreate(_PrivateLinkScopeCreate): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.location._required = False + args_schema.location._registered = False + return args_schema + + def pre_operations(self): + self.ctx.args.location = "global" diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py new file mode 100644 index 00000000000..9fcc3102cf5 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +# pylint: skip-file +# flake8: noqa \ No newline at end of file diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_approve.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_approve.py new file mode 100644 index 00000000000..6c0f6dd2f10 --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_approve.py @@ -0,0 +1,33 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import register_command +from azure.cli.command_modules.monitor.aaz.latest.monitor.private_link_scope.private_endpoint_connection._update \ + import Update +from azure.cli.command_modules.monitor.operations.private_link_scope import validate_private_endpoint_connection_id + + +@register_command("monitor private-link-scope private-endpoint-connection approve") +class ConnectionApprove(Update): + """Approve a private endpoint connection of a private link scope resource. + + :example: Approve a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection approve --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.status._registered = False + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + return args_schema + + def pre_operations(self): + self.ctx.args.status = "Approved" + validate_private_endpoint_connection_id(self.ctx.args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py new file mode 100644 index 00000000000..2ada4dd720e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_delete.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import AAZStrArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.private_link_scope.private_endpoint_connection._delete \ + import Delete as _ConnectionDelete +from azure.cli.command_modules.monitor.operations.private_link_scope import validate_private_endpoint_connection_id + + +class ConnectionDelete(_ConnectionDelete): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.id = AAZStrArg( + options=["--id"], + help="ID of the private endpoint connection associated with the private link scope. " + "Values from `az monitor private-link-scope show`." + ) + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + validate_private_endpoint_connection_id(self.ctx.args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_reject.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_reject.py new file mode 100644 index 00000000000..2ce54ce140e --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_reject.py @@ -0,0 +1,33 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access, line-too-long + +from azure.cli.core.aaz import register_command +from azure.cli.command_modules.monitor.aaz.latest.monitor.private_link_scope.private_endpoint_connection._update \ + import Update +from azure.cli.command_modules.monitor.operations.private_link_scope import validate_private_endpoint_connection_id + + +@register_command("monitor private-link-scope private-endpoint-connection reject") +class ConnectionReject(Update): + """Reject a private endpoint connection of a private link scope resource. + + :example: Reject a private endpoint connection of a private link scope resource. + az monitor private-link-scope private-endpoint-connection reject --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope + """ + + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.status._registered = False + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + return args_schema + + def pre_operations(self): + self.ctx.args.status = "Rejected" + validate_private_endpoint_connection_id(self.ctx.args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_show.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_show.py new file mode 100644 index 00000000000..18c8cb9e9fc --- /dev/null +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/latest/monitor/private_link_scope/private_endpoint_connection/_show.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +# pylint: disable=protected-access + +from azure.cli.core.aaz import AAZStrArg +from azure.cli.command_modules.monitor.aaz.latest.monitor.private_link_scope.private_endpoint_connection._show \ + import Show as _ConnectionShow +from azure.cli.command_modules.monitor.operations.private_link_scope import validate_private_endpoint_connection_id + + +class ConnectionShow(_ConnectionShow): + @classmethod + def _build_arguments_schema(cls, *args, **kwargs): + args_schema = super()._build_arguments_schema(*args, **kwargs) + args_schema.id = AAZStrArg( + options=["--id"], + help="ID of the private endpoint connection associated with the private link scope. " + "Values from `az monitor private-link-scope show`." + ) + args_schema.name._required = False + args_schema.resource_group._required = False + args_schema.scope_name._required = False + + return args_schema + + def pre_operations(self): + validate_private_endpoint_connection_id(self.ctx.args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_linked_storage_account.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_linked_storage_account.py index ad0d773fdb4..dd2d03355db 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_linked_storage_account.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_linked_storage_account.py @@ -3,28 +3,13 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.linked_storage import \ - Create as _WorkspaceLinkedStorageAccountCreate, Update as _WorkspaceLinkedStorageAccountUpdate - - -class WorkspaceLinkedStorageAccountCreate(_WorkspaceLinkedStorageAccountCreate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZResourceIdArg, AAZResourceIdArgFormat - cls._args_schema = super()._build_arguments_schema(*args, **kwargs) - - storage_accounts = cls._args_schema.storage_accounts - storage_accounts._element = AAZResourceIdArg(fmt=AAZResourceIdArgFormat( # pylint: disable=protected-access - template='/subscriptions/{subscription}/resourceGroups/{resource_group}/' - 'providers/Microsoft.Storage/storageAccounts/{}')) - return cls._args_schema - def add_log_analytics_workspace_linked_storage_accounts(cmd, resource_group_name, workspace_name, data_source_type, storage_account_ids): - class Add(_WorkspaceLinkedStorageAccountUpdate): + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.linked_storage._update \ + import Update as _WorkspaceLinkedStorageAccountUpdate + class Add(_WorkspaceLinkedStorageAccountUpdate): def pre_instance_update(self, instance): instance.properties.storage_account_ids.extend(storage_account_ids) @@ -37,8 +22,10 @@ def pre_instance_update(self, instance): def remove_log_analytics_workspace_linked_storage_accounts(cmd, resource_group_name, workspace_name, data_source_type, storage_account_ids): - class Remove(_WorkspaceLinkedStorageAccountUpdate): + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.linked_storage._update \ + import Update as _WorkspaceLinkedStorageAccountUpdate + class Remove(_WorkspaceLinkedStorageAccountUpdate): def pre_instance_update(self, instance): storage_account_ids_set = set(str.lower(storage_account_id) for storage_account_id in storage_account_ids) new_storage_account_ids = [] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py index c08313dd429..e8c1179df1c 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/log_analytics_workspace.py @@ -2,22 +2,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- - # pylint: disable=protected-access -from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.data_export import \ - Create as _WorkspaceDataExportCreate, \ - Update as _WorkspaceDataExportUpdate -from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.table import \ - Create as _WorkspaceTableCreate, \ - Update as _WorkspaceTableUpdate -from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.table.search_job \ - import Cancel as _WorkspaceTableSearchJobCancel - -from azure.cli.core.azclierror import ArgumentUsageError, InvalidArgumentValueError, RequiredArgumentMissingError -from azure.cli.core.commands.transform import _parse_id -from azure.cli.core.aaz import has_value - def list_deleted_log_analytics_workspaces(client, resource_group_name=None): if resource_group_name: @@ -26,8 +12,11 @@ def list_deleted_log_analytics_workspaces(client, resource_group_name=None): def recover_log_analytics_workspace(cmd, workspace_name, resource_group_name=None, no_wait=False): - from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace import Create, \ - ListDeletedWorkspaces + from azure.cli.core.azclierror import InvalidArgumentValueError + from azure.cli.core.commands.transform import _parse_id + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace._create import Create + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace._list_deleted_workspaces \ + import ListDeletedWorkspaces deleted_workspaces = ListDeletedWorkspaces(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name @@ -58,7 +47,8 @@ def create_log_analytics_workspace_saved_search(cmd, workspace_name, resource_gr category, display_name, saved_query, function_alias=None, function_parameters=None, tags=None): - from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.saved_search import Create + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.saved_search._create \ + import Create command_args = { "resource_group": resource_group_name, @@ -83,7 +73,8 @@ def update_log_analytics_workspace_saved_search(cmd, workspace_name, resource_gr category=None, display_name=None, saved_query=None, function_alias=None, function_parameters=None, tags=None): - from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.saved_search import Update + from azure.cli.command_modules.monitor.aaz.latest.monitor.log_analytics.workspace.saved_search._update \ + import Update command_args = { "resource_group": resource_group_name, "saved_search_name": saved_search_id, @@ -107,148 +98,14 @@ def update_log_analytics_workspace_saved_search(cmd, workspace_name, resource_gr ) -class WorkspaceDataExportCreate(_WorkspaceDataExportCreate): - - def pre_operations(self): - args = self.ctx.args - destination = str(args.destination) - from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id - if not is_valid_resource_id(destination): - raise InvalidArgumentValueError('usage error: --destination should be a storage account,' - ' an evenhug namespace or an event hub resource id.') - result = parse_resource_id(destination) - if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': - args.destination = resource_id( - subscription=result['subscription'], - resource_group=result['resource_group'], - namespace=result['namespace'], - type=result['type'], - name=result['name'] - ) - if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': - args.event_hub_name = result['child_name_1'] - elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': - pass - else: - raise InvalidArgumentValueError('usage error: --destination should be a storage account,' - ' an evenhug namespace or an event hub resource id.') - - -class WorkspaceDataExportUpdate(_WorkspaceDataExportUpdate): - - def pre_operations(self): - args = self.ctx.args - if args.destination: - destination = str(args.destination) - from azure.mgmt.core.tools import is_valid_resource_id, resource_id, parse_resource_id - if not is_valid_resource_id(destination): - raise InvalidArgumentValueError('usage error: --destination should be a storage account,' - ' an evenhug namespace or an event hub resource id.') - result = parse_resource_id(destination) - if result['namespace'].lower() == 'microsoft.eventhub' and result['type'].lower() == 'namespaces': - args.destination = resource_id( - subscription=result['subscription'], - resource_group=result['resource_group'], - namespace=result['namespace'], - type=result['type'], - name=result['name'] - ) - if 'child_type_1' in result and result['child_type_1'].lower() == 'eventhubs': - args.event_hub_name = result['child_name_1'] - elif result['namespace'].lower() == 'microsoft.storage' and result['type'].lower() == 'storageaccounts': - pass - else: - raise InvalidArgumentValueError('usage error: --destination should be a storage account,' - ' an evenhug namespace or an event hub resource id.') - - -class WorkspaceTableCreate(_WorkspaceTableCreate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZIntArgFormat - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.total_retention_in_days._fmt = AAZIntArgFormat( - maximum=4383, - minimum=-1, - ) - args_schema.retention_in_days._fmt = AAZIntArgFormat( - maximum=730, - minimum=-1, - ) - return args_schema - - def pre_operations(self): - args = self.ctx.args - if has_value(args.retention_in_days): - retention_time = args.retention_in_days.to_serialized_data() - if retention_time == -1 or (4 <= retention_time <= 730): - pass - else: - raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " - "Otherwise setting this property to -1 will default to " - "workspace retention.") - - if has_value(args.total_retention_in_days): - total_retention_time = args.total_retention_in_days.to_serialized_data() - if total_retention_time == -1 or (4 <= total_retention_time <= 4383): - pass - else: - raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " - "Otherwise setting this property to -1 will default to " - "table retention.") - - -class WorkspaceTableUpdate(_WorkspaceTableUpdate): - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZIntArgFormat - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.total_retention_in_days._fmt = AAZIntArgFormat( - maximum=4383, - minimum=-1, - ) - args_schema.retention_in_days._fmt = AAZIntArgFormat( - maximum=730, - minimum=-1, - ) - return args_schema - - def pre_operations(self): - args = self.ctx.args - if has_value(args.retention_in_days): - retention_time = args.retention_in_days.to_serialized_data() - if retention_time == -1 or (4 <= retention_time <= 730): - pass - else: - raise InvalidArgumentValueError("usage error: --retention-time should between 4 and 730. " - "Otherwise setting this property to -1 will default to " - "workspace retention.") - - if has_value(args.total_retention_in_days): - total_retention_time = args.total_retention_in_days.to_serialized_data() - if total_retention_time == -1 or (4 <= total_retention_time <= 4383): - pass - else: - raise InvalidArgumentValueError("usage error: --total-retention-time should between 4 and 4383. " - "Otherwise setting this property to -1 will default to " - "table retention.") - - -class WorkspaceTableSearchJobCancel(_WorkspaceTableSearchJobCancel): - def pre_operations(self): - args = self.ctx.args - table_name = args.table_name.to_serialized_data() - - if table_name and not table_name.endswith("_SRCH"): - raise InvalidArgumentValueError('usage: The table name needs to end with _SRCH') - - # pylint:disable=too-many-locals def create_log_analytics_workspace_table(cmd, resource_group_name, workspace_name, table_name, columns=None, retention_in_days=None, total_retention_in_days=None, plan=None, description=None, no_wait=False): + from azure.cli.core.azclierror import InvalidArgumentValueError, ArgumentUsageError, RequiredArgumentMissingError + from azure.cli.command_modules.monitor.operations.latest.monitor.log_analytics.workspace.table._create \ + import WorkspaceTableCreate + if retention_in_days and total_retention_in_days: if total_retention_in_days < retention_in_days: raise InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time' @@ -286,6 +143,9 @@ def create_log_analytics_workspace_table_search_job(cmd, resource_group_name, wo search_query, start_search_time, end_search_time, retention_in_days=None, total_retention_in_days=None, limit=None, no_wait=False): + from azure.cli.command_modules.monitor.operations.latest.monitor.log_analytics.workspace.table._create \ + import WorkspaceTableCreate + return WorkspaceTableCreate(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "table_name": table_name, @@ -305,6 +165,9 @@ def create_log_analytics_workspace_table_search_job(cmd, resource_group_name, wo def create_log_analytics_workspace_table_restore(cmd, resource_group_name, workspace_name, table_name, start_restore_time, end_restore_time, restore_source_table, no_wait=False): + from azure.cli.command_modules.monitor.operations.latest.monitor.log_analytics.workspace.table._create \ + import WorkspaceTableCreate + return WorkspaceTableCreate(cli_ctx=cmd.cli_ctx)(command_args={ "resource_group": resource_group_name, "table_name": table_name, @@ -321,6 +184,10 @@ def create_log_analytics_workspace_table_restore(cmd, resource_group_name, works def update_log_analytics_workspace_table(cmd, resource_group_name, workspace_name, table_name, columns=None, retention_in_days=None, total_retention_in_days=None, plan=None, description=None, no_wait=False): + from azure.cli.core.azclierror import ArgumentUsageError + from azure.cli.command_modules.monitor.operations.latest.monitor.log_analytics.workspace.table._update \ + import WorkspaceTableUpdate + columns_list = None if columns: columns_list = [] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py index 53ccd0fbe46..fe98a0b6280 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py @@ -3,18 +3,9 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=too-many-locals, line-too-long, protected-access, too-many-nested-blocks -import antlr4 +# Class MetricsAlertUpdate moved to operations/latest/monitor/metrics/alert/_update.py -from azure.cli.command_modules.monitor.actions import AAZCustomListArg -from azure.cli.command_modules.monitor.grammar.metric_alert import MetricAlertConditionLexer, \ - MetricAlertConditionParser, MetricAlertConditionValidator -from azure.cli.core.aaz import has_value -from azure.cli.core.azclierror import InvalidArgumentValueError -from azure.mgmt.core.tools import is_valid_resource_id, resource_id from knack.log import get_logger -from msrest.serialization import Serializer - -from ..aaz.latest.monitor.metrics.alert import Update as _MetricsAlertUpdate logger = get_logger(__name__) @@ -24,6 +15,10 @@ def create_metric_alert(cmd, resource_group_name, rule_name, scopes, condition, disabled=False, description=None, tags=None, actions=None, severity=2, window_size='5m', evaluation_frequency='1m', auto_mitigate=None, target_resource_type=None, target_resource_region=None): + from azure.cli.command_modules.monitor.aaz.latest.monitor.metrics.alert._create import Create + from azure.cli.core.azclierror import InvalidArgumentValueError + from msrest.serialization import Serializer + # generate metadata for the conditions is_dynamic_threshold_criterion = False all_of = [] @@ -70,7 +65,6 @@ def create_metric_alert(cmd, resource_group_name, rule_name, scopes, condition, target_resource_type = resource_type target_resource_region = target_resource_region if target_resource_region else 'global' - from ..aaz.latest.monitor.metrics.alert import Create return Create(cli_ctx=cmd.cli_ctx)(command_args={ 'resource_group': resource_group_name, 'name': rule_name, @@ -90,201 +84,6 @@ def create_metric_alert(cmd, resource_group_name, rule_name, scopes, condition, }) -class MetricsAlertUpdate(_MetricsAlertUpdate): - def __init__(self, loader=None, cli_ctx=None, callbacks=None, **kwargs): - super().__init__(loader, cli_ctx, callbacks, **kwargs) - self.add_actions = [] - self.add_conditions = [] - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZListArg, AAZStrArg, AAZResourceIdArg, AAZResourceIdArgFormat - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.add_actions = AAZCustomListArg( - options=["--add-actions"], - singular_options=["--add-action"], - arg_group="Action", - help="Add an action group and optional webhook properties to fire when the alert is triggered.\n\n" - "Usage: --add-action ACTION_GROUP_NAME_OR_ID [KEY=VAL [KEY=VAL ...]]\n\n" - "Multiple action groups can be specified by using more than one `--add-action` argument." - ) - args_schema.add_actions.Element = AAZCustomListArg() - args_schema.add_actions.Element.Element = AAZStrArg() - args_schema.remove_actions = AAZListArg( - options=["--remove-actions"], - arg_group="Action", - help="Space-separated list of action group names to remove." - ) - args_schema.remove_actions.Element = AAZResourceIdArg( - fmt=AAZResourceIdArgFormat( - template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Insights" - "/actionGroups/{}" - ) - ) - args_schema.add_conditions = AAZCustomListArg( - options=["--add-conditions"], - singular_options=["--add-condition"], - arg_group="Condition", - help="Add a condition which triggers the rule.\n\n" - "Usage: --add-condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n" - "[{=,!=,>,>=,<,<=} THRESHOLD]\n" - "[{>,><,<} dynamic SENSITIVITY VIOLATIONS of EVALUATIONS [since DATETIME]]\n" - "[where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n" - "[and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n\n" - "Sensitivity can be 'low', 'medium', 'high'.\n\n" - "Violations can be the number of violations to trigger an alert. It should be smaller or equal to evaluation.\n\n" - "Evaluations can be the number of evaluation periods for dynamic threshold.\n\n" - "Datetime can be the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format).\n\n" - "Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be queried by combining them with the 'and' keyword.\n\n" - "Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az monitor metrics list-definitions` command.\n\n" - "Due to server limitation, when an alert rule contains multiple criterias, the use of dimensions is limited to one value per dimension within each criterion.\n\n" - "Multiple conditions can be specified by using more than one `--add-condition` argument." - ) - args_schema.add_conditions.Element = AAZListArg() - args_schema.add_conditions.Element.Element = AAZStrArg() - args_schema.remove_conditions = AAZListArg( - options=["--remove-conditions"], - arg_group="Condition", - help="Space-separated list of condition names to remove." - ) - args_schema.remove_conditions.Element = AAZStrArg() - - return args_schema - - def pre_operations(self): - def complete_action_group_id(name): - if is_valid_resource_id(name): - return name - - return resource_id( - subscription=self.ctx.subscription_id, - resource_group=self.ctx.args.resource_group, - namespace="Microsoft.Insights", - type="actionGroups", - name=name - ) - - args = self.ctx.args - if has_value(args.add_actions): - self.add_actions = [] - for add_action in args.add_actions: - values = add_action.to_serialized_data()[0].split() - action_group_id = complete_action_group_id(values[0]) - try: - webhook_property_candidates = dict(x.split('=', 1) for x in values[1:]) if len(values) > 1 else None - except ValueError: - err_msg = "Value of --add-action is invalid. Please refer to --help to get insight of correct format." - raise InvalidArgumentValueError(err_msg) - - action = { - "action_group_id": action_group_id, - "web_hook_properties": webhook_property_candidates - } - action["odatatype"] = "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models." \ - "Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.Action" - - self.add_actions.append(action) - - if has_value(args.add_conditions): - err_msg = 'usage error: --condition {avg,min,max,total,count} [NAMESPACE.]METRIC\n' \ - ' [{=,!=,>,>=,<,<=} THRESHOLD]\n' \ - ' [{<,>,><} dynamic SENSITIVITY VIOLATION of EVALUATION [since DATETIME]]\n' \ - ' [where DIMENSION {includes,excludes} VALUE [or VALUE ...]\n' \ - ' [and DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]\n' \ - ' [with skipmetricvalidation]' - - self.add_conditions = [] - for add_condition in args.add_conditions: - string_val = add_condition.to_serialized_data()[0] - lexer = MetricAlertConditionLexer(antlr4.InputStream(string_val)) - stream = antlr4.CommonTokenStream(lexer) - parser = MetricAlertConditionParser(stream) - tree = parser.expression() - - try: - validator = MetricAlertConditionValidator() - walker = antlr4.ParseTreeWalker() - walker.walk(validator, tree) - metric_condition = validator.result() - if "static" in metric_condition: - # static metric criteria - for item in ['time_aggregation', 'metric_name', 'operator', 'threshold']: - if item not in metric_condition["static"]: - raise InvalidArgumentValueError(err_msg) - elif "dynamic" in metric_condition: - # dynamic metric criteria - for item in ['time_aggregation', 'metric_name', 'operator', 'alert_sensitivity', - 'failing_periods']: - if item not in metric_condition["dynamic"]: - raise InvalidArgumentValueError(err_msg) - else: - raise NotImplementedError() - except (AttributeError, TypeError, KeyError): - raise InvalidArgumentValueError(err_msg) - - self.add_conditions.append(metric_condition) - - def pre_instance_update(self, instance): - def get_next_name(): - idx = 0 - while True: - possible_name = f"cond{idx}" - match = next((cond for cond in instance.properties.criteria.all_of if cond.name == possible_name), None) - if match: - idx += 1 - continue - - return possible_name - - args = self.ctx.args - if has_value(args.remove_actions): - to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_actions)) - - new_actions = [] - for action in instance.properties.actions: - if action.action_group_id.to_serialized_data().lower() not in to_be_removed: - new_actions.append(action) - - instance.properties.actions = new_actions - - if has_value(args.add_actions): - to_be_added = set(map(lambda x: x["action_group_id"].lower(), self.add_actions)) - - new_actions = [] - for action in instance.properties.actions: - if action.action_group_id.to_serialized_data().lower() not in to_be_added: - new_actions.append(action) - new_actions.extend(self.add_actions) - - instance.properties.actions = new_actions - - if has_value(args.remove_conditions): - to_be_removed = set(map(lambda x: x.to_serialized_data().lower(), args.remove_conditions)) - - new_conditions = [] - for cond in instance.properties.criteria.all_of: - if cond.name.to_serialized_data().lower() not in to_be_removed: - new_conditions.append(cond) - - instance.properties.criteria.all_of = new_conditions - - if has_value(args.add_conditions): - for cond in self.add_conditions: - if "dynamic" in cond: - item = cond["dynamic"] - item["name"] = get_next_name() - item["criterion_type"] = "DynamicThresholdCriterion" - item["ignore_data_before"] = Serializer.serialize_iso(dt) if (dt := item.pop("ignore_data_before", None)) else None - - instance.properties.criteria.all_of.append(item) - else: - item = cond["static"] - item["name"] = get_next_name() - item["criterion_type"] = "StaticThresholdCriterion" - - instance.properties.criteria.all_of.append(item) - - def create_metric_alert_dimension(dimension_name, value_list, operator=None): values = ' or '.join(value_list) return '{} {} {} {}'.format(_metric_alert_dimension_prefix, dimension_name, operator, values) @@ -336,6 +135,7 @@ def _parse_action_removals(actions): def _parse_resource_and_scope_type(scopes): from azure.mgmt.core.tools import parse_resource_id + from azure.cli.core.azclierror import InvalidArgumentValueError if not scopes: raise InvalidArgumentValueError('scopes cannot be null.') diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py index 89f7c2677bf..c670909dbae 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/monitor_clone_util.py @@ -5,9 +5,7 @@ # pylint: disable=line-too-long, protected-access from knack.log import get_logger from knack.util import CLIError -from azure.mgmt.core.tools import parse_resource_id from azure.cli.core.commands.transform import _parse_id -from azure.cli.command_modules.network.custom import _convert_to_snake_case from azure.cli.command_modules.monitor.util import gen_guid logger = get_logger(__name__) @@ -15,8 +13,11 @@ def _get_metrics_alert_rules_clone_list(cmd, source_resource, target_resource): + from azure.mgmt.core.tools import parse_resource_id + from azure.cli.command_modules.network.custom import _convert_to_snake_case + subscription_id = parse_resource_id(source_resource)['subscription'] - from ..aaz.latest.monitor.metrics.alert import List + from ..aaz.latest.monitor.metrics.alert._list import List alert_rules = List(cli_ctx=cmd.cli_ctx)(command_args={"subscription": subscription_id}) alert_rules = _convert_to_snake_case(alert_rules) for alert_rule in alert_rules: @@ -29,6 +30,8 @@ def _get_metrics_alert_rules_clone_list(cmd, source_resource, target_resource): def _add_into_existing_scopes(cmd, source_resource, alert_rule, target_resource): + from azure.mgmt.core.tools import parse_resource_id + subscription_id = parse_resource_id(source_resource)['subscription'] resource_group_name, name = _parse_id(alert_rule['id']).values() # pylint: disable=unbalanced-dict-unpacking command_args = { @@ -37,11 +40,13 @@ def _add_into_existing_scopes(cmd, source_resource, alert_rule, target_resource) "name": name, "scopes": alert_rule['scopes'] + [target_resource] } - from ..aaz.latest.monitor.metrics.alert import Update + from ..aaz.latest.monitor.metrics.alert._update import Update return Update(cli_ctx=cmd.cli_ctx)(command_args=command_args) def _clone_and_replace_action_group(cmd, source_resource, alert_rule, action_group_mapping, target_resource): + from azure.mgmt.core.tools import parse_resource_id + source_subscription_id = parse_resource_id(source_resource)['subscription'] target_subscription_id = parse_resource_id(target_resource)['subscription'] for index, action in enumerate(alert_rule['actions']): @@ -49,14 +54,15 @@ def _clone_and_replace_action_group(cmd, source_resource, alert_rule, action_gro alert_rule['actions'][index] = action_group_mapping[action['action_group_id']][1] else: resource_group_name, name = _parse_id(action["action_group_id"]).values() # pylint: disable=unbalanced-dict-unpacking - from ..aaz.latest.monitor.action_group import Show + from ..aaz.latest.monitor.action_group._show import Show action_group = Show(cli_ctx=cmd.cli_ctx)(command_args={ 'subscription': source_subscription_id, "resource_group": resource_group_name, "action_group_name": name, }) - from .action_groups import ActionGroupCreate + from azure.cli.command_modules.monitor.operations.latest.monitor.action_group._create \ + import ActionGroupCreate name = CLONED_NAME.format(name, gen_guid()) resource_group_name, _ = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking action_group["subscription"] = target_subscription_id @@ -73,6 +79,8 @@ def _clone_and_replace_action_group(cmd, source_resource, alert_rule, action_gro def format_metrics_alert_req(alert_rule): + from azure.cli.command_modules.network.custom import _convert_to_snake_case + all_of = alert_rule["criteria"]["all_of"] odata_type = alert_rule["criteria"]["odata.type"] otype = odata_type.split(".")[-1] @@ -88,6 +96,8 @@ def format_metrics_alert_req(alert_rule): def _clone_alert_rule(cmd, alert_rule, target_resource): + from azure.mgmt.core.tools import parse_resource_id + alert_rule['scopes'] = [target_resource] resource_group_name, name = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking name = CLONED_NAME.format(name, gen_guid()) @@ -96,7 +106,7 @@ def _clone_alert_rule(cmd, alert_rule, target_resource): alert_rule["resource_group"] = resource_group_name alert_rule["name"] = name format_metrics_alert_req(alert_rule) - from ..aaz.latest.monitor.metrics.alert import Create + from ..aaz.latest.monitor.metrics.alert._create import Create return Create(cli_ctx=cmd.cli_ctx)(command_args=alert_rule) @@ -126,6 +136,8 @@ def _clone_monitor_metrics_alerts(cmd, source_resource, target_resource, always_ def _is_resource_type_same_and_sub_same(source_resource, target_resource): + from azure.mgmt.core.tools import parse_resource_id + source_dict = parse_resource_id(source_resource.lower()) target_dict = parse_resource_id(target_resource.lower()) same_rp = source_dict['namespace'] == target_dict['namespace'] and source_dict['type'] == target_dict['type'] diff --git a/src/azure-cli/azure/cli/command_modules/monitor/operations/private_link_scope.py b/src/azure-cli/azure/cli/command_modules/monitor/operations/private_link_scope.py index c55463d77b5..7fad5a0962d 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/operations/private_link_scope.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/operations/private_link_scope.py @@ -3,16 +3,15 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # pylint: disable=line-too-long, protected-access -from azure.cli.core.aaz import has_value, register_command -from azure.cli.core.azclierror import ArgumentUsageError -from azure.cli.core.util import parse_proxy_resource_id - -from ..aaz.latest.monitor.private_link_scope import Create as _PrivateLinkScopeCreate -from ..aaz.latest.monitor.private_link_scope.private_endpoint_connection import Delete as _ConnectionDelete, \ - Show as _ConnectionShow, Update +# Classes moved to operations/latest/monitor/private_link_scope/ +# Helper function remains here and is imported by the tree files. def validate_private_endpoint_connection_id(args): + from azure.cli.core.aaz import has_value + from azure.cli.core.azclierror import ArgumentUsageError + from azure.cli.core.util import parse_proxy_resource_id + if has_value(args.id): data = parse_proxy_resource_id(args.id.to_serialized_data()) args.name = data["child_name_1"] @@ -22,105 +21,3 @@ def validate_private_endpoint_connection_id(args): if not all([has_value(args.name), has_value(args.resource_group), has_value(args.scope_name)]): err_msg = "Incorrect usage. Please provide [--id ID] or [--n NAME -g NAME --scope-name NAME]." raise ArgumentUsageError(error_msg=err_msg) - - -class PrivateLinkScopeCreate(_PrivateLinkScopeCreate): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.location._required = False - args_schema.location._registered = False - - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.location = "global" - - -class ConnectionDelete(_ConnectionDelete): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZStrArg - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.id = AAZStrArg( - options=["--id"], - help="ID of the private endpoint connection associated with the private link scope. " - "Values from `az monitor private-link-scope show`." - ) - args_schema.name._required = False - args_schema.resource_group._required = False - args_schema.scope_name._required = False - - return args_schema - - def pre_operations(self): - validate_private_endpoint_connection_id(self.ctx.args) - - -class ConnectionShow(_ConnectionShow): - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - from azure.cli.core.aaz import AAZStrArg - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.id = AAZStrArg( - options=["--id"], - help="ID of the private endpoint connection associated with the private link scope. " - "Values from `az monitor private-link-scope show`." - ) - args_schema.name._required = False - args_schema.resource_group._required = False - args_schema.scope_name._required = False - - return args_schema - - def pre_operations(self): - validate_private_endpoint_connection_id(self.ctx.args) - - -@register_command("monitor private-link-scope private-endpoint-connection approve") -class ConnectionApprove(Update): - """ Approve a private endpoint connection of a private link scope resource. - - :example: Approve a private endpoint connection of a private link scope resource. - az monitor private-link-scope private-endpoint-connection approve --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.status._registered = False - args_schema.name._required = False - args_schema.resource_group._required = False - args_schema.scope_name._required = False - - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.status = "Approved" - validate_private_endpoint_connection_id(args) - - -@register_command("monitor private-link-scope private-endpoint-connection reject") -class ConnectionReject(Update): - """ Reject a private endpoint connection of a private link scope resource. - - :example: Reject a private endpoint connection of a private link scope resource. - az monitor private-link-scope private-endpoint-connection reject --name MyPrivateEndpointConnection --resource-group MyResourceGroup --scope-name MyScope - """ - - @classmethod - def _build_arguments_schema(cls, *args, **kwargs): - args_schema = super()._build_arguments_schema(*args, **kwargs) - args_schema.status._registered = False - args_schema.name._required = False - args_schema.resource_group._required = False - args_schema.scope_name._required = False - - return args_schema - - def pre_operations(self): - args = self.ctx.args - args.status = "Rejected" - validate_private_endpoint_connection_id(args) diff --git a/src/azure-cli/azure/cli/command_modules/monitor/tests/latest/test_monitor_general_operations.py b/src/azure-cli/azure/cli/command_modules/monitor/tests/latest/test_monitor_general_operations.py index bdb052ba736..82a44efe383 100644 --- a/src/azure-cli/azure/cli/command_modules/monitor/tests/latest/test_monitor_general_operations.py +++ b/src/azure-cli/azure/cli/command_modules/monitor/tests/latest/test_monitor_general_operations.py @@ -44,7 +44,8 @@ def test_monitor_clone_vm_metric_alerts_scenario(self, resource_group): self.check('evaluationFrequency', 'PT1M'), self.check('length(scopes)', 2) ]) - with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): + with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid), \ + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): self.cmd('monitor clone --source-resource {vm1_id} --target-resource {vm3_id}', checks=[ self.check('metricsAlert[0].description', 'High CPU'), self.check('metricsAlert[0].severity', 2), @@ -96,7 +97,8 @@ def test_monitor_clone_storage_metric_alerts_scenario(self, resource_group, stor self.check('length(criteria.allOf[1].dimensions)', 1) ]) - with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): + with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid), \ + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): self.cmd('monitor clone --source-resource {sa_id} --target-resource {sa_id_2}', checks=[ self.check('metricsAlert[0].description', 'Test'), self.check('metricsAlert[0].severity', 2), @@ -162,7 +164,8 @@ def test_monitor_clone_storage_metric_alerts_always_scenario(self, resource_grou self.check('length(criteria.allOf[1].dimensions)', 1) ]) - with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): + with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid), \ + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): self.cmd('monitor clone --source-resource {sa_id} --target-resource {sa_id_2} --always-clone', checks=[ self.check('metricsAlert[0].description', 'Test'), self.check('metricsAlert[0].severity', 2), @@ -221,7 +224,8 @@ def test_monitor_clone_public_ip_metric_alerts_scenario(self, resource_group): self.check('length(scopes)', 1) ]) - with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): + with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid), \ + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): self.cmd('monitor clone --source-resource {ip1_id} --target-resource {ip2_id}', checks=[ self.check('length(metricsAlert)', 2), ]) @@ -273,7 +277,8 @@ def test_monitor_clone_storage_metric_alerts_across_subs_scenario(self, resource self.check('length(criteria.allOf[1].dimensions)', 1) ]) - with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): + with mock.patch('azure.cli.command_modules.monitor.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid), \ + mock.patch('azure.cli.command_modules.monitor._legacy.operations.monitor_clone_util.gen_guid', side_effect=self.create_guid): self.cmd('monitor clone --source-resource {sa_id} --target-resource {sa_id_2}', checks=[ self.check('metricsAlert[0].description', 'Test'), self.check('metricsAlert[0].severity', 2),