示例#1
0
def validate_onedeploy_params(namespace):
    if namespace.src_path and namespace.src_url:
        raise MutuallyExclusiveArgumentError(
            'Only one of --src-path and --src-url can be specified')

    if not namespace.src_path and not namespace.src_url:
        raise RequiredArgumentMissingError(
            'Either of --src-path or --src-url must be specified')

    if namespace.src_url and not namespace.artifact_type:
        raise RequiredArgumentMissingError(
            'Deployment type is mandatory when deploying from URLs. Use --type'
        )
示例#2
0
def _infer_acr_credentials(cmd, registry_server, disable_warnings=False):
    # If registry is Azure Container Registry, we can try inferring credentials
    if '.azurecr.io' not in registry_server:
        raise RequiredArgumentMissingError('Registry username and password are required if not using Azure Container Registry.')
    not disable_warnings and logger.warning('No credential was provided to access Azure Container Registry. Trying to look up credentials...')
    parsed = urlparse(registry_server)
    registry_name = (parsed.netloc if parsed.scheme else parsed.path).split('.')[0]

    try:
        registry_user, registry_pass, registry_rg = _get_acr_cred(cmd.cli_ctx, registry_name)  # pylint: disable=unused-variable
        return (registry_user, registry_pass)
    except Exception as ex:
        raise RequiredArgumentMissingError('Failed to retrieve credentials for container registry {}. Please provide the registry username and password'.format(registry_name)) from ex
def validate_and_get_protected_settings(ssh_private_key, ssh_private_key_file,
                                        https_user, https_key):
    protected_settings = {}
    ssh_private_key_data = get_data_from_key_or_file(ssh_private_key,
                                                     ssh_private_key_file)

    # Add gitops private key data to protected settings if exists
    # Dry-run all key types to determine if the private key is in a valid format
    invalid_rsa_key, invalid_ecc_key, invalid_dsa_key, invalid_ed25519_key = (
        False, False, False, False)
    if ssh_private_key_data != '':
        try:
            RSA.import_key(from_base64(ssh_private_key_data))
        except ValueError:
            invalid_rsa_key = True
        try:
            ECC.import_key(from_base64(ssh_private_key_data))
        except ValueError:
            invalid_ecc_key = True
        try:
            DSA.import_key(from_base64(ssh_private_key_data))
        except ValueError:
            invalid_dsa_key = True
        try:
            key_obj = io.StringIO(
                from_base64(ssh_private_key_data).decode('utf-8'))
            Ed25519Key(file_obj=key_obj)
        except SSHException:
            invalid_ed25519_key = True

        if invalid_rsa_key and invalid_ecc_key and invalid_dsa_key and invalid_ed25519_key:
            raise InvalidArgumentValueError(
                'Error! ssh private key provided in invalid format',
                'Verify the key provided is a valid PEM-formatted key of type RSA, ECC, DSA, or Ed25519'
            )
        protected_settings["sshPrivateKey"] = ssh_private_key_data

    # Check if both httpsUser and httpsKey exist, then add to protected settings
    if https_user != '' and https_key != '':
        protected_settings['httpsUser'] = to_base64(https_user)
        protected_settings['httpsKey'] = to_base64(https_key)
    elif https_user != '':
        raise RequiredArgumentMissingError(
            'Error! --https-user used without --https-key',
            'Try providing both --https-user and --https-key together')
    elif https_key != '':
        raise RequiredArgumentMissingError(
            'Error! --http-key used without --http-user',
            'Try providing both --https-user and --https-key together')

    return protected_settings
def _autoadd_providers(cmd, providers_in_region, providers_selected,
                       workspace_location, auto_accept):
    already_accepted_terms = False
    for provider in providers_in_region:
        for sku in provider.properties.skus:
            if sku.auto_add:
                # Don't duplicate a provider/sku if it was also specified in the command's -r parameter
                provider_already_added = False
                for already_selected_provider in providers_selected:
                    if already_selected_provider[
                            'provider_id'] == provider.id and already_selected_provider[
                                'sku'] == sku.id:
                        provider_already_added = True
                        break
                if not provider_already_added:
                    (publisher,
                     offer) = _get_publisher_and_offer_from_provider_id(
                         providers_in_region, provider.id)
                    if (offer is None or publisher is None):
                        raise RequiredArgumentMissingError(
                            f"Error adding 'autoAdd' provider: Publisher or Offer not found for '{provider.id}'"
                        )

                    provider_selected = {
                        'provider_id': provider.id,
                        'sku': sku.id,
                        'offer_id': offer,
                        'publisher_id': publisher
                    }
                    if cmd is not None and not already_accepted_terms and _provider_terms_need_acceptance(
                            cmd, provider_selected):
                        if not auto_accept:
                            print(C4A_TERMS_ACCEPTANCE_MESSAGE, end='')
                            if input().lower() != 'y':
                                sys.exit(
                                    'Terms not accepted. No workspace created.'
                                )
                        accept_terms(cmd, provider.id, sku.id,
                                     workspace_location)
                        already_accepted_terms = True
                    providers_selected.append(provider_selected)

    # If there weren't any autoAdd providers and none were specified with the -r parameter, we have a problem...
    if providers_selected == []:
        raise RequiredArgumentMissingError(
            "A list of Azure Quantum providers and SKUs is required.",
            "Supply the missing -r parameter. For example:\n"
            "\t-r \"Microsoft/Basic, Microsoft.FleetManagement/Basic\"\n"
            "To display a list of Provider IDs and their SKUs, use the following command:\n"
            "\taz quantum offerings list -l MyLocation -o table")
示例#5
0
def interactive_input(arg, hint):
    '''Get interactive inputs from users
    '''
    value = None
    cmd_value = None
    if arg == 'secret_auth_info':
        name = prompt('User name of database (--secret name=): ')
        secret = prompt_pass('Password of database (--secret secret=): ')
        value = {
            'name': name,
            'secret_info': {
                'secret_type': 'rawValue',
                'value': secret
            },
            'auth_type': 'secret'
        }
        cmd_value = 'name={} secret={}'.format(name, '*' * len(secret))
    elif arg == 'service_principal_auth_info_secret':
        client_id = prompt('ServicePrincipal client-id (--service-principal client_id=): ')
        object_id = prompt('Enterprise Application object-id (--service-principal object-id=): ')
        secret = prompt_pass('ServicePrincipal secret (--service-principal secret=): ')
        value = {
            'client_id': client_id,
            'object-id': object_id,
            'secret': secret,
            'auth_type': 'servicePrincipalSecret'
        }
        cmd_value = 'client-id={} principal-id={} secret={}'.format(client_id, object_id, '*' * len(secret))
    elif arg == 'user_identity_auth_info':
        client_id = prompt('UserAssignedIdentity client-id (--user-identity client_id=): ')
        subscription_id = prompt('UserAssignedIdentity subscription-id (--user-identity subs_id=): ')
        value = {
            'client_id': client_id,
            'subscription_id': subscription_id,
            'auth_type': 'userAssignedIdentity'
        }
        cmd_value = 'client-id={} subscription-id={}'.format(client_id, subscription_id)
    else:
        value = prompt('{}: '.format(hint))
        cmd_value = value

    # check blank value
    if isinstance(value, dict):
        for sub_val in value.values():
            if not sub_val:
                raise RequiredArgumentMissingError('{} should not be blank'.format(hint))
    elif not value:
        raise RequiredArgumentMissingError('{} should not be blank'.format(hint))

    return value, cmd_value
示例#6
0
def sig_share_update(cmd,
                     client,
                     resource_group_name,
                     gallery_name,
                     subscription_ids=None,
                     tenant_ids=None,
                     op_type=None):
    from .vendored_sdks.azure_mgmt_compute.models._models_py3 import SharingProfileGroup, SharingUpdate, SharingProfileGroupTypes
    if op_type != 'EnableCommunity':
        if subscription_ids is None and tenant_ids is None:
            raise RequiredArgumentMissingError(
                'At least one of subscription ids or tenant ids must be provided'
            )
    groups = []
    if subscription_ids:
        groups.append(
            SharingProfileGroup(type=SharingProfileGroupTypes.SUBSCRIPTIONS,
                                ids=subscription_ids))
    if tenant_ids:
        groups.append(
            SharingProfileGroup(type=SharingProfileGroupTypes.AAD_TENANTS,
                                ids=tenant_ids))
    sharing_update = SharingUpdate(operation_type=op_type, groups=groups)
    return client.begin_update(resource_group_name=resource_group_name,
                               gallery_name=gallery_name,
                               sharing_update=sharing_update)
示例#7
0
def validate_blob_arguments(namespace):
    from azure.cli.core.azclierror import RequiredArgumentMissingError
    if not namespace.blob_url and not all(
        [namespace.blob_name, namespace.container_name]):
        raise RequiredArgumentMissingError(
            "Please specify --blob-url or combination of blob name, container name and storage account arguments."
        )
示例#8
0
    def error(self, message):
        # Get a recommended command from the CommandRecommender
        command_arguments = self._get_failure_recovery_arguments()
        cli_ctx = self.cli_ctx or (self.cli_help.cli_ctx if self.cli_help else None)
        recommender = CommandRecommender(*command_arguments, message, cli_ctx)
        recommender.set_help_examples(self.get_examples(self.prog))
        recommendation = recommender.recommend_a_command()

        az_error = ArgumentUsageError(message)
        if 'unrecognized arguments' in message:
            az_error = UnrecognizedArgumentError(message)
        elif 'arguments are required' in message:
            az_error = RequiredArgumentMissingError(message)
        elif 'invalid' in message:
            az_error = InvalidArgumentValueError(message)

        if '--query' in message:
            from azure.cli.core.util import QUERY_REFERENCE
            az_error.set_recommendation(QUERY_REFERENCE)
        elif recommendation:
            az_error.set_recommendation("Try this: '{}'".format(recommendation))
            az_error.set_recommendation(OVERVIEW_REFERENCE.format(command=self.prog))
        az_error.print_error()
        az_error.send_telemetry()
        self.exit(2)
def database_create_func(client,
                         resource_group_name=None,
                         server_name=None,
                         database_name=None,
                         charset=None,
                         collation=None):

    if charset is None and collation is None:
        charset = 'utf8'
        collation = 'utf8_general_ci'
        logger.warning(
            "Creating database with utf8 charset and utf8_general_ci collation"
        )
    elif (not charset and collation) or (charset and not collation):
        raise RequiredArgumentMissingError(
            "charset and collation have to be input together.")

    parameters = {
        'name': database_name,
        'charset': charset,
        'collation': collation
    }

    return client.begin_create_or_update(resource_group_name, server_name,
                                         database_name, parameters)
示例#10
0
def cf_communication_chat(cli_ctx, kwargs):
    from azure.communication.chat import ChatClient, CommunicationTokenCredential

    endpoint = kwargs.pop('endpoint', None)
    if endpoint is None:
        raise RequiredArgumentMissingError(
            'Please specify --endpoint, or set AZURE_COMMUNICATION_ENDPOINT.')

    token = kwargs.pop('access_token', None)
    if token is None:
        raise RequiredArgumentMissingError(
            'Please specify --access-token or set AZURE_COMMUNICATION_ACCESS_TOKEN.'
        )

    client = ChatClient(endpoint, CommunicationTokenCredential(token))
    return client
示例#11
0
def connection_validate(cmd,
                        client,
                        connection_name=None,
                        source_resource_group=None,
                        source_id=None,
                        indentifier=None,
                        cluster=None,
                        site=None,
                        spring=None,
                        app=None,
                        deployment='default'):
    if not source_id or not connection_name:
        raise RequiredArgumentMissingError(
            err_msg.format('--source-id, --connection'))

    # HACK: get linker first to infer target resource type so that user token can be
    # set to work around OBO
    linker = todict(
        client.get(resource_uri=source_id, linker_name=connection_name))
    target_id = linker.get('targetService', dict()).get('id', '')
    target_type = get_resource_type_by_id(target_id)
    source_type = get_source_resource_name(cmd)
    client = set_user_token_by_source_and_target(client, cmd.cli_ctx,
                                                 source_type, target_type)

    return auto_register(client.begin_validate,
                         resource_uri=source_id,
                         linker_name=connection_name)
示例#12
0
def generate_sas(client,
                 services,
                 resource_types,
                 permission,
                 expiry,
                 start=None,
                 ip=None,
                 protocol=None):
    from azure.cli.core.azclierror import RequiredArgumentMissingError
    if not client.account_name or not client.account_key:
        error_msg = """
        Missing/Invalid credentials to access storage service. The following variations are accepted:
            (1) account name and key (--account-name and --account-key options or
                set AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_KEY environment variables)
            (2) account name (--account-name option or AZURE_STORAGE_ACCOUNT environment variable;
                this will make calls to query for a storage account key using login credentials)
            (3) connection string (--connection-string option or
                set AZURE_STORAGE_CONNECTION_STRING environment variable); some shells will require
                quoting to preserve literal character interpretation.
        """
        raise RequiredArgumentMissingError(error_msg)
    return client.generate_shared_access_signature(services,
                                                   resource_types,
                                                   permission,
                                                   expiry,
                                                   start=start,
                                                   ip=ip,
                                                   protocol=protocol)
def flexible_server_provision_network_resource(cmd, resource_group_name, server_name,
                                               location, db_context, private_dns_zone_arguments=None, public_access=None,
                                               vnet=None, subnet=None, vnet_address_prefix=None, subnet_address_prefix=None, yes=False):
    start_ip = -1
    end_ip = -1
    network = mysql_flexibleservers.models.Network()

    if subnet is not None or vnet is not None:
        subnet_id = prepare_private_network(cmd,
                                            resource_group_name,
                                            server_name,
                                            vnet=vnet,
                                            subnet=subnet,
                                            location=location,
                                            delegation_service_name=DELEGATION_SERVICE_NAME,
                                            vnet_address_pref=vnet_address_prefix,
                                            subnet_address_pref=subnet_address_prefix,
                                            yes=yes)
        private_dns_zone_id = prepare_private_dns_zone(db_context,
                                                       'MySQL',
                                                       resource_group_name,
                                                       server_name,
                                                       private_dns_zone=private_dns_zone_arguments,
                                                       subnet_id=subnet_id,
                                                       location=location,
                                                       yes=yes)
        network.delegated_subnet_resource_id = subnet_id
        network.private_dns_zone_resource_id = private_dns_zone_id
    elif subnet is None and vnet is None and private_dns_zone_arguments is not None:
        raise RequiredArgumentMissingError("Private DNS zone can only be used with private access setting. Use vnet or/and subnet parameters.")
    else:
        start_ip, end_ip = prepare_public_network(public_access, yes=yes)

    return network, start_ip, end_ip
示例#14
0
def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file,
                             known_hosts, known_hosts_file, https_user,
                             https_key):

    scheme = urlparse(url).scheme
    if scheme.lower() in ('http', 'https'):
        if ssh_private_key or ssh_private_key_file:
            raise MutuallyExclusiveArgumentError(
                consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_ERROR,
                consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_HELP)
        if known_hosts or known_hosts_file:
            raise MutuallyExclusiveArgumentError(
                consts.KNOWN_HOSTS_WITH_HTTP_URL_ERROR,
                consts.KNOWN_HOSTS_WITH_HTTP_URL_HELP)
        if not (https_user and https_key) and scheme == 'https':
            logger.warning(consts.HTTP_URL_NO_AUTH_WARNING)
    else:
        if https_user or https_key:
            raise MutuallyExclusiveArgumentError(
                consts.HTTPS_AUTH_WITH_SSH_URL_ERROR,
                consts.HTTPS_AUTH_WITH_SSH_URL_HELP)

    if https_user and https_key:
        return
    # If we just provide one or the other raise an error
    if https_user or https_key:
        raise RequiredArgumentMissingError(consts.HTTPS_USER_KEY_MATCH_ERROR,
                                           consts.HTTPS_USER_KEY_MATCH_HELP)
示例#15
0
def _get_acr_from_image(cmd, app):
    if app.image is not None and "azurecr.io" in app.image:
        app.registry_server = app.image.split("/")[
            0]  # TODO what if this conflicts with registry_server param?
        parsed = urlparse(app.image)
        registry_name = (parsed.netloc
                         if parsed.scheme else parsed.path).split(".")[0]
        if app.registry_user is None or app.registry_pass is None:
            logger.info(
                "No credential was provided to access Azure Container Registry. Trying to look up..."
            )
            try:
                app.registry_user, app.registry_pass, registry_rg = _get_acr_cred(
                    cmd.cli_ctx, registry_name)
                app.acr = AzureContainerRegistry(
                    registry_name, ResourceGroup(cmd, registry_rg, None, None))
            except Exception as ex:
                raise RequiredArgumentMissingError(
                    "Failed to retrieve credentials for container registry. Please provide the registry username and password"
                ) from ex
        else:
            acr_rg = _get_acr_rg(app)
            app.acr = AzureContainerRegistry(
                name=registry_name,
                resource_group=ResourceGroup(app.cmd, acr_rg, None, None),
            )
    def _get_enable_pod_identity_with_kubenet(self, enable_validation: bool = False, **kwargs) -> bool:
        """Internal function to obtain the value of enable_pod_identity_with_kubenet.

        This function supports the option of enable_validation. When enabled, if network_profile has been set up in
        `mc`, network_plugin equals to "kubenet" and enable_pod_identity is specified but
        enable_pod_identity_with_kubenet is not, raise a RequiredArgumentMissingError.

        :return: bool
        """
        # read the original value passed by the command
        enable_pod_identity_with_kubenet = self.raw_param.get("enable_pod_identity_with_kubenet")
        # try to read the property value corresponding to the parameter from the `mc` object
        if (
            self.mc and
            self.mc.pod_identity_profile and
            self.mc.pod_identity_profile.allow_network_plugin_kubenet is not None
        ):
            enable_pod_identity_with_kubenet = self.mc.pod_identity_profile.allow_network_plugin_kubenet

        # this parameter does not need dynamic completion
        # validation
        if enable_validation:
            if self.mc and self.mc.network_profile and safe_lower(self.mc.network_profile.network_plugin) == "kubenet":
                if not enable_pod_identity_with_kubenet and self._get_enable_pod_identity(enable_validation=False):
                    raise RequiredArgumentMissingError(
                        "--enable-pod-identity-with-kubenet is required for enabling pod identity addon "
                        "when using Kubenet network plugin"
                    )
        return enable_pod_identity_with_kubenet
示例#17
0
def get_cluster_rp_api_version(cluster_type, cluster_rp=None) -> Tuple[str, str]:
    if cluster_type.lower() == consts.PROVISIONED_CLUSTER_TYPE:
        if cluster_rp is None or cluster_rp.strip() == "":
            raise RequiredArgumentMissingError(
                "Error! Cluster Resource Provider value is required for Cluster Type '{}'".format(cluster_type)
            )
        if cluster_rp.lower() == consts.HYBRIDCONTAINERSERVICE_RP:
            return (
                consts.HYBRIDCONTAINERSERVICE_RP,
                consts.HYBRIDCONTAINERSERVICE_API_VERSION,
            )
        raise InvalidArgumentValueError(
            "Error! Cluster type '{}' and Cluster Resource Provider '{}' combination is not supported".format(cluster_type, cluster_rp)
        )
    if cluster_type.lower() == consts.CONNECTED_CLUSTER_TYPE:
        return consts.CONNECTED_CLUSTER_RP, consts.CONNECTED_CLUSTER_API_VERSION
    if cluster_type.lower() == consts.APPLIANCE_TYPE:
        return consts.APPLIANCE_RP, consts.APPLIANCE_API_VERSION
    if (
        cluster_type.lower() == ""
        or cluster_type.lower() == consts.MANAGED_CLUSTER_TYPE
    ):
        return consts.MANAGED_CLUSTER_RP, consts.MANAGED_CLUSTER_API_VERSION
    raise InvalidArgumentValueError(
        "Error! Cluster type '{}' is not supported".format(cluster_type)
    )
示例#18
0
def apim_api_schema_create(client, resource_group_name, service_name, api_id, schema_id, schema_type,
                           schema_name=None, schema_path=None, schema_content=None,
                           resource_type=None, no_wait=False):
    """creates or updates an API Schema. """

    if schema_path is not None and schema_content is None:
        api_file = open(schema_path, 'r')
        content_value = api_file.read()
        value = content_value
    elif schema_content is not None and schema_path is None:
        value = schema_content
    elif schema_path is not None and schema_content is not None:
        raise MutuallyExclusiveArgumentError(
            "Can't specify schema_path and schema_content at the same time.")
    else:
        raise RequiredArgumentMissingError(
            "Please either specify schema_path or schema_content.")

    parameters = SchemaContract(
        id=schema_id,
        name=schema_name,
        type=resource_type,
        content_type=schema_type,
        value=value
    )

    return sdk_no_wait(no_wait, client.api_schema.begin_create_or_update,
                       resource_group_name=resource_group_name,
                       service_name=service_name, api_id=api_id, schema_id=schema_id, parameters=parameters)
示例#19
0
def require(values: Dict[str, str], key: str) -> str:
    '''Gets the required script execution parameter or raises a CLIError.'''
    value = values.get(key)
    if value is None:
        raise RequiredArgumentMissingError(
            'script execution parameter \'{}\' required'.format(key))
    return value
示例#20
0
def connection_validate(cmd,
                        client,
                        connection_name=None,
                        source_resource_group=None,
                        source_id=None,
                        indentifier=None,
                        site=None,
                        spring=None,
                        app=None,
                        deployment=None):
    import re
    from ._validators import get_resource_regex

    if not source_id or not connection_name:
        raise RequiredArgumentMissingError(
            err_msg.format('--source-id, --connection'))

    # HACK: get linker first to infer target resource type so that user token can be
    # set to work around OBO
    linker = todict(
        client.get(resource_uri=source_id, linker_name=connection_name))
    target_id = linker.get('targetId')
    for resource_type, resource_id in TARGET_RESOURCES.items():
        matched = re.match(get_resource_regex(resource_id), target_id,
                           re.IGNORECASE)
        if matched and resource_type in TARGET_RESOURCES_USERTOKEN:
            client = set_user_token_header(client, cmd.cli_ctx)

    return auto_register(client.begin_validate,
                         resource_uri=source_id,
                         linker_name=connection_name)
示例#21
0
def datamigration_assessment(connection_string=None,
                             output_folder=None,
                             overwrite=False,
                             config_file_path=None):

    try:

        defaultOutputFolder, exePath = helper.console_app_setup()

        if connection_string is not None and config_file_path is not None:
            raise MutuallyExclusiveArgumentError(
                "Both connection_string and config_file_path are mutually exclusive arguments. Please provide only one of these arguments."
            )

        if connection_string is not None:
            connection_string = " ".join(f"\"{i}\"" for i in connection_string)
            cmd = f'{exePath} Assess --sqlConnectionStrings {connection_string} ' if output_folder is None else f'{exePath} Assess --sqlConnectionStrings {connection_string} --outputFolder "{output_folder}" '
            cmd += '--overwrite False' if overwrite is False else ''
            subprocess.call(cmd, shell=False)
        elif config_file_path is not None:
            helper.validate_config_file_path(config_file_path, "assess")
            cmd = f'{exePath} --configFile "{config_file_path}"'
            subprocess.call(cmd, shell=False)
        else:
            raise RequiredArgumentMissingError(
                'No valid parameter set used. Please provide any one of the these prameters: connection_string, config_file_path'
            )

        # Printing log file path
        logFilePath = os.path.join(defaultOutputFolder, "Logs")
        print(f"Event and Error Logs Folder Path: {logFilePath}")

    except Exception as e:
        raise e
示例#22
0
def connect_to_server_helper(server_type,
                             endpoint,
                             default_db_name,
                             server_name,
                             administrator_login,
                             administrator_login_password,
                             database_name,
                             query_command=None,
                             interactive=None,
                             file_path=None):
    host = '{}{}'.format(server_name, endpoint)
    json_data = None

    # setup or validate passed in params:
    if database_name is None:
        database_name = default_db_name
        if database_name:  # in mysql scenario default db will be empty string
            logger.warning("Connecting to %s database by default.",
                           database_name)

    if administrator_login_password is None and interactive is None:
        raise RequiredArgumentMissingError(
            "Please provide password (--admin-password / -p) or "
            "run in --interactive mode.")

    # run in either interactive or simple connection mode
    if interactive is not None:
        if query_command is not None:
            logger.warning(
                "Ignoring query command passed in. Cannot run a query and interactive mode simultaneously. "
                "Please try running either a simple query using -q or run your query in interactive "
                "mode using --interactive.")

        _connect_interactive(server_type=server_type,
                             host=host,
                             server_name=server_name,
                             database_name=database_name,
                             login_username=administrator_login)

    elif file_path is None:
        json_data = _connect_execute_query(
            server_type=server_type,
            host=host,
            server_name=server_name,
            database_name=database_name,
            login_username=administrator_login,
            login_pw=administrator_login_password,
            query=query_command)

    if file_path is not None:
        _connect_execute_file(server_type=server_type,
                              host=host,
                              server_name=server_name,
                              database_name=database_name,
                              login_username=administrator_login,
                              login_pw=administrator_login_password,
                              file_path=file_path)

    return json_data
def validate_scope_after_customization(scope_obj):
    if (
        scope_obj is not None
        and scope_obj.namespace is not None
        and scope_obj.namespace.target_namespace is None
    ):
        message = "When --scope is 'namespace', --target-namespace must be given."
        raise RequiredArgumentMissingError(message)
示例#24
0
def validate_role_assignment_args(ns):
    if not any([
            ns.role_assignment_name, ns.scope, ns.assignee,
            ns.assignee_object_id, ns.role, ns.ids
    ]):
        raise RequiredArgumentMissingError(
            'Please specify at least one of these parameters: '
            '--name, --scope, --assignee, --assignee-object-id, --role, --ids')
示例#25
0
def raise_missing_token_suggestion():
    pat_documentation = "https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line"
    raise RequiredArgumentMissingError(
        "GitHub access token is required to authenticate to your repositories. "
        "If you need to create a Github Personal Access Token, "
        "please run with the '--login-with-github' flag or follow "
        "the steps found at the following link:\n{0}".format(
            pat_documentation))
def validate_only_equals_operator(args):
    if len(args) < 2:
        raise RequiredArgumentMissingError(
            'Filter Argument Error: values length can\'t be smaller than 2')
    if args[0].lower() not in ['equals', 'notequals']:
        raise InvalidArgumentValueError(
            'Filter Argument Error: operator must be one of the follows: Equals, NotEquals'
        )
示例#27
0
    def _validate_subnet(cmd, namespace):
        subnet = getattr(namespace, key)

        if not is_valid_resource_id(subnet):
            if not namespace.vnet:
                raise RequiredArgumentMissingError(
                    f"Must specify --vnet if --{key.replace('_', '-')} is not an id."
                )

            validate_vnet(cmd, namespace)

            subnet = namespace.vnet + '/subnets/' + subnet
            setattr(namespace, key, subnet)

        parts = parse_resource_id(subnet)

        if parts['subscription'] != get_subscription_id(cmd.cli_ctx):
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} subscription '{parts['subscription']}' must equal cluster subscription."
            )

        if parts['namespace'].lower() != 'microsoft.network':
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} namespace '{parts['namespace']}' must equal Microsoft.Network."
            )

        if parts['type'].lower() != 'virtualnetworks':
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} type '{parts['type']}' must equal virtualNetworks."
            )

        if parts['last_child_num'] != 1:
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} '{subnet}' must have one child.")

        if 'child_namespace_1' in parts:
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} '{subnet}' must not have child namespace."
            )

        if parts['child_type_1'].lower() != 'subnets':
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} child type '{subnet}' must equal subnets."
            )

        client = get_mgmt_service_client(cmd.cli_ctx,
                                         ResourceType.MGMT_NETWORK)
        try:
            client.subnets.get(parts['resource_group'], parts['name'],
                               parts['child_name_1'])
        except Exception as err:
            if isinstance(err, ResourceNotFoundError):
                raise InvalidArgumentValueError(
                    f"Invald --{key.replace('_', '-')}, error when getting '{subnet}': {str(err)}"
                ) from err
            raise CLIInternalError(
                f"Unexpected error when getting subnet '{subnet}': {str(err)}"
            ) from err
示例#28
0
def list_offerings(cmd, location=None):
    """
    Get the list of all provider offerings available on the given location.
    """
    if (not location):
        raise RequiredArgumentMissingError(
            "A location is required to list offerings available.")
    client = cf_offerings(cmd.cli_ctx)
    return client.list(location_name=location)
 def validate(self):
     super().validate_required_params(**self.kwargs)
     validate_bucket_url(self.url)
     if not ((self.bucket_access_key and self.bucket_secret_key)
             or self.local_auth_ref):
         raise RequiredArgumentMissingError(
             consts.REQUIRED_BUCKET_VALUES_MISSING_ERROR,
             consts.REQUIRED_BUCKET_VALUES_MISSING_HELP,
         )
示例#30
0
def validate_client_id(namespace):
    if namespace.client_id is not None:
        try:
            uuid.UUID(namespace.client_id)
        except ValueError:
            raise InvalidArgumentValueError("Invalid --client-id '%s'." % namespace.client_id)

        if namespace.client_secret is None or not str(namespace.client_secret):
            raise RequiredArgumentMissingError('Must specify --client-secret with --client-id.')