code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def _set_aladdin_recommendations(self): # pylint: disable=too-many-locals
"""Set Aladdin recommendations.
Call the API, parse the response and set aladdin_recommendations.
"""
import hashlib
import json
import requests
from requests import RequestException
from http import HTTPStatus
from azure.cli.core import __version__ as version
api_url = 'https://app.aladdin.microsoft.com/api/v1.0/suggestions'
correlation_id = telemetry._session.correlation_id # pylint: disable=protected-access
subscription_id = telemetry._get_azure_subscription_id() # pylint: disable=protected-access
event_id = telemetry._session.event_id # pylint: disable=protected-access
# Used for DDOS protection and rate limiting
user_id = telemetry._get_user_azure_id() # pylint: disable=protected-access
hashed_user_id = hashlib.sha256(user_id.encode('utf-8')).hexdigest()
headers = {
'Content-Type': 'application/json',
'X-UserId': hashed_user_id
}
context = {
'versionNumber': version,
'errorType': get_error_type(self.error_msg)
}
if telemetry.is_telemetry_enabled():
if correlation_id:
context['correlationId'] = correlation_id
if subscription_id:
context['subscriptionId'] = subscription_id
if event_id:
context['eventId'] = event_id
parameters = self._normalize_parameters(self.parameters)
parameters = [item for item in set(parameters) if item not in ['--debug', '--verbose', '--only-show-errors']]
query = {
"command": self.command,
"parameters": ','.join(parameters)
}
response = None
try:
response = requests.get(
api_url,
params={
'query': json.dumps(query),
'clientType': 'AzureCli',
'context': json.dumps(context)
},
headers=headers,
timeout=1)
telemetry.set_debug_info('AladdinResponseTime', response.elapsed.total_seconds())
except RequestException as ex:
logger.debug('Recommendation requests.get() exception: %s', ex)
telemetry.set_debug_info('AladdinException', ex.__class__.__name__)
recommendations = []
if response and response.status_code == HTTPStatus.OK:
for result in response.json():
# parse the response to get the raw command
raw_command = 'az {} '.format(result['command'])
for parameter, placeholder in zip(result['parameters'].split(','), result['placeholders'].split('♠')):
raw_command += '{} {}{}'.format(parameter, placeholder, ' ' if placeholder else '')
# format the recommendation
recommendation = {
'command': raw_command.strip(),
'description': result['description'],
'link': result['link']
}
recommendations.append(recommendation)
self.aladdin_recommendations.extend(recommendations) | Set Aladdin recommendations.
Call the API, parse the response and set aladdin_recommendations. | _set_aladdin_recommendations | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def sort_recommendations(recommendations):
"""Sort the recommendations by parameter matching.
The sorting rules below are applied in order:
1. Commands starting with the user's input command name are ahead of those don't
2. Commands having more matched arguments are ahead of those having less
3. Commands having less arguments are ahead of those having more
:param recommendations: The unordered recommendations
:type recommendations: list
:return: The ordered recommendations
:type: list
"""
candidates = []
target_arg_list = self._normalize_parameters(self.parameters)
for recommendation in recommendations:
matches = 0
arg_list = self._normalize_parameters(recommendation['command'].split(' '))
# ignore commands that do not start with the use's input command name
if recommendation['command'].startswith('az {}'.format(self.command)):
for arg in arg_list:
if arg in target_arg_list:
matches += 1
else:
matches = -1
candidates.append({
'recommendation': recommendation,
'arg_list': arg_list,
'matches': matches
})
# sort the candidates by the number of matched arguments and total arguments
candidates.sort(key=lambda item: (item['matches'], -len(item['arg_list'])), reverse=True)
return [candidate['recommendation'] for candidate in candidates] | Sort the recommendations by parameter matching.
The sorting rules below are applied in order:
1. Commands starting with the user's input command name are ahead of those don't
2. Commands having more matched arguments are ahead of those having less
3. Commands having less arguments are ahead of those having more
:param recommendations: The unordered recommendations
:type recommendations: list
:return: The ordered recommendations
:type: list | provide_recommendations.sort_recommendations | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def replace_param_values(command): # pylint: disable=unused-variable
"""Replace the parameter values in a command with user's input values
:param command: The command whose parameter value needs to be replaced
:type command: str
:return: The command with parameter values being replaced
:type: str
"""
# replace the parameter values only when the recommended
# command's name is the same with user's input command name
if not command.startswith('az {}'.format(self.command)):
return command
source_kwargs = get_parameter_kwargs(self.parameters)
param_mappings = self._get_param_mappings()
return replace_parameter_values(command, source_kwargs, param_mappings) | Replace the parameter values in a command with user's input values
:param command: The command whose parameter value needs to be replaced
:type command: str
:return: The command with parameter values being replaced
:type: str | provide_recommendations.replace_param_values | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def provide_recommendations(self):
"""Provide recommendations when a command fails.
The recommendations are either from Aladdin service or CLI help examples,
which include both commands and reference links along with their descriptions.
:return: The decorated recommendations
:type: list
"""
from azure.cli.core.style import Style, highlight_command
from azure.cli.core.parser import OVERVIEW_REFERENCE
def sort_recommendations(recommendations):
"""Sort the recommendations by parameter matching.
The sorting rules below are applied in order:
1. Commands starting with the user's input command name are ahead of those don't
2. Commands having more matched arguments are ahead of those having less
3. Commands having less arguments are ahead of those having more
:param recommendations: The unordered recommendations
:type recommendations: list
:return: The ordered recommendations
:type: list
"""
candidates = []
target_arg_list = self._normalize_parameters(self.parameters)
for recommendation in recommendations:
matches = 0
arg_list = self._normalize_parameters(recommendation['command'].split(' '))
# ignore commands that do not start with the use's input command name
if recommendation['command'].startswith('az {}'.format(self.command)):
for arg in arg_list:
if arg in target_arg_list:
matches += 1
else:
matches = -1
candidates.append({
'recommendation': recommendation,
'arg_list': arg_list,
'matches': matches
})
# sort the candidates by the number of matched arguments and total arguments
candidates.sort(key=lambda item: (item['matches'], -len(item['arg_list'])), reverse=True)
return [candidate['recommendation'] for candidate in candidates]
def replace_param_values(command): # pylint: disable=unused-variable
"""Replace the parameter values in a command with user's input values
:param command: The command whose parameter value needs to be replaced
:type command: str
:return: The command with parameter values being replaced
:type: str
"""
# replace the parameter values only when the recommended
# command's name is the same with user's input command name
if not command.startswith('az {}'.format(self.command)):
return command
source_kwargs = get_parameter_kwargs(self.parameters)
param_mappings = self._get_param_mappings()
return replace_parameter_values(command, source_kwargs, param_mappings)
# do not recommend commands if it is disabled by config
if self.cli_ctx and self.cli_ctx.config.get('core', 'error_recommendation', 'on').upper() == 'OFF':
return []
# get recommendations from Aladdin service
if not self._disable_aladdin_service():
self._set_aladdin_recommendations()
# recommendations are either all from Aladdin or all from help examples
recommendations = self.aladdin_recommendations
if not recommendations:
recommendations = self.help_examples
# sort the recommendations by parameter matching, get the top 3 recommended commands
recommendations = sort_recommendations(recommendations)[:3]
raw_commands = []
decorated_recommendations = []
for recommendation in recommendations:
# generate raw commands recorded in Telemetry
raw_command = recommendation['command']
raw_commands.append(raw_command)
# disable the parameter replacement feature because it will make command description inaccurate
# raw_command = replace_param_values(raw_command)
# generate decorated commands shown to users
decorated_command = highlight_command(raw_command)
decorated_description = [(
Style.SECONDARY,
recommendation.get('description', 'No description is found.') + '\n'
)]
decorated_recommendations.append((decorated_command, decorated_description))
# add reference link as a recommendation
decorated_link = [(Style.HYPERLINK, OVERVIEW_REFERENCE)]
if self.aladdin_recommendations:
decorated_link = [(Style.HYPERLINK, self.aladdin_recommendations[0]['link'])]
decorated_description = [(Style.SECONDARY, 'Read more about the command in reference docs')]
decorated_recommendations.append((decorated_link, decorated_description))
# set the recommend command into Telemetry
self._set_recommended_command_to_telemetry(raw_commands)
return decorated_recommendations | Provide recommendations when a command fails.
The recommendations are either from Aladdin service or CLI help examples,
which include both commands and reference links along with their descriptions.
:return: The decorated recommendations
:type: list | provide_recommendations | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def _set_recommended_command_to_telemetry(self, raw_commands):
"""Set the recommended commands to Telemetry
Aladdin recommended commands and commands from CLI help examples are
set to different properties in Telemetry.
:param raw_commands: The recommended raw commands
:type raw_commands: list
"""
if self.aladdin_recommendations:
telemetry.set_debug_info('AladdinRecommendCommand', ';'.join(raw_commands))
else:
telemetry.set_debug_info('ExampleRecommendCommand', ';'.join(raw_commands)) | Set the recommended commands to Telemetry
Aladdin recommended commands and commands from CLI help examples are
set to different properties in Telemetry.
:param raw_commands: The recommended raw commands
:type raw_commands: list | _set_recommended_command_to_telemetry | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def _disable_aladdin_service(self):
"""Decide whether to disable aladdin request when a command fails.
The possible cases to disable it are:
1. CLI context is missing
2. In air-gapped clouds
3. In testing environments
4. In autocomplete mode
:return: whether Aladdin service need to be disabled or not
:type: bool
"""
from azure.cli.core.cloud import CLOUDS_FORBIDDING_ALADDIN_REQUEST
# CLI is not started well
if not self.cli_ctx or not self.cli_ctx.cloud:
return True
# for air-gapped clouds
if self.cli_ctx.cloud.name in CLOUDS_FORBIDDING_ALADDIN_REQUEST:
return True
# for testing environments
if self.cli_ctx.__class__.__name__ == 'DummyCli':
return True
if self.cli_ctx.data['completer_active']:
return True
return False | Decide whether to disable aladdin request when a command fails.
The possible cases to disable it are:
1. CLI context is missing
2. In air-gapped clouds
3. In testing environments
4. In autocomplete mode
:return: whether Aladdin service need to be disabled or not
:type: bool | _disable_aladdin_service | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def _normalize_parameters(self, args):
"""Normalize a parameter list.
Get the standard parameter name list of the raw parameters, which includes:
1. Use long options to replace short options
2. Remove the unrecognized parameter names
3. Sort the parameter names by their lengths
An example: ['-g', 'RG', '-n', 'NAME'] ==> ['--resource-group', '--name']
:param args: The raw arg list of a command
:type args: list
:return: A standard, valid and sorted parameter name list
:type: list
"""
from azure.cli.core.commands import AzCliCommandInvoker
parameters = AzCliCommandInvoker._extract_parameter_names(args) # pylint: disable=protected-access
normalized_parameters = []
param_mappings = self._get_param_mappings()
for parameter in parameters:
if parameter in param_mappings:
normalized_form = param_mappings.get(parameter, None) or parameter
normalized_parameters.append(normalized_form)
else:
logger.debug('"%s" is an invalid parameter for command "%s".', parameter, self.command)
return sorted(normalized_parameters) | Normalize a parameter list.
Get the standard parameter name list of the raw parameters, which includes:
1. Use long options to replace short options
2. Remove the unrecognized parameter names
3. Sort the parameter names by their lengths
An example: ['-g', 'RG', '-n', 'NAME'] ==> ['--resource-group', '--name']
:param args: The raw arg list of a command
:type args: list
:return: A standard, valid and sorted parameter name list
:type: list | _normalize_parameters | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def get_parameter_mappings(command_table):
"""Get the short option to long option mappings of a command
:param parameter_table: CLI command object
:type parameter_table: knack.commands.CLICommand
:param command_name: The command name
:type command name: str
:return: The short to long option mappings of the parameters
:type: dict
"""
from knack.deprecation import Deprecated
parameter_table = None
if hasattr(command_table, 'arguments'):
parameter_table = command_table.arguments
param_mappings = {
'-h': '--help',
'-o': '--output',
'--only-show-errors': None,
'--help': None,
'--output': None,
'--query': None,
'--debug': None,
'--verbose': None,
'--yes': None,
'--no-wait': None
}
if parameter_table:
for argument in parameter_table.values():
options = argument.type.settings['options_list']
options = [option for option in options if not isinstance(option, Deprecated)]
# skip the positional arguments
if not options:
continue
try:
sorted_options = sorted(options, key=len, reverse=True)
standard_form = sorted_options[0]
for option in sorted_options[1:]:
param_mappings[option] = standard_form
param_mappings[standard_form] = standard_form
except TypeError:
logger.debug('Unexpected argument options `%s` of type `%s`.', options, type(options).__name__)
return param_mappings | Get the short option to long option mappings of a command
:param parameter_table: CLI command object
:type parameter_table: knack.commands.CLICommand
:param command_name: The command name
:type command name: str
:return: The short to long option mappings of the parameters
:type: dict | get_parameter_mappings | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def get_parameter_kwargs(args):
"""Get parameter name-value mappings from the raw arg list
An example: ['-g', 'RG', '--name=NAME'] ==> {'-g': 'RG', '--name': 'NAME'}
:param args: The raw arg list of a command
:type args: list
:return: The parameter name-value mappings
:type: dict
"""
parameter_kwargs = {}
for index, parameter in enumerate(args):
if parameter.startswith('-'):
param_name, param_val = parameter, None
if '=' in parameter:
pieces = parameter.split('=')
param_name, param_val = pieces[0], pieces[1]
elif index + 1 < len(args) and not args[index + 1].startswith('-'):
param_val = args[index + 1]
if param_val is not None and ' ' in param_val:
param_val = '"{}"'.format(param_val)
parameter_kwargs[param_name] = param_val
return parameter_kwargs | Get parameter name-value mappings from the raw arg list
An example: ['-g', 'RG', '--name=NAME'] ==> {'-g': 'RG', '--name': 'NAME'}
:param args: The raw arg list of a command
:type args: list
:return: The parameter name-value mappings
:type: dict | get_parameter_kwargs | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def get_user_param_value(target_param):
"""Get the value that is used as the replaced value of target_param
:param target_param: The parameter name whose value needs to be replaced
:type target_param: str
:return: The replaced value for target_param
:type: str
"""
standard_source_kwargs = {}
for param, val in source_kwargs.items():
if param in param_mappings:
standard_param = param_mappings[param]
standard_source_kwargs[standard_param] = val
if target_param in param_mappings:
standard_target_param = param_mappings[target_param]
if standard_target_param in standard_source_kwargs:
return standard_source_kwargs[standard_target_param]
return None | Get the value that is used as the replaced value of target_param
:param target_param: The parameter name whose value needs to be replaced
:type target_param: str
:return: The replaced value for target_param
:type: str | replace_parameter_values.get_user_param_value | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def replace_parameter_values(target_command, source_kwargs, param_mappings):
"""Replace the parameter values in target_command with values in source_kwargs
:param target_command: The command in which the parameter values need to be replaced
:type target_command: str
:param source_kwargs: The source key-val pairs used to replace the values
:type source_kwargs: dict
:param param_mappings: The short-long option mappings in terms of the target_command
:type param_mappings: dict
:returns: The target command with parameter values being replaced
:type: str
"""
def get_user_param_value(target_param):
"""Get the value that is used as the replaced value of target_param
:param target_param: The parameter name whose value needs to be replaced
:type target_param: str
:return: The replaced value for target_param
:type: str
"""
standard_source_kwargs = {}
for param, val in source_kwargs.items():
if param in param_mappings:
standard_param = param_mappings[param]
standard_source_kwargs[standard_param] = val
if target_param in param_mappings:
standard_target_param = param_mappings[target_param]
if standard_target_param in standard_source_kwargs:
return standard_source_kwargs[standard_target_param]
return None
command_args = target_command.split(' ')
for index, arg in enumerate(command_args):
if arg.startswith('-') and index + 1 < len(command_args) and not command_args[index + 1].startswith('-'):
user_param_val = get_user_param_value(arg)
if user_param_val:
command_args[index + 1] = user_param_val
return ' '.join(command_args) | Replace the parameter values in target_command with values in source_kwargs
:param target_command: The command in which the parameter values need to be replaced
:type target_command: str
:param source_kwargs: The source key-val pairs used to replace the values
:type source_kwargs: dict
:param param_mappings: The short-long option mappings in terms of the target_command
:type param_mappings: dict
:returns: The target command with parameter values being replaced
:type: str | replace_parameter_values | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/command_recommender.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/command_recommender.py | MIT |
def hash256_result(func):
"""
Secure the return string of the annotated function with SHA256 algorithm. If the annotated function doesn't return
string or return None, raise ValueError.
"""
@wraps(func)
def _decorator(*args, **kwargs):
val = func(*args, **kwargs)
if val is None:
raise ValueError('Return value is None')
if not isinstance(val, str):
raise ValueError('Return value is not string')
if not val:
return val
hash_object = hashlib.sha256(val.encode('utf-8'))
return str(hash_object.hexdigest())
return _decorator | Secure the return string of the annotated function with SHA256 algorithm. If the annotated function doesn't return
string or return None, raise ValueError. | hash256_result | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/decorators.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/decorators.py | MIT |
def retry(retry_times=3, interval=0.5, exceptions=Exception):
"""Use optimistic locking to call a function, so that multiple processes can
access the same resource (such as a file) at the same time.
:param retry_times: Times to retry.
:param interval: Interval between retries.
:param exceptions: Exceptions that can be ignored. Use a tuple if multiple exceptions should be ignored.
"""
def _decorator(func):
@wraps(func)
def _wrapped_func(*args, **kwargs):
for attempt in range(1, retry_times + 1):
try:
return func(*args, **kwargs)
except exceptions: # pylint: disable=broad-except
if attempt < retry_times:
logger.debug("%s failed in No. %d attempt", func, attempt)
import traceback
import time
logger.debug(traceback.format_exc())
time.sleep(interval)
else:
raise # End of retry. Re-raise the exception as-is.
return _wrapped_func
return _decorator | Use optimistic locking to call a function, so that multiple processes can
access the same resource (such as a file) at the same time.
:param retry_times: Times to retry.
:param interval: Interval between retries.
:param exceptions: Exceptions that can be ignored. Use a tuple if multiple exceptions should be ignored. | retry | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/decorators.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/decorators.py | MIT |
def __init__(self, name, actions, scopes=None):
""" Local Context Attribute arguments
:param name: Argument name in local context. Make sure it is consistent for SET and GET.
:type name: str
:param actions: Which action should be taken for local context. Allowed values: SET, GET
:type actions: list
:param scopes: The effective commands or command groups of this argument when saved to local context.
:type scopes: list
"""
self.name = name
if isinstance(actions, str):
actions = [actions]
self.actions = actions
if isinstance(scopes, str):
scopes = [scopes]
if scopes is None and LocalContextAction.SET in actions:
scopes = [ALL]
self.scopes = scopes | Local Context Attribute arguments
:param name: Argument name in local context. Make sure it is consistent for SET and GET.
:type name: str
:param actions: Which action should be taken for local context. Allowed values: SET, GET
:type actions: list
:param scopes: The effective commands or command groups of this argument when saved to local context.
:type scopes: list | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/local_context.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/local_context.py | MIT |
def load_command_table(self, command_loader):
"""Load a command table into our parser."""
# If we haven't already added a subparser, we
# better do it.
cmd_tbl = command_loader.command_table
grp_tbl = command_loader.command_group_table
if not self.subparsers:
sp = self.add_subparsers(dest='_command_package')
sp.required = True
self.subparsers = {(): sp}
for command_name, metadata in cmd_tbl.items():
subparser = self._get_subparser(command_name.split(), grp_tbl)
deprecate_info = metadata.deprecate_info
if not subparser or (deprecate_info and deprecate_info.expired()):
continue
command_verb = command_name.split()[-1]
# inject command_module designer's help formatter -- default is HelpFormatter
fc = metadata.formatter_class or argparse.HelpFormatter
command_parser = subparser.add_parser(command_verb,
description=metadata.description,
parents=self.parents,
conflict_handler='error',
help_file=metadata.help,
formatter_class=fc,
cli_help=self.cli_help,
_command_source=metadata.command_source)
self.subparser_map[command_name] = command_parser
command_parser.cli_ctx = self.cli_ctx
command_validator = metadata.validator
argument_validators = []
argument_groups = {}
for _, arg in metadata.arguments.items():
# don't add deprecated arguments to the parser
deprecate_info = arg.type.settings.get('deprecate_info', None)
if deprecate_info and deprecate_info.expired():
continue
if arg.validator:
argument_validators.append(arg.validator)
try:
if arg.arg_group:
try:
group = argument_groups[arg.arg_group]
except KeyError:
# group not found so create
group_name = '{} Arguments'.format(arg.arg_group)
group = command_parser.add_argument_group(arg.arg_group, group_name)
argument_groups[arg.arg_group] = group
param = AzCliCommandParser._add_argument(group, arg)
else:
param = AzCliCommandParser._add_argument(command_parser, arg)
except argparse.ArgumentError as ex:
raise CLIError("command authoring error for '{}': '{}' {}".format(
command_name, ex.args[0].dest, ex.message)) # pylint: disable=no-member
param.completer = arg.completer
param.deprecate_info = arg.deprecate_info
param.preview_info = arg.preview_info
param.experimental_info = arg.experimental_info
param.default_value_source = arg.default_value_source
command_parser.set_defaults(
func=metadata,
command=command_name,
_cmd=metadata,
_command_validator=command_validator,
_argument_validators=argument_validators,
_parser=command_parser) | Load a command table into our parser. | load_command_table | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/parser.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/parser.py | MIT |
def _rgb_hex(rgb_hex: str):
"""
Convert RGB hex value to Control Sequences.
"""
template = '\x1b[38;2;{r};{g};{b}m'
if rgb_hex.startswith("#"):
rgb_hex = rgb_hex[1:]
rgb = {}
for i, c in enumerate(('r', 'g', 'b')):
value_str = rgb_hex[i * 2: i * 2 + 2]
value_int = int(value_str, 16)
rgb[c] = value_int
return template.format(**rgb) | Convert RGB hex value to Control Sequences. | _rgb_hex | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/style.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/style.py | MIT |
def print_styled_text(*styled_text_objects, file=None, **kwargs):
"""
Print styled text. This function wraps the built-in function `print`, additional arguments can be sent
via keyword arguments.
:param styled_text_objects: The input text objects. See format_styled_text for formats of each object.
:param file: The file to print the styled text. The default target is sys.stderr.
"""
formatted_list = [format_styled_text(obj) for obj in styled_text_objects]
# Always fetch the latest sys.stderr in case it has been wrapped by colorama.
print(*formatted_list, file=file or sys.stderr, **kwargs) | Print styled text. This function wraps the built-in function `print`, additional arguments can be sent
via keyword arguments.
:param styled_text_objects: The input text objects. See format_styled_text for formats of each object.
:param file: The file to print the styled text. The default target is sys.stderr. | print_styled_text | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/style.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/style.py | MIT |
def format_styled_text(styled_text, theme=None):
"""Format styled text. Dark theme used by default. Available themes are 'dark', 'light', 'none'.
To change theme for all invocations of this function, set `format_styled_text.theme`.
To change theme for one invocation, set parameter `theme`.
:param styled_text: Can be in these formats:
- text
- (style, text)
- [(style, text), ...]
:param theme: The theme used to format text. Can be theme name str, `Theme` Enum or dict.
"""
if theme is None:
theme = getattr(format_styled_text, "theme", THEME_DARK)
# Convert str to the theme dict
if isinstance(theme, str):
theme = get_theme_dict(theme)
# If style is enabled, cache the value of is_legacy_powershell.
# Otherwise if theme is None, is_legacy_powershell is meaningless.
is_legacy_powershell = None
if theme:
if not hasattr(format_styled_text, "_is_legacy_powershell"):
from azure.cli.core.util import get_parent_proc_name
is_legacy_powershell = not is_modern_terminal() and get_parent_proc_name() == "powershell.exe"
setattr(format_styled_text, "_is_legacy_powershell", is_legacy_powershell)
is_legacy_powershell = getattr(format_styled_text, "_is_legacy_powershell")
# https://python-prompt-toolkit.readthedocs.io/en/stable/pages/printing_text.html#style-text-tuples
formatted_parts = []
# A str as PRIMARY text
if isinstance(styled_text, str):
styled_text = [(Style.PRIMARY, styled_text)]
# A tuple
if isinstance(styled_text, tuple):
styled_text = [styled_text]
for text in styled_text:
# str can also be indexed, bypassing IndexError, so explicitly check if the type is tuple
if not (isinstance(text, tuple) and len(text) == 2):
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid styled text. It should be a list of 2-element tuples.")
style, raw_text = text
if theme:
try:
escape_seq = theme[style]
except KeyError:
if style.startswith('\x1b['):
escape_seq = style
else:
from azure.cli.core.azclierror import CLIInternalError
raise CLIInternalError("Invalid style. Please use pre-defined style in Style enum "
"or give a valid ANSI code.")
# Replace blue in powershell.exe
if is_legacy_powershell and escape_seq in POWERSHELL_COLOR_REPLACEMENT:
escape_seq = POWERSHELL_COLOR_REPLACEMENT[escape_seq]
formatted_parts.append(escape_seq + raw_text)
else:
formatted_parts.append(raw_text)
# Reset control sequence
if theme is not THEME_NONE:
formatted_parts.append(DEFAULT)
return ''.join(formatted_parts) | Format styled text. Dark theme used by default. Available themes are 'dark', 'light', 'none'.
To change theme for all invocations of this function, set `format_styled_text.theme`.
To change theme for one invocation, set parameter `theme`.
:param styled_text: Can be in these formats:
- text
- (style, text)
- [(style, text), ...]
:param theme: The theme used to format text. Can be theme name str, `Theme` Enum or dict. | format_styled_text | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/style.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/style.py | MIT |
def highlight_command(raw_command):
"""Highlight a command with colors.
For example, for
az group create --name myrg --location westus
The command name 'az group create', argument name '--name', '--location' are marked as ACTION style.
The argument value 'myrg' and 'westus' are marked as PRIMARY style.
If the argument is provided as '--location=westus', it will be marked as PRIMARY style.
:param raw_command: The command that needs to be highlighted.
:type raw_command: str
:return: The styled command text.
:rtype: list
"""
styled_command = []
argument_begins = False
for index, arg in enumerate(raw_command.split()):
spaced_arg = ' {}'.format(arg) if index > 0 else arg
style = Style.PRIMARY
if arg.startswith('-') and '=' not in arg:
style = Style.ACTION
argument_begins = True
elif not argument_begins and '=' not in arg:
style = Style.ACTION
styled_command.append((style, spaced_arg))
return styled_command | Highlight a command with colors.
For example, for
az group create --name myrg --location westus
The command name 'az group create', argument name '--name', '--location' are marked as ACTION style.
The argument value 'myrg' and 'westus' are marked as PRIMARY style.
If the argument is provided as '--location=westus', it will be marked as PRIMARY style.
:param raw_command: The command that needs to be highlighted.
:type raw_command: str
:return: The styled command text.
:rtype: list | highlight_command | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/style.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/style.py | MIT |
def is_containing_credential(content, is_file=False):
"""Check if the given content contains credential or not.
:param content: The content or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:param max_level: the max level of credential to check.
:type max_level: int.
:returns: bool.
"""
if is_file:
with open(content, 'r') as f:
content = f.read()
elif not isinstance(content, str):
try:
content = json.dumps(content)
except TypeError:
content = str(content)
except ValueError:
raise ValueError('The content is not string or json object.')
return get_secret_masker().detect_secrets(content) | Check if the given content contains credential or not.
:param content: The content or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:param max_level: the max level of credential to check.
:type max_level: int.
:returns: bool. | is_containing_credential | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/credential_helper.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/credential_helper.py | MIT |
def distinguish_credential(content, is_file=False):
"""Distinguish which property contains credential from the given content.
:param content: The content(can be string or json object) or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:param max_level: the max level of credential to check.
:type max_level: int.
:returns: bool, set.
"""
containing_credential = False
secret_property_names = set()
secret_names = set()
if is_file:
with open(content, 'r') as f:
content = json.load(f)
if isinstance(content, list):
for item in content:
_containing_credential, _secret_property_names, _secret_names = distinguish_credential(item)
containing_credential = containing_credential or _containing_credential
secret_property_names.update(_secret_property_names)
secret_names.update(_secret_names)
return containing_credential, secret_property_names, secret_names
if isinstance(content, dict):
for key, value in content.items():
_containing_credential, _secret_property_names, _secret_names = distinguish_credential(value)
containing_credential = containing_credential or _containing_credential
secret_property_names.update(_secret_property_names)
if _containing_credential:
secret_property_names.add(key)
secret_names.update(_secret_names)
return containing_credential, secret_property_names, secret_names
detections = is_containing_credential(content)
if detections:
containing_credential = True
for detection in detections:
secret_names.add(detection.name)
return containing_credential, secret_property_names, secret_names | Distinguish which property contains credential from the given content.
:param content: The content(can be string or json object) or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:param max_level: the max level of credential to check.
:type max_level: int.
:returns: bool, set. | distinguish_credential | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/credential_helper.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/credential_helper.py | MIT |
def redact_credential(content, is_file=False):
"""Redact credential for the given content.
:param content: The content(can be string or json object) or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:returns: processed content.
"""
if is_file:
fp = content
with open(fp, 'r') as f:
content = f.read()
content = redact_credential_for_string(content)
with open(fp, 'w') as f:
f.write(content)
return fp
if isinstance(content, str):
return redact_credential_for_string(content)
try:
content = json.dumps(content)
content = redact_credential_for_string(content)
return json.loads(content)
except ValueError:
raise ValueError('The content is not string or json object.') | Redact credential for the given content.
:param content: The content(can be string or json object) or the file path.
:type content: Any.
:param is_file: flag to clarify the content is file path or not.
:type is_file: bool.
:returns: processed content. | redact_credential | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/credential_helper.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/credential_helper.py | MIT |
def retrieve_arm_cloud_metadata():
""" Retrieve Cloud metadata from ARM endpoint api defined in ARM_CLOUD_METADATA_URL"""
if 'ARM_CLOUD_METADATA_URL' in os.environ:
return json.loads(urlretrieve(os.getenv('ARM_CLOUD_METADATA_URL'))) | Retrieve Cloud metadata from ARM endpoint api defined in ARM_CLOUD_METADATA_URL | retrieve_arm_cloud_metadata | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/cloud.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/cloud.py | MIT |
def get_default_cloud_name():
""" Pick AzureCloud as the default cloud if it is available, otherwise pick the first in the list"""
if CloudNameEnum.AzureCloud.lower() in [c.name.lower() for c in KNOWN_CLOUDS]:
return CloudNameEnum.AzureCloud
return KNOWN_CLOUDS[0].name | Pick AzureCloud as the default cloud if it is available, otherwise pick the first in the list | get_default_cloud_name | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/cloud.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/cloud.py | MIT |
def _config_add_cloud(config, cloud, overwrite=False):
""" Add a cloud to a config object """
try:
config.add_section(cloud.name)
except configparser.DuplicateSectionError:
if not overwrite:
raise CloudAlreadyRegisteredException(cloud.name)
if cloud.profile:
config.set(cloud.name, 'profile', cloud.profile)
for k, v in cloud.endpoints.__dict__.items():
if v is not None:
config.set(cloud.name, 'endpoint_{}'.format(k), v)
for k, v in cloud.suffixes.__dict__.items():
if v is not None:
config.set(cloud.name, 'suffix_{}'.format(k), v) | Add a cloud to a config object | _config_add_cloud | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/cloud.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/cloud.py | MIT |
def _delete_old_logs(log_dir):
"""
Periodically delete the 5 oldest command log files, ensuring that only the history of the last
25 commands (or less) are kept.
"""
# get log file names and sort them from newest to oldest file.
log_file_names = [file for file in os.listdir(log_dir) if file.endswith(".log")]
sorted_files = sorted(log_file_names, reverse=True)
# if we have too many files, delete the 5 last / oldest command log files.
if len(sorted_files) > 25:
for file in sorted_files[-5:]:
try:
os.remove(os.path.join(log_dir, file))
except OSError: # FileNotFoundError introduced in Python 3
continue | Periodically delete the 5 oldest command log files, ensuring that only the history of the last
25 commands (or less) are kept. | init_command_file_logging._delete_old_logs | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/azlogging.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/azlogging.py | MIT |
def init_command_file_logging(cli_ctx, **kwargs):
def _delete_old_logs(log_dir):
"""
Periodically delete the 5 oldest command log files, ensuring that only the history of the last
25 commands (or less) are kept.
"""
# get log file names and sort them from newest to oldest file.
log_file_names = [file for file in os.listdir(log_dir) if file.endswith(".log")]
sorted_files = sorted(log_file_names, reverse=True)
# if we have too many files, delete the 5 last / oldest command log files.
if len(sorted_files) > 25:
for file in sorted_files[-5:]:
try:
os.remove(os.path.join(log_dir, file))
except OSError: # FileNotFoundError introduced in Python 3
continue
# if tab-completion and not command don't log to file.
if not cli_ctx.data.get('completer_active', False):
self = cli_ctx.logging
args = kwargs['args']
metadata_logger = logging.getLogger(AzCliLogging.COMMAND_METADATA_LOGGER)
# Overwrite the default of knack.log.CLILogging._is_file_log_enabled() to True
self.file_log_enabled = cli_ctx.config.getboolean('logging', 'enable_log_file', fallback=True)
if self.file_log_enabled:
self._init_command_logfile_handlers(metadata_logger, args) # pylint: disable=protected-access
_delete_old_logs(self.command_log_dir) | Periodically delete the 5 oldest command log files, ensuring that only the history of the last
25 commands (or less) are kept. | init_command_file_logging | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/azlogging.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/azlogging.py | MIT |
def get_installed_cli_distributions():
# Stop importing pkg_resources, because importing it is slow (~200ms).
# from pkg_resources import working_set
# return [d for d in list(working_set) if d.key == CLI_PACKAGE_NAME or d.key.startswith(COMPONENT_PREFIX)]
# Use the hard-coded version instead of querying all modules under site-packages.
from azure.cli.core import __version__ as azure_cli_core_version
from azure.cli.telemetry import __version__ as azure_cli_telemetry_version
class VersionItem: # pylint: disable=too-few-public-methods
"""A mock of pkg_resources.EggInfoDistribution to maintain backward compatibility."""
def __init__(self, key, version):
self.key = key
self.version = version
return [
VersionItem('azure-cli', azure_cli_core_version),
VersionItem('azure-cli-core', azure_cli_core_version),
VersionItem('azure-cli-telemetry', azure_cli_telemetry_version)
] | A mock of pkg_resources.EggInfoDistribution to maintain backward compatibility. | get_installed_cli_distributions | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def get_cached_latest_versions(versions=None):
""" Get the latest versions from a cached file"""
import datetime
from azure.cli.core._session import VERSIONS
if not versions:
versions = _get_local_versions()
if VERSIONS[_VERSION_UPDATE_TIME]:
version_update_time = datetime.datetime.strptime(VERSIONS[_VERSION_UPDATE_TIME], '%Y-%m-%d %H:%M:%S.%f')
if datetime.datetime.now() < version_update_time + datetime.timedelta(days=1):
cache_versions = VERSIONS['versions']
if cache_versions and cache_versions['azure-cli']['local'] == versions['azure-cli']['local']:
return cache_versions.copy(), True
versions, success = _update_latest_from_github(versions)
VERSIONS['versions'] = versions
VERSIONS[_VERSION_UPDATE_TIME] = str(datetime.datetime.now())
return versions.copy(), success | Get the latest versions from a cached file | get_cached_latest_versions | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def get_json_object(json_string):
""" Loads a JSON string as an object and converts all keys to snake case """
def _convert_to_snake_case(item):
if isinstance(item, dict):
new_item = {}
for key, val in item.items():
new_item[to_snake_case(key)] = _convert_to_snake_case(val)
return new_item
if isinstance(item, list):
return [_convert_to_snake_case(x) for x in item]
return item
return _convert_to_snake_case(shell_safe_json_parse(json_string)) | Loads a JSON string as an object and converts all keys to snake case | get_json_object | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def shell_safe_json_parse(json_or_dict_string, preserve_order=False, strict=True):
""" Allows the passing of JSON or Python dictionary strings. This is needed because certain
JSON strings in CMD shell are not received in main's argv. This allows the user to specify
the alternative notation, which does not have this problem (but is technically not JSON). """
try:
if not preserve_order:
return json.loads(json_or_dict_string, strict=strict)
from collections import OrderedDict
return json.loads(json_or_dict_string, object_pairs_hook=OrderedDict, strict=strict)
except ValueError as json_ex:
try:
import ast
return ast.literal_eval(json_or_dict_string)
except Exception as ex:
logger.debug(ex) # log the exception which could be a python dict parsing error.
# Echo the string received by CLI. Because the user may intend to provide a file path, we don't decisively
# say it is a JSON string.
msg = "Failed to parse string as JSON:\n{}\nError detail: {}".format(json_or_dict_string, json_ex)
# Recommendation for all shells
from azure.cli.core.azclierror import InvalidArgumentValueError
recommendation = "The provided JSON string may have been parsed by the shell. See " \
"https://learn.microsoft.com/cli/azure/use-azure-cli-successfully-quoting#json-strings"
# Recommendation especially for PowerShell
parent_proc = get_parent_proc_name()
if parent_proc and parent_proc.lower() in ("powershell.exe", "pwsh.exe"):
recommendation += "\nPowerShell requires additional quoting rules. See " \
"https://github.com/Azure/azure-cli/blob/dev/doc/quoting-issues-with-powershell.md"
# Raise from json_ex error which is more likely to be the original error
raise InvalidArgumentValueError(msg, recommendation=recommendation) from json_ex | Allows the passing of JSON or Python dictionary strings. This is needed because certain
JSON strings in CMD shell are not received in main's argv. This allows the user to specify
the alternative notation, which does not have this problem (but is technically not JSON). | shell_safe_json_parse | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def b64encode(s):
"""
Encodes a string to base64 on 2.x and 3.x
:param str s: latin_1 encoded string
:return: base64 encoded string
:rtype: str
"""
encoded = base64.b64encode(s.encode("latin-1"))
return encoded if encoded is str else encoded.decode('latin-1') | Encodes a string to base64 on 2.x and 3.x
:param str s: latin_1 encoded string
:return: base64 encoded string
:rtype: str | b64encode | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def b64_to_hex(s):
"""
Decodes a string to base64 on 2.x and 3.x
:param str s: base64 encoded string
:return: uppercase hex string
:rtype: str
"""
decoded = base64.b64decode(s)
hex_data = binascii.hexlify(decoded).upper()
if isinstance(hex_data, bytes):
return str(hex_data.decode("utf-8"))
return hex_data | Decodes a string to base64 on 2.x and 3.x
:param str s: base64 encoded string
:return: uppercase hex string
:rtype: str | b64_to_hex | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def todict(obj, post_processor=None):
"""
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process
"""
from datetime import date, time, datetime, timedelta
from enum import Enum
if isinstance(obj, dict):
result = {k: todict(v, post_processor) for (k, v) in obj.items()}
return post_processor(obj, result) if post_processor else result
if isinstance(obj, list):
return [todict(a, post_processor) for a in obj]
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, (date, time, datetime)):
return obj.isoformat()
if isinstance(obj, timedelta):
return str(obj)
# This is the only difference with knack.util.todict because for typespec generated SDKs
# The base model stores data in obj.__dict__['_data'] instead of in obj.__dict__
# We need to call obj.as_dict() to extract data for this kind of model
if hasattr(obj, 'as_dict') and not hasattr(obj, '_attribute_map'):
result = {to_camel_case(k): todict(v, post_processor) for k, v in obj.as_dict().items()}
return post_processor(obj, result) if post_processor else result
if hasattr(obj, '_asdict'):
return todict(obj._asdict(), post_processor)
if hasattr(obj, '__dict__'):
result = {to_camel_case(k): todict(v, post_processor)
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')}
return post_processor(obj, result) if post_processor else result
return obj | Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process | todict | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def hash_string(value, length=16, force_lower=False):
""" Generate a deterministic hashed string."""
import hashlib
m = hashlib.sha256()
try:
m.update(value)
except TypeError:
m.update(value.encode())
digest = m.hexdigest()
digest = digest.lower() if force_lower else digest
while len(digest) < length:
digest = digest + digest
return digest[:length] | Generate a deterministic hashed string. | hash_string | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def is_track2(client_class):
""" IS this client a autorestv3/track2 one?.
Could be refined later if necessary.
"""
from inspect import getfullargspec as get_arg_spec
args = get_arg_spec(client_class.__init__).args
return "credential" in args | IS this client a autorestv3/track2 one?.
Could be refined later if necessary. | is_track2 | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def augment_no_wait_handler_args(no_wait_enabled, handler, handler_args):
""" Populates handler_args with the appropriate args for no wait """
h_args = get_arg_list(handler)
if 'no_wait' in h_args:
handler_args['no_wait'] = no_wait_enabled
if 'raw' in h_args and no_wait_enabled:
# support autorest 2
handler_args['raw'] = True
if 'polling' in h_args and no_wait_enabled:
# support autorest 3
handler_args['polling'] = False
# Support track2 SDK.
# In track2 SDK, there is no parameter 'polling' in SDK, but just use '**kwargs'.
# So we check the name of the operation to see if it's a long running operation.
# The name of long running operation in SDK is like 'begin_xxx_xxx'.
op_name = handler.__name__
if op_name and op_name.startswith('begin_') and no_wait_enabled:
handler_args['polling'] = False | Populates handler_args with the appropriate args for no wait | augment_no_wait_handler_args | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def _extract_subscription_id(url):
"""Extract the subscription ID from an ARM request URL."""
subscription_regex = '/subscriptions/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'
match = re.search(subscription_regex, url, re.IGNORECASE)
if match:
subscription_id = match.groups()[0]
logger.debug('Found subscription ID %s in the URL %s', subscription_id, url)
return subscription_id
logger.debug('No subscription ID specified in the URL %s', url)
return None | Extract the subscription ID from an ARM request URL. | _extract_subscription_id | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def _log_request(request):
"""Log a client request. Copied from msrest
https://github.com/Azure/msrest-for-python/blob/3653d29fc44da408898b07c710290a83d196b777/msrest/http_logger.py#L39
"""
if not logger.isEnabledFor(logging.DEBUG):
return
try:
logger.info("Request URL: %r", request.url)
logger.info("Request method: %r", request.method)
logger.info("Request headers:")
for header, value in request.headers.items():
if header.lower() == 'authorization':
# Trim at least half of the token but keep at most 20 characters
preserve_length = min(int(len(value) * 0.5), 20)
value = value[:preserve_length] + '...'
logger.info(" %r: %r", header, value)
logger.info("Request body:")
# We don't want to log the binary data of a file upload.
import types
if isinstance(request.body, types.GeneratorType):
logger.info("File upload")
else:
logger.info(str(request.body))
except Exception as err: # pylint: disable=broad-except
logger.info("Failed to log request: %r", err) | Log a client request. Copied from msrest
https://github.com/Azure/msrest-for-python/blob/3653d29fc44da408898b07c710290a83d196b777/msrest/http_logger.py#L39 | _log_request | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def _log_response(response, **kwargs):
"""Log a server response. Copied from msrest
https://github.com/Azure/msrest-for-python/blob/3653d29fc44da408898b07c710290a83d196b777/msrest/http_logger.py#L68
"""
if not logger.isEnabledFor(logging.DEBUG):
return None
try:
logger.info("Response status: %r", response.status_code)
logger.info("Response headers:")
for res_header, value in response.headers.items():
logger.info(" %r: %r", res_header, value)
# We don't want to log binary data if the response is a file.
logger.info("Response content:")
pattern = re.compile(r'attachment; ?filename=["\w.]+', re.IGNORECASE)
header = response.headers.get('content-disposition')
if header and pattern.match(header):
filename = header.partition('=')[2]
logger.info("File attachments: %s", filename)
elif response.headers.get("content-type", "").endswith("octet-stream"):
logger.info("Body contains binary data.")
elif response.headers.get("content-type", "").startswith("image"):
logger.info("Body contains image data.")
else:
if kwargs.get('stream', False):
logger.info("Body is streamable")
else:
logger.info(response.content.decode("utf-8-sig"))
return response
except Exception as err: # pylint: disable=broad-except
logger.info("Failed to log response: %s", repr(err))
return response | Log a server response. Copied from msrest
https://github.com/Azure/msrest-for-python/blob/3653d29fc44da408898b07c710290a83d196b777/msrest/http_logger.py#L68 | _log_response | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def parse_proxy_resource_id(rid):
"""Parses a resource_id into its various parts.
Return an empty dictionary, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
:rtype: dict[str,str]
"""
if not rid:
return {}
match = _PROXYID_RE.match(rid)
if match:
result = match.groupdict()
children = _CHILDREN_RE.finditer(result['children'] or '')
count = None
for count, child in enumerate(children):
result.update({
key + '_%d' % (count + 1): group for key, group in child.groupdict().items()})
result['last_child_num'] = count + 1 if isinstance(count, int) else None
result.pop('children', None)
return {key: value for key, value in result.items() if value is not None}
return None | Parses a resource_id into its various parts.
Return an empty dictionary, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
:rtype: dict[str,str] | parse_proxy_resource_id | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def get_az_rest_user_agent():
"""Get User-Agent for az rest calls"""
agents = ['python/{}'.format(platform.python_version()),
'({})'.format(platform.platform()),
get_az_user_agent()
]
return ' '.join(agents) | Get User-Agent for az rest calls | get_az_rest_user_agent | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def handle_version_update():
"""Clean up information in local files that may be invalidated
because of a version update of Azure CLI
"""
try:
from azure.cli.core._session import VERSIONS
from packaging.version import parse # pylint: disable=import-error,no-name-in-module
from azure.cli.core import __version__
if not VERSIONS['versions']:
get_cached_latest_versions()
elif parse(VERSIONS['versions']['core']['local']) != parse(__version__):
logger.debug("Azure CLI has been updated.")
logger.debug("Clean up versions and refresh cloud endpoints information in local files.")
VERSIONS['versions'] = {}
VERSIONS['update_time'] = ''
from azure.cli.core.cloud import refresh_known_clouds
refresh_known_clouds()
except Exception as ex: # pylint: disable=broad-except
logger.warning(ex) | Clean up information in local files that may be invalidated
because of a version update of Azure CLI | handle_version_update | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def is_modern_terminal():
"""In addition to knack.util.is_modern_terminal, detect Cloud Shell."""
import knack.util
return knack.util.is_modern_terminal() or in_cloud_console() | In addition to knack.util.is_modern_terminal, detect Cloud Shell. | is_modern_terminal | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def get_secret_store(cli_ctx, name):
"""Create a process-concurrency-safe azure.cli.core.auth.persistence.SecretStore instance that can be used to
save secret data.
"""
from azure.cli.core._environment import get_config_dir
from azure.cli.core.auth.persistence import load_secret_store
# Save to CLI's config dir, by default ~/.azure
location = os.path.join(get_config_dir(), name)
# We honor the system type (Windows, Linux, or MacOS) and global config
encrypt = should_encrypt_token_cache(cli_ctx)
return load_secret_store(location, encrypt) | Create a process-concurrency-safe azure.cli.core.auth.persistence.SecretStore instance that can be used to
save secret data. | get_secret_store | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def run_cmd(args, *, capture_output=False, timeout=None, check=False, encoding=None, env=None):
"""Run command in a subprocess. It reduces (not eliminates) shell injection by forcing args to be a list
and shell=False. Other arguments are keyword-only. For their documentation, see
https://docs.python.org/3/library/subprocess.html#subprocess.run
"""
if not isinstance(args, list):
from azure.cli.core.azclierror import ArgumentUsageError
raise ArgumentUsageError("Invalid args. run_cmd args must be a list")
import subprocess
return subprocess.run(args, capture_output=capture_output, timeout=timeout, check=check,
encoding=encoding, env=env) | Run command in a subprocess. It reduces (not eliminates) shell injection by forcing args to be a list
and shell=False. Other arguments are keyword-only. For their documentation, see
https://docs.python.org/3/library/subprocess.html#subprocess.run | run_cmd | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def run_az_cmd(args, out_file=None):
"""
run_az_cmd would run az related cmds during command execution
:param args: cmd to be executed, array of string, like `["az", "version"]`, "az" is optional
:param out_file: The file to send output to. file-like object
:return: cmd execution result object, containing `result`, `error`, `exit_code`
"""
from azure.cli.core.azclierror import ArgumentUsageError
if not isinstance(args, list):
raise ArgumentUsageError("Invalid args. run_az_cmd args must be a list")
if args[0] == "az":
args = args[1:]
from azure.cli.core import get_default_cli
cli = get_default_cli()
cli.invoke(args, out_file=out_file)
return cli.result | run_az_cmd would run az related cmds during command execution
:param args: cmd to be executed, array of string, like `["az", "version"]`, "az" is optional
:param out_file: The file to send output to. file-like object
:return: cmd execution result object, containing `result`, `error`, `exit_code` | run_az_cmd | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def getprop(o, name, *default):
""" This function is used to get the property of the object.
It will raise an error if the property is a private property or a method.
"""
if name.startswith('_'):
# avoid to access the private properties or methods
raise AttributeError(name)
v = getattr(o, name, *default)
if callable(v):
# avoid to access the methods
raise AttributeError(name)
return v | This function is used to get the property of the object.
It will raise an error if the property is a private property or a method. | getprop | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py | MIT |
def set_feedback(feedback):
""" This method is used for modules in which user feedback is collected. The data can be an arbitrary string but it
will be truncated at 512 characters to avoid abusing the telemetry."""
_session.feedback = feedback[:512] | This method is used for modules in which user feedback is collected. The data can be an arbitrary string but it
will be truncated at 512 characters to avoid abusing the telemetry. | set_feedback | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/telemetry.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/telemetry.py | MIT |
def _configure_knack():
"""Override consts defined in knack to make them Azure CLI-specific."""
# Customize status tag messages.
from knack.util import status_tag_messages
ref_message = "Reference and support levels: https://aka.ms/CLI_refstatus"
# Override the preview message.
status_tag_messages['preview'] = "{} is in preview and under development. " + ref_message
# Override the experimental message.
status_tag_messages['experimental'] = "{} is experimental and under development. " + ref_message
# Allow logs from 'azure' logger to be displayed.
from knack.log import cli_logger_names
cli_logger_names.append('azure') | Override consts defined in knack to make them Azure CLI-specific. | _configure_knack | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def refresh_request_id(self):
"""Assign a new random GUID as x-ms-client-request-id
The method must be invoked before each command execution in order to ensure
unique client-side request ID is generated.
"""
import uuid
self.data['headers']['x-ms-client-request-id'] = str(uuid.uuid1()) | Assign a new random GUID as x-ms-client-request-id
The method must be invoked before each command execution in order to ensure
unique client-side request ID is generated. | refresh_request_id | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def save_local_context(self, parsed_args, argument_definitions, specified_arguments):
""" Local Context Attribute arguments
Save argument value to local context if it is defined as SET and user specify a value for it.
:param parsed_args: Parsed args which return by AzCliCommandParser parse_args
:type parsed_args: Namespace
:param argument_definitions: All available argument definitions
:type argument_definitions: dict
:param specified_arguments: Arguments which user specify in this command
:type specified_arguments: list
"""
local_context_args = []
for argument_name in specified_arguments:
# make sure SET is defined
if argument_name not in argument_definitions:
continue
argtype = argument_definitions[argument_name].type
lca = argtype.settings.get('local_context_attribute', None)
if not lca or not lca.actions or LocalContextAction.SET not in lca.actions:
continue
# get the specified value
value = getattr(parsed_args, argument_name)
# save when name and scopes have value
if lca.name and lca.scopes:
self.local_context.set(lca.scopes, lca.name, value)
options = argtype.settings.get('options_list', None)
if options:
local_context_args.append((options[0], value))
# print warning if there are values saved to local context
if local_context_args:
logger.warning('Parameter persistence is turned on. Its information is saved in working directory %s. '
'You can run `az config param-persist off` to turn it off.',
self.local_context.effective_working_directory())
args_str = []
for name, value in local_context_args:
args_str.append('{}: {}'.format(name, value))
logger.warning('Your preference of %s now saved as persistent parameter. To learn more, type in `az '
'config param-persist --help`',
', '.join(args_str) + (' is' if len(args_str) == 1 else ' are')) | Local Context Attribute arguments
Save argument value to local context if it is defined as SET and user specify a value for it.
:param parsed_args: Parsed args which return by AzCliCommandParser parse_args
:type parsed_args: Namespace
:param argument_definitions: All available argument definitions
:type argument_definitions: dict
:param specified_arguments: Arguments which user specify in this command
:type specified_arguments: list | save_local_context | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def _update_command_table_from_modules(args, command_modules=None):
"""Loads command tables from modules and merge into the main command table.
:param args: Arguments of the command.
:param list command_modules: Command modules to load, in the format like ['resource', 'profile'].
If None, will do module discovery and load all modules.
If [], only ALWAYS_LOADED_MODULES will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_MODULES.
"""
# As command modules are built-in, the existence of modules in ALWAYS_LOADED_MODULES is NOT checked
if command_modules is not None:
command_modules.extend(ALWAYS_LOADED_MODULES)
else:
# Perform module discovery
command_modules = []
try:
mods_ns_pkg = import_module('azure.cli.command_modules')
command_modules = [modname for _, modname, _ in
pkgutil.iter_modules(mods_ns_pkg.__path__)]
logger.debug('Discovered command modules: %s', command_modules)
except ImportError as e:
logger.warning(e)
count = 0
cumulative_elapsed_time = 0
cumulative_group_count = 0
cumulative_command_count = 0
logger.debug("Loading command modules:")
logger.debug(self.header_mod)
for mod in [m for m in command_modules if m not in BLOCKED_MODS]:
try:
start_time = timeit.default_timer()
module_command_table, module_group_table = _load_module_command_loader(self, args, mod)
import_module_breaking_changes(mod)
for cmd in module_command_table.values():
cmd.command_source = mod
self.command_table.update(module_command_table)
self.command_group_table.update(module_group_table)
elapsed_time = timeit.default_timer() - start_time
logger.debug(self.item_format_string, mod, elapsed_time,
len(module_group_table), len(module_command_table))
count += 1
cumulative_elapsed_time += elapsed_time
cumulative_group_count += len(module_group_table)
cumulative_command_count += len(module_command_table)
except Exception as ex: # pylint: disable=broad-except
# Changing this error message requires updating CI script that checks for failed
# module loading.
from azure.cli.core import telemetry
logger.error("Error loading command module '%s': %s", mod, ex)
telemetry.set_exception(exception=ex, fault_type='module-load-error-' + mod,
summary='Error loading module: {}'.format(mod))
logger.debug(traceback.format_exc())
# Summary line
logger.debug(self.item_format_string,
"Total ({})".format(count), cumulative_elapsed_time,
cumulative_group_count, cumulative_command_count) | Loads command tables from modules and merge into the main command table.
:param args: Arguments of the command.
:param list command_modules: Command modules to load, in the format like ['resource', 'profile'].
If None, will do module discovery and load all modules.
If [], only ALWAYS_LOADED_MODULES will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_MODULES. | load_command_table._update_command_table_from_modules | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def _update_command_table_from_extensions(ext_suppressions, extension_modname=None):
"""Loads command tables from extensions and merge into the main command table.
:param ext_suppressions: Extension suppression information.
:param extension_modname: Command modules to load, in the format like ['azext_timeseriesinsights'].
If None, will do extension discovery and load all extensions.
If [], only ALWAYS_LOADED_EXTENSIONS will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_EXTENSIONS.
If the extensions in the list are not installed, it will be skipped.
"""
def _handle_extension_suppressions(extensions):
filtered_extensions = []
for ext in extensions:
should_include = True
for suppression in ext_suppressions:
if should_include and suppression.handle_suppress(ext):
should_include = False
if should_include:
filtered_extensions.append(ext)
return filtered_extensions
def _filter_modname(extensions):
# Extension's name may not be the same as its modname. eg. name: virtual-wan, modname: azext_vwan
filtered_extensions = []
for ext in extensions:
ext_mod = get_extension_modname(ext.name, ext.path)
# Filter the extensions according to the index
if ext_mod in extension_modname:
filtered_extensions.append(ext)
extension_modname.remove(ext_mod)
if extension_modname:
logger.debug("These extensions are not installed and will be skipped: %s", extension_modname)
return filtered_extensions
extensions = get_extensions()
if extensions:
if extension_modname is not None:
extension_modname.extend(ALWAYS_LOADED_EXTENSIONS)
extensions = _filter_modname(extensions)
allowed_extensions = _handle_extension_suppressions(extensions)
module_commands = set(self.command_table.keys())
count = 0
cumulative_elapsed_time = 0
cumulative_group_count = 0
cumulative_command_count = 0
logger.debug("Loading extensions:")
logger.debug(self.header_ext)
for ext in allowed_extensions:
try:
# Import in the `for` loop because `allowed_extensions` can be []. In such case we
# don't need to import `check_version_compatibility` at all.
from azure.cli.core.extension.operations import check_version_compatibility
check_version_compatibility(ext.get_metadata())
except CLIError as ex:
# issue warning and skip loading extensions that aren't compatible with the CLI core
logger.warning(ex)
continue
ext_name = ext.name
ext_dir = ext.path or get_extension_path(ext_name)
sys.path.append(ext_dir)
try:
ext_mod = get_extension_modname(ext_name, ext_dir=ext_dir)
# Add to the map. This needs to happen before we load commands as registering a command
# from an extension requires this map to be up-to-date.
# self._mod_to_ext_map[ext_mod] = ext_name
start_time = timeit.default_timer()
extension_command_table, extension_group_table = \
_load_extension_command_loader(self, args, ext_mod)
import_extension_breaking_changes(ext_mod)
for cmd_name, cmd in extension_command_table.items():
cmd.command_source = ExtensionCommandSource(
extension_name=ext_name,
overrides_command=cmd_name in module_commands,
preview=ext.preview,
experimental=ext.experimental)
self.command_table.update(extension_command_table)
self.command_group_table.update(extension_group_table)
elapsed_time = timeit.default_timer() - start_time
logger.debug(self.item_ext_format_string, ext_name, elapsed_time,
len(extension_group_table), len(extension_command_table),
ext_dir)
count += 1
cumulative_elapsed_time += elapsed_time
cumulative_group_count += len(extension_group_table)
cumulative_command_count += len(extension_command_table)
except Exception as ex: # pylint: disable=broad-except
self.cli_ctx.raise_event(EVENT_FAILED_EXTENSION_LOAD, extension_name=ext_name)
logger.warning("Unable to load extension '%s: %s'. Use --debug for more information.",
ext_name, ex)
logger.debug(traceback.format_exc())
# Summary line
logger.debug(self.item_ext_format_string,
"Total ({})".format(count), cumulative_elapsed_time,
cumulative_group_count, cumulative_command_count, "") | Loads command tables from extensions and merge into the main command table.
:param ext_suppressions: Extension suppression information.
:param extension_modname: Command modules to load, in the format like ['azext_timeseriesinsights'].
If None, will do extension discovery and load all extensions.
If [], only ALWAYS_LOADED_EXTENSIONS will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_EXTENSIONS.
If the extensions in the list are not installed, it will be skipped. | load_command_table._update_command_table_from_extensions | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def _wrap_suppress_extension_func(func, ext):
""" Wrapper method to handle centralization of log messages for extension filters """
res = func(ext)
should_suppress = res
reason = "Use --debug for more information."
if isinstance(res, tuple):
should_suppress, reason = res
suppress_types = (bool, type(None))
if not isinstance(should_suppress, suppress_types):
raise ValueError("Command module authoring error: "
"Valid extension suppression values are {} in {}".format(suppress_types, func))
if should_suppress:
logger.warning("Extension %s (%s) has been suppressed. %s",
ext.name, ext.version, reason)
logger.debug("Extension %s (%s) suppressed from being loaded due "
"to %s", ext.name, ext.version, func)
return should_suppress | Wrapper method to handle centralization of log messages for extension filters | load_command_table._wrap_suppress_extension_func | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def load_command_table(self, args):
from importlib import import_module
import pkgutil
import traceback
from azure.cli.core.commands import (
_load_module_command_loader, _load_extension_command_loader, BLOCKED_MODS, ExtensionCommandSource)
from azure.cli.core.extension import (
get_extensions, get_extension_path, get_extension_modname)
from azure.cli.core.breaking_change import (import_module_breaking_changes, import_extension_breaking_changes)
def _update_command_table_from_modules(args, command_modules=None):
"""Loads command tables from modules and merge into the main command table.
:param args: Arguments of the command.
:param list command_modules: Command modules to load, in the format like ['resource', 'profile'].
If None, will do module discovery and load all modules.
If [], only ALWAYS_LOADED_MODULES will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_MODULES.
"""
# As command modules are built-in, the existence of modules in ALWAYS_LOADED_MODULES is NOT checked
if command_modules is not None:
command_modules.extend(ALWAYS_LOADED_MODULES)
else:
# Perform module discovery
command_modules = []
try:
mods_ns_pkg = import_module('azure.cli.command_modules')
command_modules = [modname for _, modname, _ in
pkgutil.iter_modules(mods_ns_pkg.__path__)]
logger.debug('Discovered command modules: %s', command_modules)
except ImportError as e:
logger.warning(e)
count = 0
cumulative_elapsed_time = 0
cumulative_group_count = 0
cumulative_command_count = 0
logger.debug("Loading command modules:")
logger.debug(self.header_mod)
for mod in [m for m in command_modules if m not in BLOCKED_MODS]:
try:
start_time = timeit.default_timer()
module_command_table, module_group_table = _load_module_command_loader(self, args, mod)
import_module_breaking_changes(mod)
for cmd in module_command_table.values():
cmd.command_source = mod
self.command_table.update(module_command_table)
self.command_group_table.update(module_group_table)
elapsed_time = timeit.default_timer() - start_time
logger.debug(self.item_format_string, mod, elapsed_time,
len(module_group_table), len(module_command_table))
count += 1
cumulative_elapsed_time += elapsed_time
cumulative_group_count += len(module_group_table)
cumulative_command_count += len(module_command_table)
except Exception as ex: # pylint: disable=broad-except
# Changing this error message requires updating CI script that checks for failed
# module loading.
from azure.cli.core import telemetry
logger.error("Error loading command module '%s': %s", mod, ex)
telemetry.set_exception(exception=ex, fault_type='module-load-error-' + mod,
summary='Error loading module: {}'.format(mod))
logger.debug(traceback.format_exc())
# Summary line
logger.debug(self.item_format_string,
"Total ({})".format(count), cumulative_elapsed_time,
cumulative_group_count, cumulative_command_count)
def _update_command_table_from_extensions(ext_suppressions, extension_modname=None):
"""Loads command tables from extensions and merge into the main command table.
:param ext_suppressions: Extension suppression information.
:param extension_modname: Command modules to load, in the format like ['azext_timeseriesinsights'].
If None, will do extension discovery and load all extensions.
If [], only ALWAYS_LOADED_EXTENSIONS will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_EXTENSIONS.
If the extensions in the list are not installed, it will be skipped.
"""
def _handle_extension_suppressions(extensions):
filtered_extensions = []
for ext in extensions:
should_include = True
for suppression in ext_suppressions:
if should_include and suppression.handle_suppress(ext):
should_include = False
if should_include:
filtered_extensions.append(ext)
return filtered_extensions
def _filter_modname(extensions):
# Extension's name may not be the same as its modname. eg. name: virtual-wan, modname: azext_vwan
filtered_extensions = []
for ext in extensions:
ext_mod = get_extension_modname(ext.name, ext.path)
# Filter the extensions according to the index
if ext_mod in extension_modname:
filtered_extensions.append(ext)
extension_modname.remove(ext_mod)
if extension_modname:
logger.debug("These extensions are not installed and will be skipped: %s", extension_modname)
return filtered_extensions
extensions = get_extensions()
if extensions:
if extension_modname is not None:
extension_modname.extend(ALWAYS_LOADED_EXTENSIONS)
extensions = _filter_modname(extensions)
allowed_extensions = _handle_extension_suppressions(extensions)
module_commands = set(self.command_table.keys())
count = 0
cumulative_elapsed_time = 0
cumulative_group_count = 0
cumulative_command_count = 0
logger.debug("Loading extensions:")
logger.debug(self.header_ext)
for ext in allowed_extensions:
try:
# Import in the `for` loop because `allowed_extensions` can be []. In such case we
# don't need to import `check_version_compatibility` at all.
from azure.cli.core.extension.operations import check_version_compatibility
check_version_compatibility(ext.get_metadata())
except CLIError as ex:
# issue warning and skip loading extensions that aren't compatible with the CLI core
logger.warning(ex)
continue
ext_name = ext.name
ext_dir = ext.path or get_extension_path(ext_name)
sys.path.append(ext_dir)
try:
ext_mod = get_extension_modname(ext_name, ext_dir=ext_dir)
# Add to the map. This needs to happen before we load commands as registering a command
# from an extension requires this map to be up-to-date.
# self._mod_to_ext_map[ext_mod] = ext_name
start_time = timeit.default_timer()
extension_command_table, extension_group_table = \
_load_extension_command_loader(self, args, ext_mod)
import_extension_breaking_changes(ext_mod)
for cmd_name, cmd in extension_command_table.items():
cmd.command_source = ExtensionCommandSource(
extension_name=ext_name,
overrides_command=cmd_name in module_commands,
preview=ext.preview,
experimental=ext.experimental)
self.command_table.update(extension_command_table)
self.command_group_table.update(extension_group_table)
elapsed_time = timeit.default_timer() - start_time
logger.debug(self.item_ext_format_string, ext_name, elapsed_time,
len(extension_group_table), len(extension_command_table),
ext_dir)
count += 1
cumulative_elapsed_time += elapsed_time
cumulative_group_count += len(extension_group_table)
cumulative_command_count += len(extension_command_table)
except Exception as ex: # pylint: disable=broad-except
self.cli_ctx.raise_event(EVENT_FAILED_EXTENSION_LOAD, extension_name=ext_name)
logger.warning("Unable to load extension '%s: %s'. Use --debug for more information.",
ext_name, ex)
logger.debug(traceback.format_exc())
# Summary line
logger.debug(self.item_ext_format_string,
"Total ({})".format(count), cumulative_elapsed_time,
cumulative_group_count, cumulative_command_count, "")
def _wrap_suppress_extension_func(func, ext):
""" Wrapper method to handle centralization of log messages for extension filters """
res = func(ext)
should_suppress = res
reason = "Use --debug for more information."
if isinstance(res, tuple):
should_suppress, reason = res
suppress_types = (bool, type(None))
if not isinstance(should_suppress, suppress_types):
raise ValueError("Command module authoring error: "
"Valid extension suppression values are {} in {}".format(suppress_types, func))
if should_suppress:
logger.warning("Extension %s (%s) has been suppressed. %s",
ext.name, ext.version, reason)
logger.debug("Extension %s (%s) suppressed from being loaded due "
"to %s", ext.name, ext.version, func)
return should_suppress
def _get_extension_suppressions(mod_loaders):
res = []
for m in mod_loaders:
suppressions = getattr(m, 'suppress_extension', None)
if suppressions:
suppressions = suppressions if isinstance(suppressions, list) else [suppressions]
for sup in suppressions:
if isinstance(sup, ModExtensionSuppress):
res.append(sup)
return res
# Clear the tables to make this method idempotent
self.command_group_table.clear()
self.command_table.clear()
command_index = None
# Set fallback=False to turn off command index in case of regression
use_command_index = self.cli_ctx.config.getboolean('core', 'use_command_index', fallback=True)
if use_command_index:
command_index = CommandIndex(self.cli_ctx)
index_result = command_index.get(args)
if index_result:
index_modules, index_extensions = index_result
# Always load modules and extensions, because some of them (like those in
# ALWAYS_LOADED_EXTENSIONS) don't expose a command, but hooks into handlers in CLI core
_update_command_table_from_modules(args, index_modules)
# The index won't contain suppressed extensions
_update_command_table_from_extensions([], index_extensions)
logger.debug("Loaded %d groups, %d commands.", len(self.command_group_table), len(self.command_table))
from azure.cli.core.util import roughly_parse_command
# The index may be outdated. Make sure the command appears in the loaded command table
raw_cmd = roughly_parse_command(args)
for cmd in self.command_table:
if raw_cmd.startswith(cmd):
# For commands with positional arguments, the raw command won't match the one in the
# command table. For example, `az find vm create` won't exist in the command table, but the
# corresponding command should be `az find`.
# raw command : az find vm create
# command table: az find
# remaining : vm create
logger.debug("Found a match in the command table.")
logger.debug("Raw command : %s", raw_cmd)
logger.debug("Command table: %s", cmd)
remaining = raw_cmd[len(cmd) + 1:]
if remaining:
logger.debug("remaining : %s %s", ' ' * len(cmd), remaining)
return self.command_table
# For command group, it must be an exact match, as no positional argument is supported by
# command group operations.
if raw_cmd in self.command_group_table:
logger.debug("Found a match in the command group table for '%s'.", raw_cmd)
return self.command_table
if self.cli_ctx.data['completer_active']:
# If the command is not complete in autocomplete mode, we should match shorter command.
# For example, `account sho` should match `account`.
logger.debug("Could not find a match in the command or command group table for '%s'", raw_cmd)
trimmed_raw_cmd = ' '.join(raw_cmd.split()[:-1])
logger.debug("In autocomplete mode, try to match trimmed raw cmd: '%s'", trimmed_raw_cmd)
if not trimmed_raw_cmd:
# If full command is 'az acc', raw_cmd is 'acc', trimmed_raw_cmd is ''.
logger.debug("Trimmed raw cmd is empty, return command table.")
return self.command_table
if trimmed_raw_cmd in self.command_group_table:
logger.debug("Found a match in the command group table for trimmed raw cmd: '%s'.",
trimmed_raw_cmd)
return self.command_table
logger.debug("Could not find a match in the command or command group table for '%s'. "
"The index may be outdated.", raw_cmd)
else:
logger.debug("No module found from index for '%s'", args)
# No module found from the index. Load all command modules and extensions
logger.debug("Loading all modules and extensions")
_update_command_table_from_modules(args)
ext_suppressions = _get_extension_suppressions(self.loaders)
# We always load extensions even if the appropriate module has been loaded
# as an extension could override the commands already loaded.
_update_command_table_from_extensions(ext_suppressions)
logger.debug("Loaded %d groups, %d commands.", len(self.command_group_table), len(self.command_table))
if use_command_index:
command_index.update(self.command_table)
return self.command_table | Loads command tables from modules and merge into the main command table.
:param args: Arguments of the command.
:param list command_modules: Command modules to load, in the format like ['resource', 'profile'].
If None, will do module discovery and load all modules.
If [], only ALWAYS_LOADED_MODULES will be loaded.
Otherwise, the list will be extended using ALWAYS_LOADED_MODULES. | load_command_table | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def __init__(self, cli_ctx=None):
"""Class to manage command index.
:param cli_ctx: Only needed when `get` or `update` is called.
"""
from azure.cli.core._session import INDEX
self.INDEX = INDEX
if cli_ctx:
self.version = __version__
self.cloud_profile = cli_ctx.cloud.profile
self.cli_ctx = cli_ctx | Class to manage command index.
:param cli_ctx: Only needed when `get` or `update` is called. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def get(self, args):
"""Get the corresponding module and extension list of a command.
:param args: command arguments, like ['network', 'vnet', 'create', '-h']
:return: a tuple containing a list of modules and a list of extensions.
"""
# If the command index version or cloud profile doesn't match those of the current command,
# invalidate the command index.
index_version = self.INDEX[self._COMMAND_INDEX_VERSION]
cloud_profile = self.INDEX[self._COMMAND_INDEX_CLOUD_PROFILE]
if not (index_version and index_version == self.version and
cloud_profile and cloud_profile == self.cloud_profile):
logger.debug("Command index version or cloud profile is invalid or doesn't match the current command.")
self.invalidate()
return None
# Make sure the top-level command is provided, like `az version`.
# Skip command index for `az` or `az --help`.
if not args or args[0].startswith('-'):
return None
# Get the top-level command, like `network` in `network vnet create -h`
top_command = args[0]
index = self.INDEX[self._COMMAND_INDEX]
# Check the command index for (command: [module]) mapping, like
# "network": ["azure.cli.command_modules.natgateway", "azure.cli.command_modules.network", "azext_firewall"]
index_modules_extensions = index.get(top_command)
if not index_modules_extensions and self.cli_ctx.data['completer_active']:
# If user type `az acco`, command begin with `acco` will be matched.
logger.debug("In autocomplete mode, load commands starting with: '%s'", top_command)
index_modules_extensions = []
for command in index:
if command.startswith(top_command):
index_modules_extensions += index[command]
if index_modules_extensions:
# This list contains both built-in modules and extensions
index_builtin_modules = []
index_extensions = []
# Found modules from index
logger.debug("Modules found from index for '%s': %s", top_command, index_modules_extensions)
command_module_prefix = 'azure.cli.command_modules.'
for m in index_modules_extensions:
if m.startswith(command_module_prefix):
# The top-level command is from a command module
index_builtin_modules.append(m[len(command_module_prefix):])
elif m.startswith('azext_'):
# The top-level command is from an extension
index_extensions.append(m)
else:
logger.warning("Unrecognized module: %s", m)
return index_builtin_modules, index_extensions
return None | Get the corresponding module and extension list of a command.
:param args: command arguments, like ['network', 'vnet', 'create', '-h']
:return: a tuple containing a list of modules and a list of extensions. | get | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def update(self, command_table):
"""Update the command index according to the given command table.
:param command_table: The command table built by azure.cli.core.MainCommandsLoader.load_command_table
"""
start_time = timeit.default_timer()
self.INDEX[self._COMMAND_INDEX_VERSION] = __version__
self.INDEX[self._COMMAND_INDEX_CLOUD_PROFILE] = self.cloud_profile
from collections import defaultdict
index = defaultdict(list)
# self.cli_ctx.invocation.commands_loader.command_table doesn't exist in DummyCli due to the lack of invocation
for command_name, command in command_table.items():
# Get the top-level name: <vm> create
top_command = command_name.split()[0]
# Get module name, like azure.cli.command_modules.vm, azext_webapp
module_name = command.loader.__module__
if module_name not in index[top_command]:
index[top_command].append(module_name)
elapsed_time = timeit.default_timer() - start_time
self.INDEX[self._COMMAND_INDEX] = index
logger.debug("Updated command index in %.3f seconds.", elapsed_time) | Update the command index according to the given command table.
:param command_table: The command table built by azure.cli.core.MainCommandsLoader.load_command_table | update | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def invalidate(self):
"""Invalidate the command index.
This function MUST be called when installing or updating extensions. Otherwise, when an extension
1. overrides a built-in command, or
2. extends an existing command group,
the command or command group will only be loaded from the command modules as per the stale command index,
making the newly installed extension be ignored.
This function can be called when removing extensions.
"""
self.INDEX[self._COMMAND_INDEX_VERSION] = ""
self.INDEX[self._COMMAND_INDEX_CLOUD_PROFILE] = ""
self.INDEX[self._COMMAND_INDEX] = {}
logger.debug("Command index has been invalidated.") | Invalidate the command index.
This function MUST be called when installing or updating extensions. Otherwise, when an extension
1. overrides a built-in command, or
2. extends an existing command group,
the command or command group will only be loaded from the command modules as per the stale command index,
making the newly installed extension be ignored.
This function can be called when removing extensions. | invalidate | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def add_cli_command(self, name, command_operation, **kwargs):
"""Register a command in command_table with command operation provided"""
from knack.deprecation import Deprecated
from .commands.command_operation import BaseCommandOperation
if not issubclass(type(command_operation), BaseCommandOperation):
raise TypeError("CommandOperation must be an instance of subclass of BaseCommandOperation."
" Got instance of '{}'".format(type(command_operation)))
kwargs['deprecate_info'] = Deprecated.ensure_new_style_deprecation(self.cli_ctx, kwargs, 'command')
name = ' '.join(name.split())
if self.supported_api_version(resource_type=kwargs.get('resource_type'),
min_api=kwargs.get('min_api'),
max_api=kwargs.get('max_api'),
operation_group=kwargs.get('operation_group')):
self._populate_command_group_table_with_subgroups(' '.join(name.split()[:-1]))
self.command_table[name] = self.command_cls(loader=self,
name=name,
handler=command_operation.handler,
arguments_loader=command_operation.arguments_loader,
description_loader=command_operation.description_loader,
command_operation=command_operation,
**kwargs) | Register a command in command_table with command operation provided | add_cli_command | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def get_op_handler(self, operation, operation_group=None):
""" Import and load the operation handler """
# Patch the unversioned sdk path to include the appropriate API version for the
# resource type in question.
from importlib import import_module
import types
from azure.cli.core.profiles import AZURE_API_PROFILES
from azure.cli.core.profiles._shared import get_versioned_sdk_path
for rt in AZURE_API_PROFILES[self.cli_ctx.cloud.profile]:
if operation.startswith(rt.import_prefix + '.'):
operation = operation.replace(rt.import_prefix,
get_versioned_sdk_path(self.cli_ctx.cloud.profile, rt,
operation_group=operation_group))
break
try:
mod_to_import, attr_path = operation.split('#')
op = import_module(mod_to_import)
for part in attr_path.split('.'):
op = getattr(op, part)
if isinstance(op, types.FunctionType):
return op
return op.__func__
except (ValueError, AttributeError):
raise ValueError("The operation '{}' is invalid.".format(operation)) | Import and load the operation handler | get_op_handler | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/__init__.py | MIT |
def __init__(self, credential, auxiliary_credentials=None):
"""Credential adaptor between MSAL credential and SDK credential.
It implements Track 2 SDK's azure.core.credentials.TokenCredential by exposing get_token.
:param credential: MSAL credential from ._msal_credentials
:param auxiliary_credentials: MSAL credentials for cross-tenant authentication.
Details about cross-tenant authentication:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant
"""
self._credential = credential
self._auxiliary_credentials = auxiliary_credentials | Credential adaptor between MSAL credential and SDK credential.
It implements Track 2 SDK's azure.core.credentials.TokenCredential by exposing get_token.
:param credential: MSAL credential from ._msal_credentials
:param auxiliary_credentials: MSAL credentials for cross-tenant authentication.
Details about cross-tenant authentication:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | MIT |
def get_token(self, *scopes, **kwargs):
"""Get an access token from the main credential."""
logger.debug("CredentialAdaptor.get_token: scopes=%r, kwargs=%r", scopes, kwargs)
# Discard unsupported kwargs: tenant_id, enable_cae
filtered_kwargs = {}
if 'data' in kwargs:
filtered_kwargs['data'] = kwargs['data']
return build_sdk_access_token(self._credential.acquire_token(list(scopes), **filtered_kwargs)) | Get an access token from the main credential. | get_token | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | MIT |
def get_auxiliary_tokens(self, *scopes, **kwargs):
"""Get access tokens from auxiliary credentials."""
# To test cross-tenant authentication, see https://github.com/Azure/azure-cli/issues/16691
if self._auxiliary_credentials:
return [build_sdk_access_token(cred.acquire_token(list(scopes), **kwargs))
for cred in self._auxiliary_credentials]
return None | Get access tokens from auxiliary credentials. | get_auxiliary_tokens | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/credential_adaptor.py | MIT |
def __init__(self, authority, tenant_id=None, client_id=None, encrypt=False, use_msal_http_cache=True,
enable_broker_on_windows=None, instance_discovery=None):
"""
:param authority: Authentication authority endpoint. For example,
- AAD: https://login.microsoftonline.com
- ADFS: https://adfs.redmond.azurestack.corp.microsoft.com/adfs
:param tenant_id: Tenant GUID, like 00000000-0000-0000-0000-000000000000. If unspecified, default to
'organizations'.
:param client_id: Client ID of the CLI application.
:param encrypt: Whether to encrypt MSAL token cache and service principal entries.
"""
self.authority = authority
self.tenant_id = tenant_id
self.client_id = client_id or AZURE_CLI_CLIENT_ID
self._encrypt = encrypt
self._use_msal_http_cache = use_msal_http_cache
self._enable_broker_on_windows = enable_broker_on_windows
self._instance_discovery = instance_discovery
# Build the authority in MSAL style
self._msal_authority, self._is_adfs = _get_authority_url(authority, tenant_id)
config_dir = get_config_dir()
self._token_cache_file = os.path.join(config_dir, "msal_token_cache")
self._secret_file = os.path.join(config_dir, "service_principal_entries")
self._msal_http_cache_file = os.path.join(config_dir, "msal_http_cache.bin")
# We make _msal_app_instance an instance attribute, instead of a class attribute,
# because MSAL apps can have different tenant IDs.
self._msal_app_instance = None | :param authority: Authentication authority endpoint. For example,
- AAD: https://login.microsoftonline.com
- ADFS: https://adfs.redmond.azurestack.corp.microsoft.com/adfs
:param tenant_id: Tenant GUID, like 00000000-0000-0000-0000-000000000000. If unspecified, default to
'organizations'.
:param client_id: Client ID of the CLI application.
:param encrypt: Whether to encrypt MSAL token cache and service principal entries. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def _msal_app_kwargs(self):
"""kwargs for creating ClientApplication (including its subclass ConfidentialClientApplication).
MSAL token cache and HTTP cache are lazily created.
"""
if not Identity._msal_token_cache:
Identity._msal_token_cache = self._load_msal_token_cache()
if self._use_msal_http_cache and not Identity._msal_http_cache:
Identity._msal_http_cache = self._load_msal_http_cache()
return {
"authority": self._msal_authority,
"token_cache": Identity._msal_token_cache,
"http_cache": Identity._msal_http_cache,
"instance_discovery": self._instance_discovery,
# CP1 means we can handle claims challenges (CAE)
"client_capabilities": None if "AZURE_IDENTITY_DISABLE_CP1" in os.environ else ["CP1"]
} | kwargs for creating ClientApplication (including its subclass ConfidentialClientApplication).
MSAL token cache and HTTP cache are lazily created. | _msal_app_kwargs | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def _msal_public_app_kwargs(self):
"""kwargs for creating PublicClientApplication."""
# enable_broker_on_windows can only be used on PublicClientApplication.
return {**self._msal_app_kwargs, "enable_broker_on_windows": self._enable_broker_on_windows} | kwargs for creating PublicClientApplication. | _msal_public_app_kwargs | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def _msal_app(self):
"""A PublicClientApplication instance for user login/logout.
The instance is lazily created.
"""
if not self._msal_app_instance:
self._msal_app_instance = PublicClientApplication(self.client_id, **self._msal_public_app_kwargs)
return self._msal_app_instance | A PublicClientApplication instance for user login/logout.
The instance is lazily created. | _msal_app | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def _service_principal_store(self):
"""A ServicePrincipalStore instance for service principal entries persistence.
The instance is lazily created.
"""
if not Identity._service_principal_store_instance:
store = load_secret_store(self._secret_file, self._encrypt)
Identity._service_principal_store_instance = ServicePrincipalStore(store)
return Identity._service_principal_store_instance | A ServicePrincipalStore instance for service principal entries persistence.
The instance is lazily created. | _service_principal_store | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def login_with_service_principal(self, client_id, credential, scopes):
"""
`credential` is a dict returned by ServicePrincipalAuth.build_credential
"""
sp_auth = ServicePrincipalAuth.build_from_credential(self.tenant_id, client_id, credential)
client_credential = sp_auth.get_msal_client_credential()
cred = ServicePrincipalCredential(client_id, client_credential, **self._msal_app_kwargs)
cred.acquire_token(scopes)
# Only persist the service principal after a successful login
entry = sp_auth.get_entry_to_persist()
self._service_principal_store.save_entry(entry) | `credential` is a dict returned by ServicePrincipalAuth.build_credential | login_with_service_principal | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def build_credential(cls, client_secret=None,
certificate=None, use_cert_sn_issuer=None,
client_assertion=None):
"""Build credential from user input. The credential looks like below, but only one key can exist.
{
'client_secret': 'my_secret',
'certificate': '/path/to/cert.pem',
'client_assertion': 'my_federated_token'
}
"""
entry = {}
if client_secret:
entry[_CLIENT_SECRET] = client_secret
elif certificate:
entry[_CERTIFICATE] = os.path.expanduser(certificate)
if use_cert_sn_issuer:
entry[_USE_CERT_SN_ISSUER] = use_cert_sn_issuer
elif client_assertion:
entry[_CLIENT_ASSERTION] = client_assertion
return entry | Build credential from user input. The credential looks like below, but only one key can exist.
{
'client_secret': 'my_secret',
'certificate': '/path/to/cert.pem',
'client_assertion': 'my_federated_token'
} | build_credential | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def get_entry_to_persist(self):
"""Get a service principal entry that can be persisted by ServicePrincipalStore."""
persisted_keys = [_CLIENT_ID, _TENANT, _CLIENT_SECRET, _CERTIFICATE, _USE_CERT_SN_ISSUER, _CLIENT_ASSERTION]
# Only persist certain attributes whose values are not None
return {k: v for k, v in self.__dict__.items() if k in persisted_keys and v} | Get a service principal entry that can be persisted by ServicePrincipalStore. | get_entry_to_persist | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def get_msal_client_credential(self):
"""Get a client_credential that can be consumed by msal.ConfidentialClientApplication."""
client_credential = None
# client_secret
# "your client secret"
if self.client_secret:
client_credential = self.client_secret
# certificate
# {
# "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
# "thumbprint": "A1B2C3D4E5F6...",
# "public_certificate": "...-----BEGIN CERTIFICATE-----...",
# }
if self.certificate:
client_credential = {
"private_key": self._certificate_string,
"thumbprint": self._thumbprint
}
if self._public_certificate:
client_credential['public_certificate'] = self._public_certificate
# client_assertion
# {
# "client_assertion": "...a JWT with claims aud, exp, iss, jti, nbf, and sub..."
# }
if self.client_assertion:
client_credential = {'client_assertion': self.client_assertion}
return client_credential | Get a client_credential that can be consumed by msal.ConfidentialClientApplication. | get_msal_client_credential | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def _get_authority_url(authority_endpoint, tenant):
"""Convert authority endpoint (active_directory) to MSAL authority:
- AAD: https://login.microsoftonline.com/your_tenant
- ADFS: https://adfs.redmond.azurestack.corp.microsoft.com/adfs
For ADFS, tenant is discarded.
"""
# Some Azure Stack (bellevue)'s metadata returns
# "loginEndpoint": "https://login.microsoftonline.com/"
# Normalize it by removing the trailing /, so that authority_url won't become
# "https://login.microsoftonline.com//tenant_id".
authority_endpoint = authority_endpoint.rstrip('/').lower()
is_adfs = authority_endpoint.endswith('adfs')
if is_adfs:
authority_url = authority_endpoint
else:
authority_url = '{}/{}'.format(authority_endpoint, tenant or "organizations")
return authority_url, is_adfs | Convert authority endpoint (active_directory) to MSAL authority:
- AAD: https://login.microsoftonline.com/your_tenant
- ADFS: https://adfs.redmond.azurestack.corp.microsoft.com/adfs
For ADFS, tenant is discarded. | _get_authority_url | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/identity.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/identity.py | MIT |
def __init__(self, client_id, username, **kwargs):
"""User credential wrapping msal.application.PublicClientApplication
:param client_id: Client ID of the CLI.
:param username: The username for user credential.
"""
self._msal_app = PublicClientApplication(client_id, **kwargs)
# Make sure username is specified, otherwise MSAL returns all accounts
assert username, "username must be specified, got {!r}".format(username)
accounts = self._msal_app.get_accounts(username)
# Usernames are usually unique. We are collecting corner cases to better understand its behavior.
if len(accounts) > 1:
raise CLIError(f"Found multiple accounts with the same username '{username}': {accounts}\n"
"Please report to us via Github: https://github.com/Azure/azure-cli/issues/20168")
if not accounts:
raise CLIError("User '{}' does not exist in MSAL token cache. Run `az login`.".format(username))
self._account = accounts[0] | User credential wrapping msal.application.PublicClientApplication
:param client_id: Client ID of the CLI.
:param username: The username for user credential. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/msal_credentials.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/msal_credentials.py | MIT |
def __init__(self, client_id, client_credential, **kwargs):
"""Service principal credential wrapping msal.application.ConfidentialClientApplication.
:param client_id: The service principal's client ID.
:param client_credential: client_credential that will be passed to MSAL.
"""
self._msal_app = ConfidentialClientApplication(client_id, client_credential=client_credential, **kwargs) | Service principal credential wrapping msal.application.ConfidentialClientApplication.
:param client_id: The service principal's client ID.
:param client_credential: client_credential that will be passed to MSAL. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/msal_credentials.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/msal_credentials.py | MIT |
def build_persistence(location, encrypt):
"""Build a suitable persistence instance based your current OS"""
location += file_extensions[encrypt]
logger.debug("build_persistence: location=%r, encrypt=%r", location, encrypt)
if encrypt:
if sys.platform.startswith('win'):
return FilePersistenceWithDataProtection(location)
if sys.platform.startswith('darwin'):
return KeychainPersistence(location, "my_service_name", "my_account_name")
if sys.platform.startswith('linux'):
return LibsecretPersistence(
location,
schema_name="my_schema_name",
attributes={"my_attr1": "foo", "my_attr2": "bar"}
)
else:
return FilePersistence(location) | Build a suitable persistence instance based your current OS | build_persistence | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/persistence.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/persistence.py | MIT |
def aad_error_handler(error, **kwargs):
""" Handle the error from AAD server returned by ADAL or MSAL. """
# https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
# Search for an error code at https://login.microsoftonline.com/error
# To trigger this function for testing, simply provide an invalid scope:
# az account get-access-token --scope https://my-invalid-scope
from azure.cli.core.util import in_cloud_console
if in_cloud_console():
import socket
logger.warning("A Cloud Shell credential problem occurred. When you report the issue with the error "
"below, please mention the hostname '%s'", socket.gethostname())
error_description = error.get('error_description')
error_codes = error.get('error_codes')
# Build recommendation message
if error_codes and 7000215 in error_codes:
recommendation = PASSWORD_CERTIFICATE_WARNING
else:
login_command = _generate_login_command(**kwargs)
recommendation = (
# Cloud Shell uses IMDS-like interface for implicit login. If getting token/cert failed,
# we let the user explicitly log in to AAD with MSAL.
"Please explicitly log in with:\n{}" if error.get('error') == 'broker_error'
else "Interactive authentication is needed. Please run:\n{}").format(login_command)
from azure.cli.core.azclierror import AuthenticationError
raise AuthenticationError(error_description, msal_error=error, recommendation=recommendation) | Handle the error from AAD server returned by ADAL or MSAL. | aad_error_handler | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/util.py | MIT |
def resource_to_scopes(resource):
"""Convert the ADAL resource ID to MSAL scopes by appending the /.default suffix and return a list.
For example:
'https://management.core.windows.net/' -> ['https://management.core.windows.net//.default']
'https://managedhsm.azure.com' -> ['https://managedhsm.azure.com/.default']
:param resource: The ADAL resource ID
:return: A list of scopes
"""
# https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#trailing-slash-and-default
# We should not trim the trailing slash, like in https://management.azure.com/
# In other word, the trailing slash should be preserved and scope should be https://management.azure.com//.default
scope = resource + '/.default'
return [scope] | Convert the ADAL resource ID to MSAL scopes by appending the /.default suffix and return a list.
For example:
'https://management.core.windows.net/' -> ['https://management.core.windows.net//.default']
'https://managedhsm.azure.com' -> ['https://managedhsm.azure.com/.default']
:param resource: The ADAL resource ID
:return: A list of scopes | resource_to_scopes | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/util.py | MIT |
def scopes_to_resource(scopes):
"""Convert MSAL scopes to ADAL resource by stripping the /.default suffix and return a str.
For example:
['https://management.core.windows.net//.default'] -> 'https://management.core.windows.net/'
['https://managedhsm.azure.com/.default'] -> 'https://managedhsm.azure.com'
:param scopes: The MSAL scopes. It can be a list or tuple of string
:return: The ADAL resource
:rtype: str
"""
if not scopes:
return None
scope = scopes[0]
suffixes = ['/.default', '/user_impersonation']
for s in suffixes:
if scope.endswith(s):
return scope[:-len(s)]
return scope | Convert MSAL scopes to ADAL resource by stripping the /.default suffix and return a str.
For example:
['https://management.core.windows.net//.default'] -> 'https://management.core.windows.net/'
['https://managedhsm.azure.com/.default'] -> 'https://managedhsm.azure.com'
:param scopes: The MSAL scopes. It can be a list or tuple of string
:return: The ADAL resource
:rtype: str | scopes_to_resource | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/util.py | MIT |
def check_result(result, **kwargs):
"""Parse the result returned by MSAL:
1. Check if the MSAL result contains a valid access token.
2. If there is error, handle the error and show re-login message.
3. For user login, return the username and tenant_id in a dict.
"""
from azure.cli.core.azclierror import AuthenticationError
if not result:
raise AuthenticationError("Can't find token from MSAL cache.",
recommendation="To re-authenticate, please run:\naz login")
# msal_telemetry should be sent no matter if the MSAL response is a success or an error
if 'msal_telemetry' in result:
from azure.cli.core.telemetry import set_msal_telemetry
set_msal_telemetry(result['msal_telemetry'])
if 'error' in result:
aad_error_handler(result, **kwargs)
# For user authentication
if 'id_token_claims' in result:
id_token = result['id_token_claims']
return {
# AAD returns "preferred_username", ADFS returns "upn"
'username': id_token.get("preferred_username") or id_token["upn"],
'tenant_id': id_token['tid']
}
return None | Parse the result returned by MSAL:
1. Check if the MSAL result contains a valid access token.
2. If there is error, handle the error and show re-login message.
3. For user login, return the username and tenant_id in a dict. | check_result | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/util.py | MIT |
def read_response_templates():
"""Read from success.html and error.html to strings and pass them to MSAL. """
success_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'landing_pages', 'success.html')
with open(success_file) as f:
success_template = f.read()
error_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'landing_pages', 'error.html')
with open(error_file) as f:
error_template = f.read()
return success_template, error_template | Read from success.html and error.html to strings and pass them to MSAL. | read_response_templates | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/util.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/util.py | MIT |
def get_auxiliary_tokens(self, *scopes, **kwargs): # pylint:disable=no-self-use,unused-argument
"""This method is added to align with CredentialAdaptor.get_auxiliary_tokens
Since managed identity belongs to a single tenant and currently doesn't support cross-tenant authentication,
simply return None."""
return None | This method is added to align with CredentialAdaptor.get_auxiliary_tokens
Since managed identity belongs to a single tenant and currently doesn't support cross-tenant authentication,
simply return None. | get_auxiliary_tokens | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/adal_authentication.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/adal_authentication.py | MIT |
def _normalize_expires_on(expires_on):
"""
The expires_on field returned by managed identity differs on Azure VM (epoch str) and App Service (datetime str).
Normalize to epoch int.
"""
try:
# Treat as epoch string "1605238724"
expires_on_epoch_int = int(expires_on)
except ValueError:
import datetime
# Python 3.6 doesn't recognize timezone as +00:00.
# These lines can be dropped after Python 3.6 is dropped.
# https://stackoverflow.com/questions/30999230/how-to-parse-timezone-with-colon
if expires_on[-3] == ":":
expires_on = expires_on[:-3] + expires_on[-2:]
# Treat as datetime string "11/05/2021 15:18:31 +00:00"
expires_on_epoch_int = int(datetime.datetime.strptime(expires_on, '%m/%d/%Y %H:%M:%S %z').timestamp())
logger.debug("Normalize expires_on: %r -> %r", expires_on, expires_on_epoch_int)
return expires_on_epoch_int | The expires_on field returned by managed identity differs on Azure VM (epoch str) and App Service (datetime str).
Normalize to epoch int. | _normalize_expires_on | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/adal_authentication.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/adal_authentication.py | MIT |
def _load(self):
"""Load cache with retry. If it still fails at last, raise the original exception as-is."""
try:
with open(self.filename, 'rb') as f:
return pickle.load(f)
except FileNotFoundError:
# The cache file has not been created. This is expected. No need to retry.
logger.debug("%s not found. Using a fresh one.", self.filename)
return {} | Load cache with retry. If it still fails at last, raise the original exception as-is. | _load | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/auth/binary_cache.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/auth/binary_cache.py | MIT |
def __init__(self, import_prefix, client_name):
"""Constructor.
:param import_prefix: Path to the (unversioned) module.
:type import_prefix: str.
:param client_name: Name the client for this resource type.
:type client_name: str.
"""
self.import_prefix = import_prefix
self.client_name = client_name | Constructor.
:param import_prefix: Path to the (unversioned) module.
:type import_prefix: str.
:param client_name: Name the client for this resource type.
:type client_name: str. | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def __init__(self, default_api_version, profile=None):
"""Constructor.
:param str default_api_version: Default API version if not overridden by a profile. Nullable.
:param profile: A dict operation group name to API version.
:type profile: dict[str, str]
"""
self.profile = profile if profile is not None else {}
self.profile[None] = default_api_version | Constructor.
:param str default_api_version: Default API version if not overridden by a profile. Nullable.
:param profile: A dict operation group name to API version.
:type profile: dict[str, str] | __init__ | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def _get_api_version_tuple(resource_type, sdk_profile, post_process=lambda x: x):
"""Return a _ApiVersion instance where key are operation group and value are api version."""
return _ApiVersions(client_type=get_client_class(resource_type),
sdk_profile=sdk_profile,
post_process=post_process) | Return a _ApiVersion instance where key are operation group and value are api version. | _get_api_version_tuple | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def get_api_version(api_profile, resource_type, as_sdk_profile=False):
"""Get the API version of a resource type given an API profile.
:param api_profile: The name of the API profile.
:type api_profile: str.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:returns: str -- the API version.
:raises: APIVersionException
"""
try:
api_version = AZURE_API_PROFILES[api_profile][resource_type]
if as_sdk_profile:
return api_version # Could be SDKProfile or string
if isinstance(api_version, SDKProfile):
api_version = _get_api_version_tuple(resource_type, api_version)
return api_version
except KeyError:
raise APIVersionException(resource_type, api_profile) | Get the API version of a resource type given an API profile.
:param api_profile: The name of the API profile.
:type api_profile: str.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:returns: str -- the API version.
:raises: APIVersionException | get_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def _parse_api_version(api_version):
"""Will try to parse it as a date, and if not working
as semver, and if still not working raise.
"""
try:
return _DateAPIFormat(api_version)
except ValueError:
return _SemVerAPIFormat(api_version) | Will try to parse it as a date, and if not working
as semver, and if still not working raise. | _parse_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def _cross_api_format_less_than(api_version, other):
"""LT strategy that supports if types are different.
For now, let's assume that any Semver is higher than any DateAPI
This fits KeyVault, if later we have a counter-example we'll update
"""
api_version = _parse_api_version(api_version)
other = _parse_api_version(other)
if type(api_version) is type(other):
return api_version < other
return isinstance(api_version, _DateAPIFormat) and isinstance(other, _SemVerAPIFormat) | LT strategy that supports if types are different.
For now, let's assume that any Semver is higher than any DateAPI
This fits KeyVault, if later we have a counter-example we'll update | _cross_api_format_less_than | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def _validate_api_version(api_version_str, min_api=None, max_api=None):
"""Validate if api_version is inside the interval min_api/max_api.
"""
if min_api and _cross_api_format_less_than(api_version_str, min_api):
return False
if max_api and _cross_api_format_less_than(max_api, api_version_str):
return False
return True | Validate if api_version is inside the interval min_api/max_api. | _validate_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def supported_api_version(api_profile, resource_type, min_api=None, max_api=None, operation_group=None):
"""
Returns True if current API version for the resource type satisfies min/max range.
To compare profile versions, set resource type to None.
Can return a tuple<operation_group, bool> if the resource_type supports SDKProfile.
note: Currently supports YYYY-MM-DD, YYYY-MM-DD-preview, YYYY-MM-DD-profile
or YYYY-MM-DD-profile-preview formatted strings.
"""
if not isinstance(resource_type, (ResourceType, CustomResourceType)) and resource_type != PROFILE_TYPE:
raise ValueError("'resource_type' is required.")
if min_api is None and max_api is None:
raise ValueError('At least a min or max version must be specified')
api_version_obj = get_api_version(api_profile, resource_type, as_sdk_profile=True) \
if isinstance(resource_type, (ResourceType, CustomResourceType)) else api_profile
if isinstance(api_version_obj, SDKProfile):
api_version_obj = api_version_obj.profile.get(operation_group or '', api_version_obj.default_api_version)
return _validate_api_version(api_version_obj, min_api, max_api) | Returns True if current API version for the resource type satisfies min/max range.
To compare profile versions, set resource type to None.
Can return a tuple<operation_group, bool> if the resource_type supports SDKProfile.
note: Currently supports YYYY-MM-DD, YYYY-MM-DD-preview, YYYY-MM-DD-profile
or YYYY-MM-DD-profile-preview formatted strings. | supported_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def get_versioned_sdk_path(api_profile, resource_type, operation_group=None):
""" Patch the unversioned sdk path to include the appropriate API version for the
resource type in question.
e.g. Converts azure.mgmt.storage.operations.storage_accounts_operations to
azure.mgmt.storage.v2016_12_01.operations.storage_accounts_operations
azure.keyvault.v7_0.models.KeyVault
"""
api_version = get_api_version(api_profile, resource_type)
if api_version is None:
return resource_type.import_prefix
if isinstance(api_version, _ApiVersions):
if operation_group is None:
raise ValueError("operation_group is required for resource type '{}'".format(resource_type))
api_version = getattr(api_version, operation_group)
return '{}.v{}'.format(resource_type.import_prefix, api_version.replace('-', '_').replace('.', '_')) | Patch the unversioned sdk path to include the appropriate API version for the
resource type in question.
e.g. Converts azure.mgmt.storage.operations.storage_accounts_operations to
azure.mgmt.storage.v2016_12_01.operations.storage_accounts_operations
azure.keyvault.v7_0.models.KeyVault | get_versioned_sdk_path | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/_shared.py | MIT |
def get_api_version(cli_ctx, resource_type, as_sdk_profile=False):
""" Get the current API version for a given resource_type.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param bool as_sdk_profile: Return SDKProfile instance.
:returns: The API version
Can return a tuple<operation_group, str> if the resource_type supports SDKProfile.
:rtype: str or tuple[str]
"""
from azure.cli.core.profiles._shared import get_api_version as _sdk_get_api_version
return _sdk_get_api_version(cli_ctx.cloud.profile, resource_type, as_sdk_profile) | Get the current API version for a given resource_type.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param bool as_sdk_profile: Return SDKProfile instance.
:returns: The API version
Can return a tuple<operation_group, str> if the resource_type supports SDKProfile.
:rtype: str or tuple[str] | get_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/__init__.py | MIT |
def supported_api_version(cli_ctx, resource_type, min_api=None, max_api=None, operation_group=None):
""" Method to check if the current API version for a given resource_type is supported.
If resource_type is set to None, the current profile version will be used as the basis of
the comparison.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param min_api: The minimum API that is supported (inclusive). Omit for no minimum constraint.
"type min_api: str
:param max_api: The maximum API that is supported (inclusive). Omit for no maximum constraint.
:type max_api: str
:returns: True if the current API version of resource_type satisfies the min/max constraints. False otherwise.
Can return a tuple<operation_group, bool> if the resource_type supports SDKProfile.
:rtype: bool or tuple[bool]
"""
from azure.cli.core.profiles._shared import supported_api_version as _sdk_supported_api_version
return _sdk_supported_api_version(cli_ctx.cloud.profile,
resource_type=resource_type,
min_api=min_api,
max_api=max_api,
operation_group=operation_group) | Method to check if the current API version for a given resource_type is supported.
If resource_type is set to None, the current profile version will be used as the basis of
the comparison.
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param min_api: The minimum API that is supported (inclusive). Omit for no minimum constraint.
"type min_api: str
:param max_api: The maximum API that is supported (inclusive). Omit for no maximum constraint.
:type max_api: str
:returns: True if the current API version of resource_type satisfies the min/max constraints. False otherwise.
Can return a tuple<operation_group, bool> if the resource_type supports SDKProfile.
:rtype: bool or tuple[bool] | supported_api_version | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/__init__.py | MIT |
def get_sdk(cli_ctx, resource_type, *attr_args, **kwargs):
""" Get any SDK object that's versioned using the current API version for resource_type.
Supported keyword arguments:
checked - A boolean specifying if this method should suppress/check import exceptions
or not. By default, None is returned.
mod - A string specifying the submodule that all attr_args should be prefixed with.
operation_group - A string specifying the operation group name we want models.
Example usage:
Get a single SDK model.
TableService = get_sdk(resource_type, 'table#TableService')
File, Directory = get_sdk(resource_type,
'file.models#File',
'file.models#Directory')
Same as above but get multiple models where File and Directory are both part of
'file.models' and we don't want to specify each full path.
File, Directory = get_sdk(resource_type,
'File',
'Directory',
mod='file.models')
VirtualMachine = get_sdk(resource_type,
'VirtualMachine',
mod='models',
operation_group='virtual_machines')
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param attr_args: Positional arguments for paths to objects to get.
:type attr_args: str
:param kwargs: Keyword arguments.
:type kwargs: str
:returns: object -- e.g. an SDK module, model, enum, attribute. The number of objects returned
depends on len(attr_args).
"""
from azure.cli.core.profiles._shared import get_versioned_sdk as _sdk_get_versioned_sdk
return _sdk_get_versioned_sdk(cli_ctx.cloud.profile, resource_type, *attr_args, **kwargs) | Get any SDK object that's versioned using the current API version for resource_type.
Supported keyword arguments:
checked - A boolean specifying if this method should suppress/check import exceptions
or not. By default, None is returned.
mod - A string specifying the submodule that all attr_args should be prefixed with.
operation_group - A string specifying the operation group name we want models.
Example usage:
Get a single SDK model.
TableService = get_sdk(resource_type, 'table#TableService')
File, Directory = get_sdk(resource_type,
'file.models#File',
'file.models#Directory')
Same as above but get multiple models where File and Directory are both part of
'file.models' and we don't want to specify each full path.
File, Directory = get_sdk(resource_type,
'File',
'Directory',
mod='file.models')
VirtualMachine = get_sdk(resource_type,
'VirtualMachine',
mod='models',
operation_group='virtual_machines')
:param resource_type: The resource type.
:type resource_type: ResourceType.
:param attr_args: Positional arguments for paths to objects to get.
:type attr_args: str
:param kwargs: Keyword arguments.
:type kwargs: str
:returns: object -- e.g. an SDK module, model, enum, attribute. The number of objects returned
depends on len(attr_args). | get_sdk | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/profiles/__init__.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/profiles/__init__.py | MIT |
def get_index_url(cli_ctx=None):
"""Use extension index url in the order of:
1. Environment variable: AZURE_EXTENSION_INDEX_URL
2. Config setting: extension.index_url
3. Index file in azmirror storage account cloud endpoint
4. DEFAULT_INDEX_URL
"""
import posixpath
if cli_ctx:
url = cli_ctx.config.get('extension', 'index_url', None)
if url:
return url
azmirror_endpoint = cli_ctx.cloud.endpoints.azmirror_storage_account_resource_id if cli_ctx and \
cli_ctx.cloud.endpoints.has_endpoint_set('azmirror_storage_account_resource_id') else None
return posixpath.join(azmirror_endpoint, 'extensions', 'index.json') if azmirror_endpoint else DEFAULT_INDEX_URL | Use extension index url in the order of:
1. Environment variable: AZURE_EXTENSION_INDEX_URL
2. Config setting: extension.index_url
3. Index file in azmirror storage account cloud endpoint
4. DEFAULT_INDEX_URL | get_index_url | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/_index.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/_index.py | MIT |
def resolve_from_index(extension_name, cur_version=None, index_url=None, target_version=None, cli_ctx=None,
allow_preview=None):
"""Gets the download Url and digest for the matching extension
Args:
extension_name (str): Name of
cur_version (str, optional): Threshold version to filter out extensions. Defaults to None.
index_url (str, optional): Defaults to None.
target_version (str, optional): Version of extension to install. Defaults to latest version.
cli_ctx (, optional): CLI Context. Defaults to None.
allow_preview(bool, optional): Flag to allow installing preview extensions. Default to None.
Raises:
NoExtensionCandidatesError when an extension:
* Doesn't exist
* Has no versions compatible with the current platform
* Has no versions more recent than currently installed version
* Has no versions that are compatible with the version of azure cli
Returns:
tuple: (Download Url, SHA digest)
"""
candidates = get_index_extensions(index_url=index_url, cli_ctx=cli_ctx).get(extension_name, [])
if not candidates:
raise NoExtensionCandidatesError(f"No extension found with name '{extension_name}'")
if allow_preview is None:
# default value of allow-preview changed from true to false
# and the following part deals with two influenced scenariors if user does not specify allow-preview
# 1. if extension module does not have any stable version, set allow-preview=True and display warning message to
# unblock those extension module user
# 2. if extension module has a later preview version than stable one, dispaly a warning message to user
# indicating how to try the newer preview one, but allow-preview is still set to be False by default
allow_preview = False
stable_candidates = list(filter(is_stable_from_metadata, candidates))
preview_candidates = list(filter(is_preview_from_metadata, candidates))
if len(stable_candidates) == 0:
logger.warning("No stable version of '%s' to install. Preview versions allowed.", extension_name)
allow_preview = True
elif len(preview_candidates) != 0:
max_preview_item = max(preview_candidates, key=lambda x: parse(x['metadata']['version']))
max_stable_item = max(stable_candidates, key=lambda x: parse(x['metadata']['version']))
if parse(max_preview_item['metadata']['version']) > parse(max_stable_item['metadata']['version']):
logger.warning("Extension '%s' has a later preview version to install, add `--allow-preview True` "
"to try preview version.", extension_name)
else:
logger.info("No preview versions need to be tried.")
# Helper to curry predicate functions
def list_filter(f):
return lambda cs: list(filter(f, cs))
candidate_filters = [
_ExtensionFilter(
filter=list_filter(_is_not_platform_specific),
on_empty_results_message=f"No suitable extensions found for '{extension_name}'."
)
]
if not allow_preview:
candidate_filters += [
_ExtensionFilter(
filter=list_filter(is_stable_from_metadata),
on_empty_results_message=f"No suitable stable version of '{extension_name}' to install. "
f"Add `--allow-preview True` to try preview versions"
)]
if target_version:
candidate_filters += [
_ExtensionFilter(
filter=list_filter(lambda c: c['metadata']['version'] == target_version),
on_empty_results_message=f"Version '{target_version}' not found for extension '{extension_name}'"
)
]
else:
candidate_filters += [
_ExtensionFilter(
filter=list_filter(_is_greater_than_cur_version(cur_version)),
on_empty_results_message=f"Latest version of '{extension_name}' is already installed."
)
]
candidate_filters += [
_ExtensionFilter(
filter=list_filter(_is_compatible_with_cli_version),
on_empty_results_message=_get_version_compatibility_feedback
),
_ExtensionFilter(
filter=_get_latest_version,
on_empty_results_message=f"No suitable extensions found for '{extension_name}'."
)
]
for candidate_filter, on_empty_results_message in candidate_filters:
logger.debug("Candidates %s", [c['filename'] for c in candidates])
filtered_candidates = candidate_filter(candidates)
if not filtered_candidates and (on_empty_results_message is not None):
if not isinstance(on_empty_results_message, str):
on_empty_results_message = on_empty_results_message(candidates)
raise NoExtensionCandidatesError(on_empty_results_message)
candidates = filtered_candidates
chosen = candidates[0]
logger.debug("Chosen %s", chosen)
download_url, digest = chosen.get('downloadUrl'), chosen.get('sha256Digest')
if not download_url:
raise NoExtensionCandidatesError("No download url found.")
azmirror_endpoint = cli_ctx.cloud.endpoints.azmirror_storage_account_resource_id if cli_ctx and \
cli_ctx.cloud.endpoints.has_endpoint_set('azmirror_storage_account_resource_id') else None
config_index_url = cli_ctx.config.get('extension', 'index_url', None) if cli_ctx else None
if azmirror_endpoint and not config_index_url:
# when extension index and wheels are mirrored in airgapped clouds from public cloud
# the content of the index.json is not updated, so we need to modify the wheel url got
# from the index.json here.
import posixpath
whl_name = download_url.split('/')[-1]
download_url = posixpath.join(azmirror_endpoint, 'extensions', whl_name)
return download_url, digest | Gets the download Url and digest for the matching extension
Args:
extension_name (str): Name of
cur_version (str, optional): Threshold version to filter out extensions. Defaults to None.
index_url (str, optional): Defaults to None.
target_version (str, optional): Version of extension to install. Defaults to latest version.
cli_ctx (, optional): CLI Context. Defaults to None.
allow_preview(bool, optional): Flag to allow installing preview extensions. Default to None.
Raises:
NoExtensionCandidatesError when an extension:
* Doesn't exist
* Has no versions compatible with the current platform
* Has no versions more recent than currently installed version
* Has no versions that are compatible with the version of azure cli
Returns:
tuple: (Download Url, SHA digest) | resolve_from_index | python | Azure/azure-cli | src/azure-cli-core/azure/cli/core/extension/_resolve.py | https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/extension/_resolve.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.