예제 #1
0
    def _set_recommended_command_to_telemetry(self, recommend_command):
        """Set the recommended command to Telemetry for analysis. """

        if recommend_command in self.aladdin_recommendations:
            telemetry.set_debug_info('AladdinRecommendCommand',
                                     recommend_command)
        elif recommend_command:
            telemetry.set_debug_info('ExampleRecommendCommand',
                                     recommend_command)
예제 #2
0
def config_unset(cmd, key=None, local=False):
    for k in key:
        # section.name
        parts = k.split('.', 1)

        if len(parts) == 1:
            raise CLIError("usage error: [section].[name]")

        section = parts[0]
        name = parts[1]

        with ScopedConfig(cmd.cli_ctx.config, local):
            cmd.cli_ctx.config.remove_option(section, name)
    telemetry.set_debug_info('ConfigUnset', ' '.join(key))
예제 #3
0
    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))
예제 #4
0
def config_set(cmd, key_value=None, local=False):
    if key_value:
        with ScopedConfig(cmd.cli_ctx.config, local):
            telemetry_contents = []
            for kv in key_value:
                # core.no_color=true
                parts = kv.split('=', 1)
                if len(parts) == 1:
                    raise CLIError('usage error: [section].[name]=[value] ...')
                key = parts[0]
                value = parts[1]

                # core.no_color
                parts = key.split('.', 1)
                if len(parts) == 1:
                    raise CLIError('usage error: [section].[name]=[value] ...')
                section = parts[0]
                name = parts[1]

                cmd.cli_ctx.config.set_value(section, name,
                                             _normalize_config_value(value))
                telemetry_contents.append((key, section, value))
            telemetry.set_debug_info('ConfigSet', telemetry_contents)
예제 #5
0
    def _set_aladdin_recommendations(self):
        """Set recommendations from aladdin service.
        Call the aladdin service API, parse the response and set the 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
        # 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': self._get_error_type()
        }

        if telemetry.is_telemetry_enabled():
            if correlation_id:
                context['correlationId'] = correlation_id
            if subscription_id:
                context['subscriptionId'] = subscription_id

        parameters = [
            item for item in self.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)
        except RequestException as ex:
            logger.debug('Recommendation requests.get() exception: %s', ex)
            telemetry.set_debug_info('AladdinRecommendationService',
                                     ex.__class__.__name__)

        recommendations = []
        if response and response.status_code == HTTPStatus.OK:
            for result in response.json():
                # parse the reponse and format the recommendation
                command, parameters, placeholders = result['command'],\
                    result['parameters'].split(','),\
                    result['placeholders'].split('♠')
                recommendation = 'az {} '.format(command)
                for parameter, placeholder in zip(parameters, placeholders):
                    recommendation += '{} {} '.format(parameter, placeholder)
                recommendations.append(recommendation.strip())

        self.aladdin_recommendations.extend(recommendations)